comment
stringlengths
1
45k
method_body
stringlengths
23
281k
target_code
stringlengths
0
5.16k
method_body_after
stringlengths
12
281k
context_before
stringlengths
8
543k
context_after
stringlengths
8
543k
should the string "transitive" be replaced with a final transitive here?
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new IllegalArgumentException("One of the User Group Properties must be populated. " + "Please populate azure.activedirectory.user-group.allowed-groups"); } if (!DEFAULT_GROUP_RELATIONSHIP.equalsIgnoreCase(groupRelationship) && !"transitive".equalsIgnoreCase(groupRelationship)) { throw new IllegalArgumentException("Configuration 'azure.activedirectory.group-relationship' " + "should be 'direct' or 'transitive'."); } }
&& !"transitive".equalsIgnoreCase(groupRelationship)) {
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new IllegalArgumentException("One of the User Group Properties must be populated. " + "Please populate azure.activedirectory.user-group.allowed-groups"); } if (!GROUP_RELATIONSHIP_DIRECT.equalsIgnoreCase(userGroup.groupRelationship) && !GROUP_RELATIONSHIP_TRANSITIVE.equalsIgnoreCase(userGroup.groupRelationship)) { throw new IllegalArgumentException("Configuration 'azure.activedirectory.user-group.group-relationship' " + "should be 'direct' or 'transitive'."); } }
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azure AD response object that will be checked to contain the {@code * azure.activedirectory.user-group.value} to signify that this node is a valid {@code UserGroup}. */ @NotEmpty private String key = "objectType"; /** * Value of the JSON Node identified by the {@code azure.activedirectory.user-group.key} to validate the JSON * Node is a UserGroup. */ @NotEmpty private String value = Membership.OBJECT_TYPE_GROUP; /** * Key of the JSON Node containing the Azure Object ID for the {@code UserGroup}. */ @NotEmpty private String objectIDKey = "objectId"; public List<String> getAllowedGroups() { return allowedGroups; } public void setAllowedGroups(List<String> allowedGroups) { this.allowedGroups = allowedGroups; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getObjectIDKey() { return objectIDKey; } public void setObjectIDKey(String objectIDKey) { this.objectIDKey = objectIDKey; } @Override public String toString() { return "UserGroupProperties{" + "allowedGroups=" + allowedGroups + ", key='" + key + '\'' + ", value='" + value + '\'' + ", objectIDKey='" + objectIDKey + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserGroupProperties that = (UserGroupProperties) o; return Objects.equals(allowedGroups, that.allowedGroups) && Objects.equals(key, that.key) && Objects.equals(value, that.value) && Objects.equals(objectIDKey, that.objectIDKey); } @Override public int hashCode() { return Objects.hash(allowedGroups, key, value, objectIDKey); } }
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azure AD response object that will be checked to contain the {@code * azure.activedirectory.user-group.value} to signify that this node is a valid {@code UserGroup}. */ @NotEmpty private String key = "objectType"; /** * Value of the JSON Node identified by the {@code azure.activedirectory.user-group.key} to validate the JSON * Node is a UserGroup. */ @NotEmpty private String value = Membership.OBJECT_TYPE_GROUP; /** * Key of the JSON Node containing the Azure Object ID for the {@code UserGroup}. */ @NotEmpty private String objectIDKey = "objectId"; /** * The way to obtain group relationship.<br/> * direct: the default value, get groups that the user is a direct member of;<br/> * transitive: Get groups that the user is a member of, and will also return all * groups the user is a nested member of; */ @NotEmpty private String groupRelationship = GROUP_RELATIONSHIP_DIRECT; public List<String> getAllowedGroups() { return allowedGroups; } public void setAllowedGroups(List<String> allowedGroups) { this.allowedGroups = allowedGroups; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getObjectIDKey() { return objectIDKey; } public void setObjectIDKey(String objectIDKey) { this.objectIDKey = objectIDKey; } public String getGroupRelationship() { return groupRelationship; } public void setGroupRelationship(String groupRelationship) { this.groupRelationship = groupRelationship; } @Override public String toString() { return "UserGroupProperties{" + "allowedGroups=" + allowedGroups + ", key='" + key + '\'' + ", value='" + value + '\'' + ", objectIDKey='" + objectIDKey + '\'' + ", groupRelationship='" + groupRelationship + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserGroupProperties that = (UserGroupProperties) o; return Objects.equals(allowedGroups, that.allowedGroups) && Objects.equals(key, that.key) && Objects.equals(value, that.value) && Objects.equals(objectIDKey, that.objectIDKey) && Objects.equals(groupRelationship, that.groupRelationship); } @Override public int hashCode() { return Objects.hash(allowedGroups, key, value, objectIDKey); } }
Why don't we have a static variable for this one?
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new IllegalArgumentException("One of the User Group Properties must be populated. " + "Please populate azure.activedirectory.user-group.allowed-groups"); } if (!DEFAULT_GROUP_RELATIONSHIP.equalsIgnoreCase(groupRelationship) && !"transitive".equalsIgnoreCase(groupRelationship)) { throw new IllegalArgumentException("Configuration 'azure.activedirectory.group-relationship' " + "should be 'direct' or 'transitive'."); } }
&& !"transitive".equalsIgnoreCase(groupRelationship)) {
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new IllegalArgumentException("One of the User Group Properties must be populated. " + "Please populate azure.activedirectory.user-group.allowed-groups"); } if (!GROUP_RELATIONSHIP_DIRECT.equalsIgnoreCase(userGroup.groupRelationship) && !GROUP_RELATIONSHIP_TRANSITIVE.equalsIgnoreCase(userGroup.groupRelationship)) { throw new IllegalArgumentException("Configuration 'azure.activedirectory.user-group.group-relationship' " + "should be 'direct' or 'transitive'."); } }
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azure AD response object that will be checked to contain the {@code * azure.activedirectory.user-group.value} to signify that this node is a valid {@code UserGroup}. */ @NotEmpty private String key = "objectType"; /** * Value of the JSON Node identified by the {@code azure.activedirectory.user-group.key} to validate the JSON * Node is a UserGroup. */ @NotEmpty private String value = Membership.OBJECT_TYPE_GROUP; /** * Key of the JSON Node containing the Azure Object ID for the {@code UserGroup}. */ @NotEmpty private String objectIDKey = "objectId"; public List<String> getAllowedGroups() { return allowedGroups; } public void setAllowedGroups(List<String> allowedGroups) { this.allowedGroups = allowedGroups; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getObjectIDKey() { return objectIDKey; } public void setObjectIDKey(String objectIDKey) { this.objectIDKey = objectIDKey; } @Override public String toString() { return "UserGroupProperties{" + "allowedGroups=" + allowedGroups + ", key='" + key + '\'' + ", value='" + value + '\'' + ", objectIDKey='" + objectIDKey + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserGroupProperties that = (UserGroupProperties) o; return Objects.equals(allowedGroups, that.allowedGroups) && Objects.equals(key, that.key) && Objects.equals(value, that.value) && Objects.equals(objectIDKey, that.objectIDKey); } @Override public int hashCode() { return Objects.hash(allowedGroups, key, value, objectIDKey); } }
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azure AD response object that will be checked to contain the {@code * azure.activedirectory.user-group.value} to signify that this node is a valid {@code UserGroup}. */ @NotEmpty private String key = "objectType"; /** * Value of the JSON Node identified by the {@code azure.activedirectory.user-group.key} to validate the JSON * Node is a UserGroup. */ @NotEmpty private String value = Membership.OBJECT_TYPE_GROUP; /** * Key of the JSON Node containing the Azure Object ID for the {@code UserGroup}. */ @NotEmpty private String objectIDKey = "objectId"; /** * The way to obtain group relationship.<br/> * direct: the default value, get groups that the user is a direct member of;<br/> * transitive: Get groups that the user is a member of, and will also return all * groups the user is a nested member of; */ @NotEmpty private String groupRelationship = GROUP_RELATIONSHIP_DIRECT; public List<String> getAllowedGroups() { return allowedGroups; } public void setAllowedGroups(List<String> allowedGroups) { this.allowedGroups = allowedGroups; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getObjectIDKey() { return objectIDKey; } public void setObjectIDKey(String objectIDKey) { this.objectIDKey = objectIDKey; } public String getGroupRelationship() { return groupRelationship; } public void setGroupRelationship(String groupRelationship) { this.groupRelationship = groupRelationship; } @Override public String toString() { return "UserGroupProperties{" + "allowedGroups=" + allowedGroups + ", key='" + key + '\'' + ", value='" + value + '\'' + ", objectIDKey='" + objectIDKey + '\'' + ", groupRelationship='" + groupRelationship + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserGroupProperties that = (UserGroupProperties) o; return Objects.equals(allowedGroups, that.allowedGroups) && Objects.equals(key, that.key) && Objects.equals(value, that.value) && Objects.equals(objectIDKey, that.objectIDKey) && Objects.equals(groupRelationship, that.groupRelationship); } @Override public int hashCode() { return Objects.hash(allowedGroups, key, value, objectIDKey); } }
Will add another one.
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new IllegalArgumentException("One of the User Group Properties must be populated. " + "Please populate azure.activedirectory.user-group.allowed-groups"); } if (!DEFAULT_GROUP_RELATIONSHIP.equalsIgnoreCase(groupRelationship) && !"transitive".equalsIgnoreCase(groupRelationship)) { throw new IllegalArgumentException("Configuration 'azure.activedirectory.group-relationship' " + "should be 'direct' or 'transitive'."); } }
&& !"transitive".equalsIgnoreCase(groupRelationship)) {
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new IllegalArgumentException("One of the User Group Properties must be populated. " + "Please populate azure.activedirectory.user-group.allowed-groups"); } if (!GROUP_RELATIONSHIP_DIRECT.equalsIgnoreCase(userGroup.groupRelationship) && !GROUP_RELATIONSHIP_TRANSITIVE.equalsIgnoreCase(userGroup.groupRelationship)) { throw new IllegalArgumentException("Configuration 'azure.activedirectory.user-group.group-relationship' " + "should be 'direct' or 'transitive'."); } }
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azure AD response object that will be checked to contain the {@code * azure.activedirectory.user-group.value} to signify that this node is a valid {@code UserGroup}. */ @NotEmpty private String key = "objectType"; /** * Value of the JSON Node identified by the {@code azure.activedirectory.user-group.key} to validate the JSON * Node is a UserGroup. */ @NotEmpty private String value = Membership.OBJECT_TYPE_GROUP; /** * Key of the JSON Node containing the Azure Object ID for the {@code UserGroup}. */ @NotEmpty private String objectIDKey = "objectId"; public List<String> getAllowedGroups() { return allowedGroups; } public void setAllowedGroups(List<String> allowedGroups) { this.allowedGroups = allowedGroups; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getObjectIDKey() { return objectIDKey; } public void setObjectIDKey(String objectIDKey) { this.objectIDKey = objectIDKey; } @Override public String toString() { return "UserGroupProperties{" + "allowedGroups=" + allowedGroups + ", key='" + key + '\'' + ", value='" + value + '\'' + ", objectIDKey='" + objectIDKey + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserGroupProperties that = (UserGroupProperties) o; return Objects.equals(allowedGroups, that.allowedGroups) && Objects.equals(key, that.key) && Objects.equals(value, that.value) && Objects.equals(objectIDKey, that.objectIDKey); } @Override public int hashCode() { return Objects.hash(allowedGroups, key, value, objectIDKey); } }
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azure AD response object that will be checked to contain the {@code * azure.activedirectory.user-group.value} to signify that this node is a valid {@code UserGroup}. */ @NotEmpty private String key = "objectType"; /** * Value of the JSON Node identified by the {@code azure.activedirectory.user-group.key} to validate the JSON * Node is a UserGroup. */ @NotEmpty private String value = Membership.OBJECT_TYPE_GROUP; /** * Key of the JSON Node containing the Azure Object ID for the {@code UserGroup}. */ @NotEmpty private String objectIDKey = "objectId"; /** * The way to obtain group relationship.<br/> * direct: the default value, get groups that the user is a direct member of;<br/> * transitive: Get groups that the user is a member of, and will also return all * groups the user is a nested member of; */ @NotEmpty private String groupRelationship = GROUP_RELATIONSHIP_DIRECT; public List<String> getAllowedGroups() { return allowedGroups; } public void setAllowedGroups(List<String> allowedGroups) { this.allowedGroups = allowedGroups; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getObjectIDKey() { return objectIDKey; } public void setObjectIDKey(String objectIDKey) { this.objectIDKey = objectIDKey; } public String getGroupRelationship() { return groupRelationship; } public void setGroupRelationship(String groupRelationship) { this.groupRelationship = groupRelationship; } @Override public String toString() { return "UserGroupProperties{" + "allowedGroups=" + allowedGroups + ", key='" + key + '\'' + ", value='" + value + '\'' + ", objectIDKey='" + objectIDKey + '\'' + ", groupRelationship='" + groupRelationship + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserGroupProperties that = (UserGroupProperties) o; return Objects.equals(allowedGroups, that.allowedGroups) && Objects.equals(key, that.key) && Objects.equals(value, that.value) && Objects.equals(objectIDKey, that.objectIDKey) && Objects.equals(groupRelationship, that.groupRelationship); } @Override public int hashCode() { return Objects.hash(allowedGroups, key, value, objectIDKey); } }
Okay
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new IllegalArgumentException("One of the User Group Properties must be populated. " + "Please populate azure.activedirectory.user-group.allowed-groups"); } if (!DEFAULT_GROUP_RELATIONSHIP.equalsIgnoreCase(groupRelationship) && !"transitive".equalsIgnoreCase(groupRelationship)) { throw new IllegalArgumentException("Configuration 'azure.activedirectory.group-relationship' " + "should be 'direct' or 'transitive'."); } }
throw new IllegalArgumentException("Configuration 'azure.activedirectory.group-relationship' "
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new IllegalArgumentException("One of the User Group Properties must be populated. " + "Please populate azure.activedirectory.user-group.allowed-groups"); } if (!GROUP_RELATIONSHIP_DIRECT.equalsIgnoreCase(userGroup.groupRelationship) && !GROUP_RELATIONSHIP_TRANSITIVE.equalsIgnoreCase(userGroup.groupRelationship)) { throw new IllegalArgumentException("Configuration 'azure.activedirectory.user-group.group-relationship' " + "should be 'direct' or 'transitive'."); } }
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azure AD response object that will be checked to contain the {@code * azure.activedirectory.user-group.value} to signify that this node is a valid {@code UserGroup}. */ @NotEmpty private String key = "objectType"; /** * Value of the JSON Node identified by the {@code azure.activedirectory.user-group.key} to validate the JSON * Node is a UserGroup. */ @NotEmpty private String value = Membership.OBJECT_TYPE_GROUP; /** * Key of the JSON Node containing the Azure Object ID for the {@code UserGroup}. */ @NotEmpty private String objectIDKey = "objectId"; public List<String> getAllowedGroups() { return allowedGroups; } public void setAllowedGroups(List<String> allowedGroups) { this.allowedGroups = allowedGroups; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getObjectIDKey() { return objectIDKey; } public void setObjectIDKey(String objectIDKey) { this.objectIDKey = objectIDKey; } @Override public String toString() { return "UserGroupProperties{" + "allowedGroups=" + allowedGroups + ", key='" + key + '\'' + ", value='" + value + '\'' + ", objectIDKey='" + objectIDKey + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserGroupProperties that = (UserGroupProperties) o; return Objects.equals(allowedGroups, that.allowedGroups) && Objects.equals(key, that.key) && Objects.equals(value, that.value) && Objects.equals(objectIDKey, that.objectIDKey); } @Override public int hashCode() { return Objects.hash(allowedGroups, key, value, objectIDKey); } }
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azure AD response object that will be checked to contain the {@code * azure.activedirectory.user-group.value} to signify that this node is a valid {@code UserGroup}. */ @NotEmpty private String key = "objectType"; /** * Value of the JSON Node identified by the {@code azure.activedirectory.user-group.key} to validate the JSON * Node is a UserGroup. */ @NotEmpty private String value = Membership.OBJECT_TYPE_GROUP; /** * Key of the JSON Node containing the Azure Object ID for the {@code UserGroup}. */ @NotEmpty private String objectIDKey = "objectId"; /** * The way to obtain group relationship.<br/> * direct: the default value, get groups that the user is a direct member of;<br/> * transitive: Get groups that the user is a member of, and will also return all * groups the user is a nested member of; */ @NotEmpty private String groupRelationship = GROUP_RELATIONSHIP_DIRECT; public List<String> getAllowedGroups() { return allowedGroups; } public void setAllowedGroups(List<String> allowedGroups) { this.allowedGroups = allowedGroups; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getObjectIDKey() { return objectIDKey; } public void setObjectIDKey(String objectIDKey) { this.objectIDKey = objectIDKey; } public String getGroupRelationship() { return groupRelationship; } public void setGroupRelationship(String groupRelationship) { this.groupRelationship = groupRelationship; } @Override public String toString() { return "UserGroupProperties{" + "allowedGroups=" + allowedGroups + ", key='" + key + '\'' + ", value='" + value + '\'' + ", objectIDKey='" + objectIDKey + '\'' + ", groupRelationship='" + groupRelationship + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserGroupProperties that = (UserGroupProperties) o; return Objects.equals(allowedGroups, that.allowedGroups) && Objects.equals(key, that.key) && Objects.equals(value, that.value) && Objects.equals(objectIDKey, that.objectIDKey) && Objects.equals(groupRelationship, that.groupRelationship); } @Override public int hashCode() { return Objects.hash(allowedGroups, key, value, objectIDKey); } }
this shows business card
public void beginRecognizeInvoices() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, invoice.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); }
formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, invoice.length())
public void beginRecognizeInvoices() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()))); formRecognizerAsyncClient.beginRecognizeInvoices(buffer, invoice.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String formUrl = "{formUrl}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldName, formField) -> { System.out.printf("Field text: %s%n", fieldName); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options */ public void beginRecognizeContentFromUrlWithOptions() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(), new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{receiptUrl}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receiptUrl}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setFieldElementsIncluded(includeFieldElements) .setLocale("en-US") .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedReceipt = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setLocale("en-US") .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.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()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.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()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.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()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.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()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrl() { String invoiceUrl = "invoice_url"; formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrlWithOptions() { String invoiceUrl = "invoice_url"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl, new RecognizeInvoicesOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeInvoicesWithOptions() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()))); formRecognizerAsyncClient.beginRecognizeInvoices(buffer, invoice.length(), new RecognizeInvoicesOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String formUrl = "{formUrl}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldName, formField) -> { System.out.printf("Field text: %s%n", fieldName); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options */ public void beginRecognizeContentFromUrlWithOptions() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(), new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{receiptUrl}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receiptUrl}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setFieldElementsIncluded(includeFieldElements) .setLocale("en-US") .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedReceipt = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setLocale("en-US") .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.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()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.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()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.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()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.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()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrl() { String invoiceUrl = "invoice_url"; formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrlWithOptions() { String invoiceUrl = "invoice_url"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl, new RecognizeInvoicesOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeInvoicesWithOptions() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()))); formRecognizerAsyncClient.beginRecognizeInvoices(buffer, invoice.length(), new RecognizeInvoicesOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedInvoices -> { for (int i = 0; i < recognizedInvoices.size(); i++) { RecognizedForm recognizedForm = recognizedInvoices.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } } }); } }
business cards here
public void beginRecognizeInvoices() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath())); formRecognizerClient.beginRecognizeBusinessCards(inputStream, invoice.length()) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(recognizedFields -> { FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } }); }
formRecognizerClient.beginRecognizeBusinessCards(inputStream, invoice.length())
public void beginRecognizeInvoices() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath())); formRecognizerClient.beginRecognizeInvoices(inputStream, invoice.length()) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(recognizedFields -> { FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } }); }
class FormRecognizerClientJavaDocCodeSnippets { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); /** * Code snippet for creating a {@link FormRecognizerClient} */ public void createFormRecognizerClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for creating a {@link FormRecognizerClient} with pipeline */ public void createFormRecognizerClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildClient(); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length()) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{form_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formUrl) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * options. */ public void beginRecognizeContentFromUrlWithOptions() { String formPath = "{file_source_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formPath, new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.pdf}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeContent(targetStream, form.length()) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } } /** * Code snippet for {@link FormRecognizerClient * options. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{file_source_url}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(), new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); } } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl) .getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receipt_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setLocale("en-US") .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE) .getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{receipt_url}"); byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } } /** * Code snippet for {@link FormRecognizerClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setLocale("en-US") .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); 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()); } }); } } }); } /** * Code snippet for * {@link FormRecognizerClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); 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()); } }); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); 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()); } }); } } }); } } /** * Code snippet for * {@link FormRecognizerClient * Context)} with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); 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()); } }); } } } } } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrl() { String invoiceUrl = "invoice_url"; formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(recognizedFields -> { FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrlWithOptions() { String invoiceUrl = "invoice_url"; boolean includeFieldElements = true; formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl, new RecognizeInvoicesOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(recognizedFields -> { FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeInvoicesWithOptions() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); boolean includeFieldElements = true; ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath())); formRecognizerClient.beginRecognizeInvoices(inputStream, invoice.length(), new RecognizeInvoicesOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(recognizedFields -> { FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } }); } }
class FormRecognizerClientJavaDocCodeSnippets { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); /** * Code snippet for creating a {@link FormRecognizerClient} */ public void createFormRecognizerClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for creating a {@link FormRecognizerClient} with pipeline */ public void createFormRecognizerClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildClient(); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length()) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{form_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formUrl) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * options. */ public void beginRecognizeContentFromUrlWithOptions() { String formPath = "{file_source_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formPath, new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.pdf}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeContent(targetStream, form.length()) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } } /** * Code snippet for {@link FormRecognizerClient * options. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{file_source_url}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(), new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); } } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl) .getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receipt_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setLocale("en-US") .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE) .getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{receipt_url}"); byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } } /** * Code snippet for {@link FormRecognizerClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setLocale("en-US") .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); 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()); } }); } } }); } /** * Code snippet for * {@link FormRecognizerClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); 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()); } }); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); 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()); } }); } } }); } } /** * Code snippet for * {@link FormRecognizerClient * Context)} with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); 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()); } }); } } } } } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrl() { String invoiceUrl = "invoice_url"; formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(recognizedFields -> { FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeInvoicesFromUrlWithOptions() { String invoiceUrl = "invoice_url"; boolean includeFieldElements = true; formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl, new RecognizeInvoicesOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(recognizedFields -> { FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeInvoicesWithOptions() throws IOException { File invoice = new File("local/file_path/invoice.jpg"); boolean includeFieldElements = true; ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath())); formRecognizerClient.beginRecognizeInvoices(inputStream, invoice.length(), new RecognizeInvoicesOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(recognizedFields -> { FormField customAddrFormField = recognizedFields.get("CustomerAddress"); if (customAddrFormField != null) { if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) { System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString()); } } FormField invoiceDateFormField = recognizedFields.get("InvoiceDate"); if (invoiceDateFormField != null) { if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) { LocalDate invoiceDate = invoiceDateFormField.getValue().asDate(); System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateFormField.getConfidence()); } } }); } }
Invoice recognition is returning pageResults with null tables. So needed to add this to avoid NPE.
static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } }
if (pageResultItem.getTables() == null) {
static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId, boolean isBusinessCard) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults, isBusinessCard); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = null; if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults, isBusinessCard)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults, boolean isBusinessCard) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults, isBusinessCard), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults, isBusinessCard), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults, isBusinessCard) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@link FormField}. */ private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults, boolean isBusinessCard) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && OBJECT != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } else if (isBusinessCard && OBJECT.equals(fieldValue.getType())) { if (fieldValue.getValueObject().get("FirstName") != null && fieldValue.getValueObject().get("LastName") != null) { if (fieldValue.getValueObject().get("FirstName").getPage() .equals(fieldValue.getValueObject().get("LastName").getPage())) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getValueObject().get("FirstName").getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } } } return setFormField(null, valueData, fieldValue, readResults, isBusinessCard); }) .collect(Collectors.toList()); } /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId, boolean isBusinessCard) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults, isBusinessCard); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = null; if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults, isBusinessCard)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults, boolean isBusinessCard) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults, isBusinessCard), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults, isBusinessCard), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults, isBusinessCard) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@link FormField}. */ private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults, boolean isBusinessCard) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && OBJECT != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } else if (isBusinessCard && OBJECT.equals(fieldValue.getType())) { if (fieldValue.getValueObject().get("FirstName") != null && fieldValue.getValueObject().get("LastName") != null) { if (fieldValue.getValueObject().get("FirstName").getPage() .equals(fieldValue.getValueObject().get("LastName").getPage())) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getValueObject().get("FirstName").getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } } } return setFormField(null, valueData, fieldValue, readResults, isBusinessCard); }) .collect(Collectors.toList()); } /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
just curious, what drove this change?
static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } }
if (pageResultItem.getTables() == null) {
static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId, boolean isBusinessCard) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults, isBusinessCard); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = null; if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults, isBusinessCard)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults, boolean isBusinessCard) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults, isBusinessCard), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults, isBusinessCard), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults, isBusinessCard) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@link FormField}. */ private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults, boolean isBusinessCard) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && OBJECT != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } else if (isBusinessCard && OBJECT.equals(fieldValue.getType())) { if (fieldValue.getValueObject().get("FirstName") != null && fieldValue.getValueObject().get("LastName") != null) { if (fieldValue.getValueObject().get("FirstName").getPage() .equals(fieldValue.getValueObject().get("LastName").getPage())) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getValueObject().get("FirstName").getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } } } return setFormField(null, valueData, fieldValue, readResults, isBusinessCard); }) .collect(Collectors.toList()); } /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId, boolean isBusinessCard) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults, isBusinessCard); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = null; if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults, isBusinessCard)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults, boolean isBusinessCard) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults, isBusinessCard), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults, isBusinessCard), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults, isBusinessCard) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@link FormField}. */ private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults, boolean isBusinessCard) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && OBJECT != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } else if (isBusinessCard && OBJECT.equals(fieldValue.getType())) { if (fieldValue.getValueObject().get("FirstName") != null && fieldValue.getValueObject().get("LastName") != null) { if (fieldValue.getValueObject().get("FirstName").getPage() .equals(fieldValue.getValueObject().get("LastName").getPage())) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getValueObject().get("FirstName").getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } } } return setFormField(null, valueData, fieldValue, readResults, isBusinessCard); }) .collect(Collectors.toList()); } /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
ohh yes that is right. Thank you :)
static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } }
if (pageResultItem.getTables() == null) {
static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId, boolean isBusinessCard) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults, isBusinessCard); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = null; if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults, isBusinessCard)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults, boolean isBusinessCard) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults, isBusinessCard), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults, isBusinessCard), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults, isBusinessCard) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@link FormField}. */ private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults, boolean isBusinessCard) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && OBJECT != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } else if (isBusinessCard && OBJECT.equals(fieldValue.getType())) { if (fieldValue.getValueObject().get("FirstName") != null && fieldValue.getValueObject().get("LastName") != null) { if (fieldValue.getValueObject().get("FirstName").getPage() .equals(fieldValue.getValueObject().get("LastName").getPage())) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getValueObject().get("FirstName").getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } } } return setFormField(null, valueData, fieldValue, readResults, isBusinessCard); }) .collect(Collectors.toList()); } /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId, boolean isBusinessCard) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults, isBusinessCard); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = null; if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults, isBusinessCard)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults, boolean isBusinessCard) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults, isBusinessCard), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults, isBusinessCard), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState = null; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults, boolean isBusinessCard) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults, isBusinessCard) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @param isBusinessCard boolean indicating if its recognizing a business card. * @return The List of {@link FormField}. */ private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults, boolean isBusinessCard) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && OBJECT != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } else if (isBusinessCard && OBJECT.equals(fieldValue.getType())) { if (fieldValue.getValueObject().get("FirstName") != null && fieldValue.getValueObject().get("LastName") != null) { if (fieldValue.getValueObject().get("FirstName").getPage() .equals(fieldValue.getValueObject().get("LastName").getPage())) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getValueObject().get("FirstName").getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } } } return setFormField(null, valueData, fieldValue, readResults, isBusinessCard); }) .collect(Collectors.toList()); } /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
We should use `generateResourceId()` for the key name since it generates a randomized value, which helps when running live tests. ```suggestion final CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions(generateResourceId(KEY_NAME)) ```
void createRsaKeyRunner(Consumer<CreateRsaKeyOptions> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("foo", "baz"); final CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions(KEY_NAME) .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags); testRunner.accept(createRsaKeyOptions); }
final CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions(KEY_NAME)
void createRsaKeyRunner(Consumer<CreateRsaKeyOptions> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("foo", "baz"); final CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions(generateResourceId(KEY_NAME)) .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags); testRunner.accept(createRsaKeyOptions); }
class KeyClientTestBase extends TestBase { private static final String KEY_NAME = "javaKeyTemp"; private static final KeyType RSA_KEY_TYPE = KeyType.RSA; private static final KeyType EC_KEY_TYPE = KeyType.EC; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_KEYS_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_KEYS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_KEYS_SERVICE_VERSIONS); @Override protected String getTestName() { return ""; } void beforeTestSetup() { } HttpPipeline getHttpPipeline(HttpClient httpClient, KeyServiceVersion serviceVersion) { TokenCredential credential = null; if (!interceptorManager.isPlaybackMode()) { String clientId = System.getenv("ARM_CLIENTID"); String clientKey = System.getenv("ARM_CLIENTKEY"); String tenantId = System.getenv("AZURE_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .build(); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone(), serviceVersion)); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new BearerTokenAuthenticationPolicy(credential, KeyAsyncClient.KEY_VAULT_SCOPE)); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (getTestMode() == TestMode.RECORD) { policies.add(interceptorManager.getRecordPolicy()); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; } @Test public abstract void setKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void setKeyRunner(Consumer<CreateKeyOptions> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("foo", "baz"); final CreateKeyOptions keyOptions = new CreateKeyOptions(generateResourceId(KEY_NAME), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags); testRunner.accept(keyOptions); } @Test public abstract void createRsaKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void setKeyNullType(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void setKeyEmptyValueRunner(Consumer<CreateKeyOptions> testRunner) { CreateKeyOptions key = new CreateKeyOptions(KEY_NAME, null); testRunner.accept(key); } @Test public abstract void setKeyNull(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void updateKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void updateKeyRunner(BiConsumer<CreateKeyOptions, CreateKeyOptions> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); final String keyName = generateResourceId("testKey1"); final CreateKeyOptions originalKey = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags); final CreateKeyOptions updatedKey = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags); testRunner.accept(originalKey, updatedKey); } @Test public abstract void updateDisabledKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void updateDisabledKeyRunner(BiConsumer<CreateKeyOptions, CreateKeyOptions> testRunner) { final Map<String, String> tags = new HashMap<>(); final String keyName = generateResourceId("testKey2"); final CreateKeyOptions originalKey = new CreateKeyOptions(keyName, EC_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false); final CreateKeyOptions updatedKey = new CreateKeyOptions(keyName, EC_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(originalKey, updatedKey); } @Test public abstract void getKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void getKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions originalKey = new CreateKeyOptions(generateResourceId("testKey4"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(originalKey); } @Test public abstract void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void getKeySpecificVersionRunner(BiConsumer<CreateKeyOptions, CreateKeyOptions> testRunner) { final String keyName = generateResourceId("testKey3"); final CreateKeyOptions key = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); final CreateKeyOptions keyWithNewVal = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(key, keyWithNewVal); } @Test public abstract void getKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void deleteKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void deleteKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToDelete = new CreateKeyOptions(generateResourceId("testKey5"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToDelete); } @Test public abstract void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void getDeletedKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void getDeletedKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToDeleteAndGet = new CreateKeyOptions(generateResourceId("testKey6"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToDeleteAndGet); } @Test public abstract void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void recoverDeletedKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToDeleteAndRecover = new CreateKeyOptions(generateResourceId("testKey7"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToDeleteAndRecover); } @Test public abstract void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void backupKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void backupKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToBackup = new CreateKeyOptions(generateResourceId("testKey8"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToBackup); } @Test public abstract void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void restoreKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void restoreKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToBackupAndRestore = new CreateKeyOptions(generateResourceId("testKey9"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToBackupAndRestore); } @Test public abstract void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void listKeys(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void listKeysRunner(Consumer<HashMap<String, CreateKeyOptions>> testRunner) { HashMap<String, CreateKeyOptions> keys = new HashMap<>(); String keyName; for (int i = 0; i < 2; i++) { keyName = generateResourceId("listKey" + i); CreateKeyOptions key = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); keys.put(keyName, key); } testRunner.accept(keys); } @Test public abstract void listKeyVersions(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void listKeyVersionsRunner(Consumer<List<CreateKeyOptions>> testRunner) { List<CreateKeyOptions> keys = new ArrayList<>(); String keyName = generateResourceId("listKeyVersion"); for (int i = 1; i < 5; i++) { keys.add(new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC))); } testRunner.accept(keys); } @Test public abstract void listDeletedKeys(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void listDeletedKeysRunner(Consumer<HashMap<String, CreateKeyOptions>> testRunner) { HashMap<String, CreateKeyOptions> keys = new HashMap<>(); String keyName; for (int i = 0; i < 3; i++) { keyName = generateResourceId("listDeletedKeysTest" + i); keys.put(keyName, new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); } testRunner.accept(keys); } String generateResourceId(String suffix) { if (interceptorManager.isPlaybackMode()) { return suffix; } String id = UUID.randomUUID().toString(); return suffix.length() > 0 ? id + "-" + suffix : id; } /** * Helper method to verify that the Response matches what was expected. This method assumes a response status of 200. * * @param expected Key expected to be returned by the service * @param response Response returned by the service, the body should contain a Key */ static void assertKeyEquals(CreateKeyOptions expected, Response<KeyVaultKey> response) { assertKeyEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertKeyEquals(CreateKeyOptions expected, Response<KeyVaultKey> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertKeyEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertKeyEquals(CreateKeyOptions expected, KeyVaultKey actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getKeyType(), actual.getKey().getKeyType()); assertEquals(expected.getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "http: : System.getenv("AZURE_KEYVAULT_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 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(KeyServiceVersion.values()).filter(KeyClientTestBase::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 KeyServiceVersion} 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(KeyServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return KeyServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
class KeyClientTestBase extends TestBase { private static final String KEY_NAME = "javaKeyTemp"; private static final KeyType RSA_KEY_TYPE = KeyType.RSA; private static final KeyType EC_KEY_TYPE = KeyType.EC; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_KEYS_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_KEYS_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_KEYS_SERVICE_VERSIONS); @Override protected String getTestName() { return ""; } void beforeTestSetup() { } HttpPipeline getHttpPipeline(HttpClient httpClient, KeyServiceVersion serviceVersion) { TokenCredential credential = null; if (!interceptorManager.isPlaybackMode()) { String clientId = System.getenv("ARM_CLIENTID"); String clientKey = System.getenv("ARM_CLIENTKEY"); String tenantId = System.getenv("AZURE_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .build(); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone(), serviceVersion)); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new BearerTokenAuthenticationPolicy(credential, KeyAsyncClient.KEY_VAULT_SCOPE)); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (getTestMode() == TestMode.RECORD) { policies.add(interceptorManager.getRecordPolicy()); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; } @Test public abstract void setKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void setKeyRunner(Consumer<CreateKeyOptions> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("foo", "baz"); final CreateKeyOptions keyOptions = new CreateKeyOptions(generateResourceId(KEY_NAME), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) .setTags(tags); testRunner.accept(keyOptions); } @Test public abstract void createRsaKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void setKeyNullType(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void setKeyEmptyValueRunner(Consumer<CreateKeyOptions> testRunner) { CreateKeyOptions key = new CreateKeyOptions(KEY_NAME, null); testRunner.accept(key); } @Test public abstract void setKeyNull(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void updateKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void updateKeyRunner(BiConsumer<CreateKeyOptions, CreateKeyOptions> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); final String keyName = generateResourceId("testKey1"); final CreateKeyOptions originalKey = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags); final CreateKeyOptions updatedKey = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setTags(tags); testRunner.accept(originalKey, updatedKey); } @Test public abstract void updateDisabledKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void updateDisabledKeyRunner(BiConsumer<CreateKeyOptions, CreateKeyOptions> testRunner) { final Map<String, String> tags = new HashMap<>(); final String keyName = generateResourceId("testKey2"); final CreateKeyOptions originalKey = new CreateKeyOptions(keyName, EC_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) .setEnabled(false); final CreateKeyOptions updatedKey = new CreateKeyOptions(keyName, EC_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(originalKey, updatedKey); } @Test public abstract void getKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void getKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions originalKey = new CreateKeyOptions(generateResourceId("testKey4"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(originalKey); } @Test public abstract void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void getKeySpecificVersionRunner(BiConsumer<CreateKeyOptions, CreateKeyOptions> testRunner) { final String keyName = generateResourceId("testKey3"); final CreateKeyOptions key = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); final CreateKeyOptions keyWithNewVal = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(key, keyWithNewVal); } @Test public abstract void getKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void deleteKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void deleteKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToDelete = new CreateKeyOptions(generateResourceId("testKey5"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToDelete); } @Test public abstract void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void getDeletedKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void getDeletedKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToDeleteAndGet = new CreateKeyOptions(generateResourceId("testKey6"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToDeleteAndGet); } @Test public abstract void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void recoverDeletedKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToDeleteAndRecover = new CreateKeyOptions(generateResourceId("testKey7"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToDeleteAndRecover); } @Test public abstract void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void backupKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void backupKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToBackup = new CreateKeyOptions(generateResourceId("testKey8"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToBackup); } @Test public abstract void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void restoreKey(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void restoreKeyRunner(Consumer<CreateKeyOptions> testRunner) { final CreateKeyOptions keyToBackupAndRestore = new CreateKeyOptions(generateResourceId("testKey9"), RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); testRunner.accept(keyToBackupAndRestore); } @Test public abstract void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion keyServiceVersion); @Test public abstract void listKeys(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void listKeysRunner(Consumer<HashMap<String, CreateKeyOptions>> testRunner) { HashMap<String, CreateKeyOptions> keys = new HashMap<>(); String keyName; for (int i = 0; i < 2; i++) { keyName = generateResourceId("listKey" + i); CreateKeyOptions key = new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)); keys.put(keyName, key); } testRunner.accept(keys); } @Test public abstract void listKeyVersions(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void listKeyVersionsRunner(Consumer<List<CreateKeyOptions>> testRunner) { List<CreateKeyOptions> keys = new ArrayList<>(); String keyName = generateResourceId("listKeyVersion"); for (int i = 1; i < 5; i++) { keys.add(new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC))); } testRunner.accept(keys); } @Test public abstract void listDeletedKeys(HttpClient httpClient, KeyServiceVersion keyServiceVersion); void listDeletedKeysRunner(Consumer<HashMap<String, CreateKeyOptions>> testRunner) { HashMap<String, CreateKeyOptions> keys = new HashMap<>(); String keyName; for (int i = 0; i < 3; i++) { keyName = generateResourceId("listDeletedKeysTest" + i); keys.put(keyName, new CreateKeyOptions(keyName, RSA_KEY_TYPE) .setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); } testRunner.accept(keys); } String generateResourceId(String suffix) { if (interceptorManager.isPlaybackMode()) { return suffix; } String id = UUID.randomUUID().toString(); return suffix.length() > 0 ? id + "-" + suffix : id; } /** * Helper method to verify that the Response matches what was expected. This method assumes a response status of 200. * * @param expected Key expected to be returned by the service * @param response Response returned by the service, the body should contain a Key */ static void assertKeyEquals(CreateKeyOptions expected, Response<KeyVaultKey> response) { assertKeyEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertKeyEquals(CreateKeyOptions expected, Response<KeyVaultKey> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertKeyEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertKeyEquals(CreateKeyOptions expected, KeyVaultKey actual) { assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getKeyType(), actual.getKey().getKeyType()); assertEquals(expected.getExpiresOn(), actual.getProperties().getExpiresOn()); assertEquals(expected.getNotBefore(), actual.getProperties().getNotBefore()); } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "http: : System.getenv("AZURE_KEYVAULT_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 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(KeyServiceVersion.values()).filter(KeyClientTestBase::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 KeyServiceVersion} 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(KeyServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return KeyServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
Functionally this works. But BinaryData.fromBytes() copies the byte array. Then when you get the byte array back from BinaryData, it's copied again. This will happen to every message. So this might not be the most optimal way. Is it possible to use the `body` directly without the double copy?
public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); }
this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null.")));
public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); }
class ServiceBusMessage { private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ /** * Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into * {@link BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage()); this.context = Context.NONE; amqpAnnotatedMessage.getHeader().setDeliveryCount(null); removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME, ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME); removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME, DEAD_LETTER_REASON_ANNOTATION_NAME); } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return the amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for * {@code getApplicationProperties()} is to associate serialization hints for the {@link * consumers who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: Optional<byte[]> byteArrayData = ((AmqpDataBody) amqpAnnotatedMessage.getBody()).getData().stream() .findFirst(); final byte[] bytes; if (byteArrayData.isPresent()) { bytes = byteArrayData.get(); } else { logger.warning("Data not present."); bytes = new byte[0]; } return BinaryData.fromBytes(bytes); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } } /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * @param contentType of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); return this; } /** * Gets the subject for the message. * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The subject to set. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Sets the message id. * * @param messageId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); return this; } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * {@link AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue * partition: This is functionally equivalent to {@link * together and in order as they are transferred. * * @return partition key on the via queue. * @see <a href="https: * and Send Via</a> */ public String getViaPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); return this; } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusMessage}. */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session id. * * @param sessionId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /* * Gets value from given map. */ private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) { for (AmqpMessageConstant key : keys) { dataMap.remove(key.getValue()); } } }
class ServiceBusMessage { private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ /** * Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into * {@link BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage()); this.context = Context.NONE; amqpAnnotatedMessage.getHeader().setDeliveryCount(null); removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME, ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME); removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME, DEAD_LETTER_REASON_ANNOTATION_NAME); } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return the amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for * {@code getApplicationProperties()} is to associate serialization hints for the {@link * consumers who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: Optional<byte[]> byteArrayData = ((AmqpDataBody) amqpAnnotatedMessage.getBody()).getData().stream() .findFirst(); final byte[] bytes; if (byteArrayData.isPresent()) { bytes = byteArrayData.get(); } else { logger.warning("Data not present."); bytes = new byte[0]; } return BinaryData.fromBytes(bytes); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } } /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * @param contentType of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); return this; } /** * Gets the subject for the message. * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The subject to set. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Sets the message id. * * @param messageId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); return this; } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * {@link AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue * partition: This is functionally equivalent to {@link * together and in order as they are transferred. * * @return partition key on the via queue. * @see <a href="https: * and Send Via</a> */ public String getViaPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); return this; } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusMessage}. */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session id. * * @param sessionId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /* * Gets value from given map. */ private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) { for (AmqpMessageConstant key : keys) { dataMap.remove(key.getValue()); } } }
Althought .Net is doing the way you suggested., We talked about this with Jonathan as well and we want to keep it this way as long as we do drastically impact performance. Even earlier when only had byte[] , we were copying the array. Because we have a build time check for it. Also by having separate copy, we ensure in multi threaded, one thread is not changing data after creating SBM. From performance point of view, I asked Vinay to test and see if there are some degradation of performance because of this and his data suggest there was no degradation.
public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); }
this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null.")));
public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); }
class ServiceBusMessage { private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ /** * Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into * {@link BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage()); this.context = Context.NONE; amqpAnnotatedMessage.getHeader().setDeliveryCount(null); removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME, ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME); removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME, DEAD_LETTER_REASON_ANNOTATION_NAME); } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return the amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for * {@code getApplicationProperties()} is to associate serialization hints for the {@link * consumers who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: Optional<byte[]> byteArrayData = ((AmqpDataBody) amqpAnnotatedMessage.getBody()).getData().stream() .findFirst(); final byte[] bytes; if (byteArrayData.isPresent()) { bytes = byteArrayData.get(); } else { logger.warning("Data not present."); bytes = new byte[0]; } return BinaryData.fromBytes(bytes); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } } /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * @param contentType of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); return this; } /** * Gets the subject for the message. * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The subject to set. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Sets the message id. * * @param messageId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); return this; } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * {@link AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue * partition: This is functionally equivalent to {@link * together and in order as they are transferred. * * @return partition key on the via queue. * @see <a href="https: * and Send Via</a> */ public String getViaPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); return this; } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusMessage}. */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session id. * * @param sessionId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /* * Gets value from given map. */ private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) { for (AmqpMessageConstant key : keys) { dataMap.remove(key.getValue()); } } }
class ServiceBusMessage { private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ /** * Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into * {@link BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage()); this.context = Context.NONE; amqpAnnotatedMessage.getHeader().setDeliveryCount(null); removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME, ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME); removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME, DEAD_LETTER_REASON_ANNOTATION_NAME); } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return the amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for * {@code getApplicationProperties()} is to associate serialization hints for the {@link * consumers who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: Optional<byte[]> byteArrayData = ((AmqpDataBody) amqpAnnotatedMessage.getBody()).getData().stream() .findFirst(); final byte[] bytes; if (byteArrayData.isPresent()) { bytes = byteArrayData.get(); } else { logger.warning("Data not present."); bytes = new byte[0]; } return BinaryData.fromBytes(bytes); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } } /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * @param contentType of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); return this; } /** * Gets the subject for the message. * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The subject to set. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Sets the message id. * * @param messageId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); return this; } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * {@link AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue * partition: This is functionally equivalent to {@link * together and in order as they are transferred. * * @return partition key on the via queue. * @see <a href="https: * and Send Via</a> */ public String getViaPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); return this; } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusMessage}. */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session id. * * @param sessionId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /* * Gets value from given map. */ private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) { for (AmqpMessageConstant key : keys) { dataMap.remove(key.getValue()); } } }
No more concern if there is no impact to CPU performance and GC
public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); }
this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null.")));
public ServiceBusMessage(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); }
class ServiceBusMessage { private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ /** * Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into * {@link BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage()); this.context = Context.NONE; amqpAnnotatedMessage.getHeader().setDeliveryCount(null); removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME, ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME); removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME, DEAD_LETTER_REASON_ANNOTATION_NAME); } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return the amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for * {@code getApplicationProperties()} is to associate serialization hints for the {@link * consumers who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: Optional<byte[]> byteArrayData = ((AmqpDataBody) amqpAnnotatedMessage.getBody()).getData().stream() .findFirst(); final byte[] bytes; if (byteArrayData.isPresent()) { bytes = byteArrayData.get(); } else { logger.warning("Data not present."); bytes = new byte[0]; } return BinaryData.fromBytes(bytes); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } } /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * @param contentType of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); return this; } /** * Gets the subject for the message. * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The subject to set. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Sets the message id. * * @param messageId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); return this; } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * {@link AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue * partition: This is functionally equivalent to {@link * together and in order as they are transferred. * * @return partition key on the via queue. * @see <a href="https: * and Send Via</a> */ public String getViaPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); return this; } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusMessage}. */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session id. * * @param sessionId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /* * Gets value from given map. */ private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) { for (AmqpMessageConstant key : keys) { dataMap.remove(key.getValue()); } } }
class ServiceBusMessage { private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class); private Context context; /** * Creates a {@link ServiceBusMessage} with given byte array body. * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ /** * Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets * * @param body The content of the Service bus message. * * @throws NullPointerException if {@code body} is null. */ public ServiceBusMessage(String body) { this(BinaryData.fromString(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}.The {@link BinaryData} provides various * convenience API representing byte array. It also provides a way to serialize {@link Object} into * {@link BinaryData}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. * * @see BinaryData */ public ServiceBusMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.amqpAnnotatedMessage = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a * {@link ServiceBusReceivedMessage} needs to be sent to another entity. * * @param receivedMessage The received message to create new message from. * * @throws NullPointerException if {@code receivedMessage} is {@code null}. */ public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) { Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null."); this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage()); this.context = Context.NONE; amqpAnnotatedMessage.getHeader().setDeliveryCount(null); removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME, ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME); removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME, DEAD_LETTER_REASON_ANNOTATION_NAME); } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return the amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for * {@code getApplicationProperties()} is to associate serialization hints for the {@link * consumers who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: Optional<byte[]> byteArrayData = ((AmqpDataBody) amqpAnnotatedMessage.getBody()).getData().stream() .findFirst(); final byte[] bytes; if (byteArrayData.isPresent()) { bytes = byteArrayData.get(); } else { logger.warning("Data not present."); bytes = new byte[0]; } return BinaryData.fromBytes(bytes); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } } /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link ServiceBusMessage}. * * @param contentType of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); return this; } /** * Gets the subject for the message. * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The subject to set. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Sets the message id. * * @param messageId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * @see <a href="https: * entities</a> */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); return this; } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * {@link AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue * partition: This is functionally equivalent to {@link * together and in order as they are transferred. * * @return partition key on the via queue. * @see <a href="https: * and Send Via</a> */ public String getViaPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); return this; } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusMessage}. */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session id. * * @param sessionId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /* * Gets value from given map. */ private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) { for (AmqpMessageConstant key : keys) { dataMap.remove(key.getValue()); } } }
What happens if the AmqpBodyType is SEQUENCE or VALUE?
public byte[] getBodyAsBytes() { return getBody().toBytes(); }
}
public byte[] getBodyAsBytes() { return getBody().toBytes(); }
class ServiceBusReceivedMessage { private final ClientLogger logger = new ClientLogger(ServiceBusReceivedMessage.class); private final AmqpAnnotatedMessage amqpAnnotatedMessage; private UUID lockToken; /** * The representation of message as defined by AMQP protocol. * * @see <a href="http: * Amqp Message Format.</a> * * @return the {@link AmqpAnnotatedMessage} representing amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } ServiceBusReceivedMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: return BinaryData.fromBytes(((AmqpDataBody) amqpAnnotatedMessage.getBody()) .getData().stream().findFirst().get()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Body type not supported yet " + bodyType.toString())); default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } } /** * Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}. * * @return A byte array representing the data. */ /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusReceivedMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Gets the description for a message that has been dead-lettered. * * @return The description for a message that has been dead-lettered. */ public String getDeadLetterErrorDescription() { return getStringValue(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue()); } /** * Gets the reason for a message that has been dead-lettered. * * @return The reason for a message that has been dead-lettered. */ public String getDeadLetterReason() { return getStringValue(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_REASON_ANNOTATION_NAME.getValue()); } /** * Gets the name of the queue or subscription that this message was enqueued on, before it was * deadlettered. * <p> * This value is only set in messages that have been dead-lettered and subsequently auto-forwarded * from the dead-letter queue to another entity. Indicates the entity in which the message * was dead-lettered. This property is read-only. * * @return dead letter source of this message * * @see <a href="https: * queues</a> */ public String getDeadLetterSource() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue()); } /** * Gets the number of the times this message was delivered to clients. * <p> * The count is incremented when a message lock expires, or the message is explicitly abandoned by * the receiver. This property is read-only. * * @return delivery count of this message. * * @see <a href="https: * transfers, locks, and settlement.</a> */ public long getDeliveryCount() { return amqpAnnotatedMessage.getHeader().getDeliveryCount(); } /** * Gets the enqueued sequence number assigned to a message by Service Bus. * <p> * The sequence number is a unique 64-bit integer first assigned to a message as it is accepted at its original * point of submission. * * @return enqueued sequence number of this message * * @see <a href="https: * Timestamps</a> */ public long getEnqueuedSequenceNumber() { return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); } /** * Gets the datetime at which this message was enqueued in Azure Service Bus. * <p> * The UTC datetime at which the message has been accepted and stored in the entity. For scheduled messages, this * reflects the time when the message was activated. This value can be used as an authoritative and neutral arrival * time indicator when the receiver does not want to trust the sender's clock. This property is read-only. * * @return the datetime at which the message was enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getEnqueuedTime() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); } /** * Gets the datetime at which this message will expire. * <p> * The value is the UTC datetime for when the message is scheduled for removal and will no longer available for * retrieval from the entity due to expiration. Expiry is controlled by the {@link * property. This property is computed from {@link * TimeToLive}. * * @return {@link OffsetDateTime} at which this message expires * * @see <a href="https: */ public OffsetDateTime getExpiresAt() { final Duration timeToLive = getTimeToLive(); final OffsetDateTime enqueuedTime = getEnqueuedTime(); return enqueuedTime != null && timeToLive != null ? enqueuedTime.plus(timeToLive) : null; } /** * Gets the label for the message. * * @return The label for the message. */ public String getLabel() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Gets the lock token for the current message. * <p> * The lock token is a reference to the lock that is being held by the broker in * {@link ReceiveMode * Locks are used to explicitly settle messages as explained in the * <a href="https: * documentation in more detail</a>. The token can also be used to pin the lock permanently * through the <a * href="https: * take the message out of the regular delivery state flow. This property is read-only. * * @return Lock-token for this message. Could return {@code null} for {@link ReceiveMode * * @see <a href="https: * transfers, locks, and settlement</a> */ public String getLockToken() { return lockToken != null ? lockToken.toString() : null; } /** * Gets the datetime at which the lock of this message expires. * <p> * For messages retrieved under a lock (peek-lock receive mode, not pre-settled) this property reflects the UTC * datetime until which the message is held locked in the queue/subscription. When the lock expires, the {@link * * is read-only. * * @return the datetime at which the lock of this message expires if the message is received using {@link * ReceiveMode * * @see <a href="https: * transfers, locks, and settlement</a> */ public OffsetDateTime getLockedUntil() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME.getValue()); } /** * @return Id of the {@link ServiceBusReceivedMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * * @see <a href="https: * entities</a> */ public String getPartitionKey() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Gets the set of free-form {@link ServiceBusReceivedMessage} properties which may be used for passing metadata * associated with the {@link ServiceBusReceivedMessage} during Service Bus operations. A common use-case for * {@code properties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusReceivedMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); } /** * Gets the unique number assigned to a message by Service Bus. * <p> * The sequence number is a unique 64-bit integer assigned to a message as it is accepted and stored by the broker * and functions as its true identifier. For partitioned entities, the topmost 16 bits reflect the partition * identifier. Sequence numbers monotonically increase and are gapless. They roll over to 0 when the 48-64 bit range * is exhausted. This property is read-only. * * @return sequence number of this message * * @see <a href="https: * Timestamps</a> */ public long getSequenceNumber() { return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(), SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusReceivedMessage}. */ public String getSessionId() { return getAmqpAnnotatedMessage().getProperties().getGroupId(); } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the datetime the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the * transfer queue partition: This is functionally equivalent to {@link * messages are kept together and in order as they are transferred. * * @return partition key on the via queue. * * @see <a href="https: */ public String getViaPartitionKey() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @see */ void setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); } /** * Sets the content type of the {@link ServiceBusReceivedMessage}. * * @param contentType of the message. */ void setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); } /** * Sets the dead letter description. * * @param deadLetterErrorDescription Dead letter description. */ void setDeadLetterErrorDescription(String deadLetterErrorDescription) { amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue(), deadLetterErrorDescription); } /** * Sets the dead letter reason. * * @param deadLetterReason Dead letter reason. */ void setDeadLetterReason(String deadLetterReason) { amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_REASON_ANNOTATION_NAME.getValue(), deadLetterReason); } /** * Sets the name of the queue or subscription that this message was enqueued on, before it was * deadlettered. * * @param deadLetterSource the name of the queue or subscription that this message was enqueued on, * before it was deadlettered. */ void setDeadLetterSource(String deadLetterSource) { amqpAnnotatedMessage.getMessageAnnotations().put(DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue(), deadLetterSource); } /** * Sets the number of the times this message was delivered to clients. * * @param deliveryCount the number of the times this message was delivered to clients. */ void setDeliveryCount(long deliveryCount) { amqpAnnotatedMessage.getHeader().setDeliveryCount(deliveryCount); } void setEnqueuedSequenceNumber(long enqueuedSequenceNumber) { amqpAnnotatedMessage.getMessageAnnotations().put(ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), enqueuedSequenceNumber); } /** * Sets the datetime at which this message was enqueued in Azure Service Bus. * * @param enqueuedTime the datetime at which this message was enqueued in Azure Service Bus. */ void setEnqueuedTime(OffsetDateTime enqueuedTime) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME, enqueuedTime); } /** * Sets the subject for the message. * * @param subject The subject to set. */ void setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); } /** * Sets the lock token for the current message. * * @param lockToken the lock token for the current message. */ void setLockToken(UUID lockToken) { this.lockToken = lockToken; } /** * Sets the datetime at which the lock of this message expires. * * @param lockedUntil the datetime at which the lock of this message expires. */ void setLockedUntil(OffsetDateTime lockedUntil) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, lockedUntil); } /** * Sets the message id. * * @param messageId to be set. */ void setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @see */ void setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); } /** * Sets the scheduled enqueue time of this message. * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @see */ void setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME, scheduledEnqueueTime); } /** * Sets the unique number assigned to a message by Service Bus. * * @param sequenceNumber the unique number assigned to a message by Service Bus. */ void setSequenceNumber(long sequenceNumber) { amqpAnnotatedMessage.getMessageAnnotations().put(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), sequenceNumber); } /** * Sets the session id. * * @param sessionId to be set. */ void setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @see */ void setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @see */ void setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message */ void setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message */ void setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @see */ void setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); } /* * Gets String value from given map and null if key does not exists. */ private String getStringValue(Map<String, Object> dataMap, String key) { return (String) dataMap.get(key); } /* * Gets long value from given map and 0 if key does not exists. */ private long getLongValue(Map<String, Object> dataMap, String key) { return dataMap.containsKey(key) ? (long) dataMap.get(key) : 0; } /* * Gets OffsetDateTime value from given map and null if key does not exists. */ private OffsetDateTime getOffsetDateTimeValue(Map<String, Object> dataMap, String key) { return dataMap.containsKey(key) ? ((Date) dataMap.get(key)).toInstant().atOffset(ZoneOffset.UTC) : null; } private void setValue(Map<String, Object> dataMap, AmqpMessageConstant key, OffsetDateTime value) { if (value != null) { amqpAnnotatedMessage.getMessageAnnotations().put(key.getValue(), new Date(value.toInstant().toEpochMilli())); } } }
class ServiceBusReceivedMessage { private final ClientLogger logger = new ClientLogger(ServiceBusReceivedMessage.class); private final AmqpAnnotatedMessage amqpAnnotatedMessage; private UUID lockToken; /** * The representation of message as defined by AMQP protocol. * * @see <a href="http: * Amqp Message Format.</a> * * @return the {@link AmqpAnnotatedMessage} representing amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } ServiceBusReceivedMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: return BinaryData.fromBytes(((AmqpDataBody) amqpAnnotatedMessage.getBody()) .getData().stream().findFirst().get()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Body type not supported yet " + bodyType.toString())); default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } } /** * Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}. * * @return A byte array representing the data. */ /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusReceivedMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Gets the description for a message that has been dead-lettered. * * @return The description for a message that has been dead-lettered. */ public String getDeadLetterErrorDescription() { return getStringValue(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue()); } /** * Gets the reason for a message that has been dead-lettered. * * @return The reason for a message that has been dead-lettered. */ public String getDeadLetterReason() { return getStringValue(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_REASON_ANNOTATION_NAME.getValue()); } /** * Gets the name of the queue or subscription that this message was enqueued on, before it was * deadlettered. * <p> * This value is only set in messages that have been dead-lettered and subsequently auto-forwarded * from the dead-letter queue to another entity. Indicates the entity in which the message * was dead-lettered. This property is read-only. * * @return dead letter source of this message * * @see <a href="https: * queues</a> */ public String getDeadLetterSource() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue()); } /** * Gets the number of the times this message was delivered to clients. * <p> * The count is incremented when a message lock expires, or the message is explicitly abandoned by * the receiver. This property is read-only. * * @return delivery count of this message. * * @see <a href="https: * transfers, locks, and settlement.</a> */ public long getDeliveryCount() { return amqpAnnotatedMessage.getHeader().getDeliveryCount(); } /** * Gets the enqueued sequence number assigned to a message by Service Bus. * <p> * The sequence number is a unique 64-bit integer first assigned to a message as it is accepted at its original * point of submission. * * @return enqueued sequence number of this message * * @see <a href="https: * Timestamps</a> */ public long getEnqueuedSequenceNumber() { return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); } /** * Gets the datetime at which this message was enqueued in Azure Service Bus. * <p> * The UTC datetime at which the message has been accepted and stored in the entity. For scheduled messages, this * reflects the time when the message was activated. This value can be used as an authoritative and neutral arrival * time indicator when the receiver does not want to trust the sender's clock. This property is read-only. * * @return the datetime at which the message was enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getEnqueuedTime() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); } /** * Gets the datetime at which this message will expire. * <p> * The value is the UTC datetime for when the message is scheduled for removal and will no longer available for * retrieval from the entity due to expiration. Expiry is controlled by the {@link * property. This property is computed from {@link * TimeToLive}. * * @return {@link OffsetDateTime} at which this message expires * * @see <a href="https: */ public OffsetDateTime getExpiresAt() { final Duration timeToLive = getTimeToLive(); final OffsetDateTime enqueuedTime = getEnqueuedTime(); return enqueuedTime != null && timeToLive != null ? enqueuedTime.plus(timeToLive) : null; } /** * Gets the label for the message. * * @return The label for the message. */ public String getLabel() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Gets the lock token for the current message. * <p> * The lock token is a reference to the lock that is being held by the broker in * {@link ReceiveMode * Locks are used to explicitly settle messages as explained in the * <a href="https: * documentation in more detail</a>. The token can also be used to pin the lock permanently * through the <a * href="https: * take the message out of the regular delivery state flow. This property is read-only. * * @return Lock-token for this message. Could return {@code null} for {@link ReceiveMode * * @see <a href="https: * transfers, locks, and settlement</a> */ public String getLockToken() { return lockToken != null ? lockToken.toString() : null; } /** * Gets the datetime at which the lock of this message expires. * <p> * For messages retrieved under a lock (peek-lock receive mode, not pre-settled) this property reflects the UTC * datetime until which the message is held locked in the queue/subscription. When the lock expires, the {@link * * is read-only. * * @return the datetime at which the lock of this message expires if the message is received using {@link * ReceiveMode * * @see <a href="https: * transfers, locks, and settlement</a> */ public OffsetDateTime getLockedUntil() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME.getValue()); } /** * @return Id of the {@link ServiceBusReceivedMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * * @see <a href="https: * entities</a> */ public String getPartitionKey() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Gets the set of free-form {@link ServiceBusReceivedMessage} properties which may be used for passing metadata * associated with the {@link ServiceBusReceivedMessage} during Service Bus operations. A common use-case for * {@code properties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusReceivedMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); } /** * Gets the unique number assigned to a message by Service Bus. * <p> * The sequence number is a unique 64-bit integer assigned to a message as it is accepted and stored by the broker * and functions as its true identifier. For partitioned entities, the topmost 16 bits reflect the partition * identifier. Sequence numbers monotonically increase and are gapless. They roll over to 0 when the 48-64 bit range * is exhausted. This property is read-only. * * @return sequence number of this message * * @see <a href="https: * Timestamps</a> */ public long getSequenceNumber() { return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(), SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusReceivedMessage}. */ public String getSessionId() { return getAmqpAnnotatedMessage().getProperties().getGroupId(); } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the datetime the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the * transfer queue partition: This is functionally equivalent to {@link * messages are kept together and in order as they are transferred. * * @return partition key on the via queue. * * @see <a href="https: */ public String getViaPartitionKey() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @see */ void setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); } /** * Sets the content type of the {@link ServiceBusReceivedMessage}. * * @param contentType of the message. */ void setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); } /** * Sets the dead letter description. * * @param deadLetterErrorDescription Dead letter description. */ void setDeadLetterErrorDescription(String deadLetterErrorDescription) { amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue(), deadLetterErrorDescription); } /** * Sets the dead letter reason. * * @param deadLetterReason Dead letter reason. */ void setDeadLetterReason(String deadLetterReason) { amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_REASON_ANNOTATION_NAME.getValue(), deadLetterReason); } /** * Sets the name of the queue or subscription that this message was enqueued on, before it was * deadlettered. * * @param deadLetterSource the name of the queue or subscription that this message was enqueued on, * before it was deadlettered. */ void setDeadLetterSource(String deadLetterSource) { amqpAnnotatedMessage.getMessageAnnotations().put(DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue(), deadLetterSource); } /** * Sets the number of the times this message was delivered to clients. * * @param deliveryCount the number of the times this message was delivered to clients. */ void setDeliveryCount(long deliveryCount) { amqpAnnotatedMessage.getHeader().setDeliveryCount(deliveryCount); } void setEnqueuedSequenceNumber(long enqueuedSequenceNumber) { amqpAnnotatedMessage.getMessageAnnotations().put(ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), enqueuedSequenceNumber); } /** * Sets the datetime at which this message was enqueued in Azure Service Bus. * * @param enqueuedTime the datetime at which this message was enqueued in Azure Service Bus. */ void setEnqueuedTime(OffsetDateTime enqueuedTime) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME, enqueuedTime); } /** * Sets the subject for the message. * * @param subject The subject to set. */ void setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); } /** * Sets the lock token for the current message. * * @param lockToken the lock token for the current message. */ void setLockToken(UUID lockToken) { this.lockToken = lockToken; } /** * Sets the datetime at which the lock of this message expires. * * @param lockedUntil the datetime at which the lock of this message expires. */ void setLockedUntil(OffsetDateTime lockedUntil) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, lockedUntil); } /** * Sets the message id. * * @param messageId to be set. */ void setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @see */ void setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); } /** * Sets the scheduled enqueue time of this message. * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @see */ void setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME, scheduledEnqueueTime); } /** * Sets the unique number assigned to a message by Service Bus. * * @param sequenceNumber the unique number assigned to a message by Service Bus. */ void setSequenceNumber(long sequenceNumber) { amqpAnnotatedMessage.getMessageAnnotations().put(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), sequenceNumber); } /** * Sets the session id. * * @param sessionId to be set. */ void setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @see */ void setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @see */ void setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message */ void setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message */ void setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @see */ void setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); } /* * Gets String value from given map and null if key does not exists. */ private String getStringValue(Map<String, Object> dataMap, String key) { return (String) dataMap.get(key); } /* * Gets long value from given map and 0 if key does not exists. */ private long getLongValue(Map<String, Object> dataMap, String key) { return dataMap.containsKey(key) ? (long) dataMap.get(key) : 0; } /* * Gets OffsetDateTime value from given map and null if key does not exists. */ private OffsetDateTime getOffsetDateTimeValue(Map<String, Object> dataMap, String key) { return dataMap.containsKey(key) ? ((Date) dataMap.get(key)).toInstant().atOffset(ZoneOffset.UTC) : null; } private void setValue(Map<String, Object> dataMap, AmqpMessageConstant key, OffsetDateTime value) { if (value != null) { amqpAnnotatedMessage.getMessageAnnotations().put(key.getValue(), new Date(value.toInstant().toEpochMilli())); } } }
We will design with other languages, But I see we can have something like public AmqpSequenceBody getBodyAsSequence(); and in getBodyAsBytes we continue to throw for any type other than Types=DATA which is bytes in AMQP. t
public byte[] getBodyAsBytes() { return getBody().toBytes(); }
}
public byte[] getBodyAsBytes() { return getBody().toBytes(); }
class ServiceBusReceivedMessage { private final ClientLogger logger = new ClientLogger(ServiceBusReceivedMessage.class); private final AmqpAnnotatedMessage amqpAnnotatedMessage; private UUID lockToken; /** * The representation of message as defined by AMQP protocol. * * @see <a href="http: * Amqp Message Format.</a> * * @return the {@link AmqpAnnotatedMessage} representing amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } ServiceBusReceivedMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: return BinaryData.fromBytes(((AmqpDataBody) amqpAnnotatedMessage.getBody()) .getData().stream().findFirst().get()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Body type not supported yet " + bodyType.toString())); default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } } /** * Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}. * * @return A byte array representing the data. */ /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusReceivedMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Gets the description for a message that has been dead-lettered. * * @return The description for a message that has been dead-lettered. */ public String getDeadLetterErrorDescription() { return getStringValue(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue()); } /** * Gets the reason for a message that has been dead-lettered. * * @return The reason for a message that has been dead-lettered. */ public String getDeadLetterReason() { return getStringValue(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_REASON_ANNOTATION_NAME.getValue()); } /** * Gets the name of the queue or subscription that this message was enqueued on, before it was * deadlettered. * <p> * This value is only set in messages that have been dead-lettered and subsequently auto-forwarded * from the dead-letter queue to another entity. Indicates the entity in which the message * was dead-lettered. This property is read-only. * * @return dead letter source of this message * * @see <a href="https: * queues</a> */ public String getDeadLetterSource() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue()); } /** * Gets the number of the times this message was delivered to clients. * <p> * The count is incremented when a message lock expires, or the message is explicitly abandoned by * the receiver. This property is read-only. * * @return delivery count of this message. * * @see <a href="https: * transfers, locks, and settlement.</a> */ public long getDeliveryCount() { return amqpAnnotatedMessage.getHeader().getDeliveryCount(); } /** * Gets the enqueued sequence number assigned to a message by Service Bus. * <p> * The sequence number is a unique 64-bit integer first assigned to a message as it is accepted at its original * point of submission. * * @return enqueued sequence number of this message * * @see <a href="https: * Timestamps</a> */ public long getEnqueuedSequenceNumber() { return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); } /** * Gets the datetime at which this message was enqueued in Azure Service Bus. * <p> * The UTC datetime at which the message has been accepted and stored in the entity. For scheduled messages, this * reflects the time when the message was activated. This value can be used as an authoritative and neutral arrival * time indicator when the receiver does not want to trust the sender's clock. This property is read-only. * * @return the datetime at which the message was enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getEnqueuedTime() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); } /** * Gets the datetime at which this message will expire. * <p> * The value is the UTC datetime for when the message is scheduled for removal and will no longer available for * retrieval from the entity due to expiration. Expiry is controlled by the {@link * property. This property is computed from {@link * TimeToLive}. * * @return {@link OffsetDateTime} at which this message expires * * @see <a href="https: */ public OffsetDateTime getExpiresAt() { final Duration timeToLive = getTimeToLive(); final OffsetDateTime enqueuedTime = getEnqueuedTime(); return enqueuedTime != null && timeToLive != null ? enqueuedTime.plus(timeToLive) : null; } /** * Gets the label for the message. * * @return The label for the message. */ public String getLabel() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Gets the lock token for the current message. * <p> * The lock token is a reference to the lock that is being held by the broker in * {@link ReceiveMode * Locks are used to explicitly settle messages as explained in the * <a href="https: * documentation in more detail</a>. The token can also be used to pin the lock permanently * through the <a * href="https: * take the message out of the regular delivery state flow. This property is read-only. * * @return Lock-token for this message. Could return {@code null} for {@link ReceiveMode * * @see <a href="https: * transfers, locks, and settlement</a> */ public String getLockToken() { return lockToken != null ? lockToken.toString() : null; } /** * Gets the datetime at which the lock of this message expires. * <p> * For messages retrieved under a lock (peek-lock receive mode, not pre-settled) this property reflects the UTC * datetime until which the message is held locked in the queue/subscription. When the lock expires, the {@link * * is read-only. * * @return the datetime at which the lock of this message expires if the message is received using {@link * ReceiveMode * * @see <a href="https: * transfers, locks, and settlement</a> */ public OffsetDateTime getLockedUntil() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME.getValue()); } /** * @return Id of the {@link ServiceBusReceivedMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * * @see <a href="https: * entities</a> */ public String getPartitionKey() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Gets the set of free-form {@link ServiceBusReceivedMessage} properties which may be used for passing metadata * associated with the {@link ServiceBusReceivedMessage} during Service Bus operations. A common use-case for * {@code properties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusReceivedMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); } /** * Gets the unique number assigned to a message by Service Bus. * <p> * The sequence number is a unique 64-bit integer assigned to a message as it is accepted and stored by the broker * and functions as its true identifier. For partitioned entities, the topmost 16 bits reflect the partition * identifier. Sequence numbers monotonically increase and are gapless. They roll over to 0 when the 48-64 bit range * is exhausted. This property is read-only. * * @return sequence number of this message * * @see <a href="https: * Timestamps</a> */ public long getSequenceNumber() { return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(), SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusReceivedMessage}. */ public String getSessionId() { return getAmqpAnnotatedMessage().getProperties().getGroupId(); } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the datetime the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the * transfer queue partition: This is functionally equivalent to {@link * messages are kept together and in order as they are transferred. * * @return partition key on the via queue. * * @see <a href="https: */ public String getViaPartitionKey() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @see */ void setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); } /** * Sets the content type of the {@link ServiceBusReceivedMessage}. * * @param contentType of the message. */ void setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); } /** * Sets the dead letter description. * * @param deadLetterErrorDescription Dead letter description. */ void setDeadLetterErrorDescription(String deadLetterErrorDescription) { amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue(), deadLetterErrorDescription); } /** * Sets the dead letter reason. * * @param deadLetterReason Dead letter reason. */ void setDeadLetterReason(String deadLetterReason) { amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_REASON_ANNOTATION_NAME.getValue(), deadLetterReason); } /** * Sets the name of the queue or subscription that this message was enqueued on, before it was * deadlettered. * * @param deadLetterSource the name of the queue or subscription that this message was enqueued on, * before it was deadlettered. */ void setDeadLetterSource(String deadLetterSource) { amqpAnnotatedMessage.getMessageAnnotations().put(DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue(), deadLetterSource); } /** * Sets the number of the times this message was delivered to clients. * * @param deliveryCount the number of the times this message was delivered to clients. */ void setDeliveryCount(long deliveryCount) { amqpAnnotatedMessage.getHeader().setDeliveryCount(deliveryCount); } void setEnqueuedSequenceNumber(long enqueuedSequenceNumber) { amqpAnnotatedMessage.getMessageAnnotations().put(ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), enqueuedSequenceNumber); } /** * Sets the datetime at which this message was enqueued in Azure Service Bus. * * @param enqueuedTime the datetime at which this message was enqueued in Azure Service Bus. */ void setEnqueuedTime(OffsetDateTime enqueuedTime) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME, enqueuedTime); } /** * Sets the subject for the message. * * @param subject The subject to set. */ void setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); } /** * Sets the lock token for the current message. * * @param lockToken the lock token for the current message. */ void setLockToken(UUID lockToken) { this.lockToken = lockToken; } /** * Sets the datetime at which the lock of this message expires. * * @param lockedUntil the datetime at which the lock of this message expires. */ void setLockedUntil(OffsetDateTime lockedUntil) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, lockedUntil); } /** * Sets the message id. * * @param messageId to be set. */ void setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @see */ void setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); } /** * Sets the scheduled enqueue time of this message. * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @see */ void setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME, scheduledEnqueueTime); } /** * Sets the unique number assigned to a message by Service Bus. * * @param sequenceNumber the unique number assigned to a message by Service Bus. */ void setSequenceNumber(long sequenceNumber) { amqpAnnotatedMessage.getMessageAnnotations().put(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), sequenceNumber); } /** * Sets the session id. * * @param sessionId to be set. */ void setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @see */ void setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @see */ void setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message */ void setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message */ void setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @see */ void setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); } /* * Gets String value from given map and null if key does not exists. */ private String getStringValue(Map<String, Object> dataMap, String key) { return (String) dataMap.get(key); } /* * Gets long value from given map and 0 if key does not exists. */ private long getLongValue(Map<String, Object> dataMap, String key) { return dataMap.containsKey(key) ? (long) dataMap.get(key) : 0; } /* * Gets OffsetDateTime value from given map and null if key does not exists. */ private OffsetDateTime getOffsetDateTimeValue(Map<String, Object> dataMap, String key) { return dataMap.containsKey(key) ? ((Date) dataMap.get(key)).toInstant().atOffset(ZoneOffset.UTC) : null; } private void setValue(Map<String, Object> dataMap, AmqpMessageConstant key, OffsetDateTime value) { if (value != null) { amqpAnnotatedMessage.getMessageAnnotations().put(key.getValue(), new Date(value.toInstant().toEpochMilli())); } } }
class ServiceBusReceivedMessage { private final ClientLogger logger = new ClientLogger(ServiceBusReceivedMessage.class); private final AmqpAnnotatedMessage amqpAnnotatedMessage; private UUID lockToken; /** * The representation of message as defined by AMQP protocol. * * @see <a href="http: * Amqp Message Format.</a> * * @return the {@link AmqpAnnotatedMessage} representing amqp message. */ public AmqpAnnotatedMessage getAmqpAnnotatedMessage() { return amqpAnnotatedMessage; } ServiceBusReceivedMessage(BinaryData body) { Objects.requireNonNull(body, "'body' cannot be null."); amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(body.toBytes()))); } /** * Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}. * * <p>The {@link BinaryData} wraps byte array and is an abstraction over many different ways it can be represented. * It provides many convenience API including APIs to serialize/deserialize object. * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * consumers who wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public BinaryData getBody() { final AmqpBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: return BinaryData.fromBytes(((AmqpDataBody) amqpAnnotatedMessage.getBody()) .getData().stream().findFirst().get()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Body type not supported yet " + bodyType.toString())); default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } } /** * Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}. * * @return A byte array representing the data. */ /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusReceivedMessage}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return amqpAnnotatedMessage.getProperties().getCorrelationId(); } /** * Gets the description for a message that has been dead-lettered. * * @return The description for a message that has been dead-lettered. */ public String getDeadLetterErrorDescription() { return getStringValue(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue()); } /** * Gets the reason for a message that has been dead-lettered. * * @return The reason for a message that has been dead-lettered. */ public String getDeadLetterReason() { return getStringValue(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_REASON_ANNOTATION_NAME.getValue()); } /** * Gets the name of the queue or subscription that this message was enqueued on, before it was * deadlettered. * <p> * This value is only set in messages that have been dead-lettered and subsequently auto-forwarded * from the dead-letter queue to another entity. Indicates the entity in which the message * was dead-lettered. This property is read-only. * * @return dead letter source of this message * * @see <a href="https: * queues</a> */ public String getDeadLetterSource() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue()); } /** * Gets the number of the times this message was delivered to clients. * <p> * The count is incremented when a message lock expires, or the message is explicitly abandoned by * the receiver. This property is read-only. * * @return delivery count of this message. * * @see <a href="https: * transfers, locks, and settlement.</a> */ public long getDeliveryCount() { return amqpAnnotatedMessage.getHeader().getDeliveryCount(); } /** * Gets the enqueued sequence number assigned to a message by Service Bus. * <p> * The sequence number is a unique 64-bit integer first assigned to a message as it is accepted at its original * point of submission. * * @return enqueued sequence number of this message * * @see <a href="https: * Timestamps</a> */ public long getEnqueuedSequenceNumber() { return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); } /** * Gets the datetime at which this message was enqueued in Azure Service Bus. * <p> * The UTC datetime at which the message has been accepted and stored in the entity. For scheduled messages, this * reflects the time when the message was activated. This value can be used as an authoritative and neutral arrival * time indicator when the receiver does not want to trust the sender's clock. This property is read-only. * * @return the datetime at which the message was enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getEnqueuedTime() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); } /** * Gets the datetime at which this message will expire. * <p> * The value is the UTC datetime for when the message is scheduled for removal and will no longer available for * retrieval from the entity due to expiration. Expiry is controlled by the {@link * property. This property is computed from {@link * TimeToLive}. * * @return {@link OffsetDateTime} at which this message expires * * @see <a href="https: */ public OffsetDateTime getExpiresAt() { final Duration timeToLive = getTimeToLive(); final OffsetDateTime enqueuedTime = getEnqueuedTime(); return enqueuedTime != null && timeToLive != null ? enqueuedTime.plus(timeToLive) : null; } /** * Gets the label for the message. * * @return The label for the message. */ public String getLabel() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Gets the lock token for the current message. * <p> * The lock token is a reference to the lock that is being held by the broker in * {@link ReceiveMode * Locks are used to explicitly settle messages as explained in the * <a href="https: * documentation in more detail</a>. The token can also be used to pin the lock permanently * through the <a * href="https: * take the message out of the regular delivery state flow. This property is read-only. * * @return Lock-token for this message. Could return {@code null} for {@link ReceiveMode * * @see <a href="https: * transfers, locks, and settlement</a> */ public String getLockToken() { return lockToken != null ? lockToken.toString() : null; } /** * Gets the datetime at which the lock of this message expires. * <p> * For messages retrieved under a lock (peek-lock receive mode, not pre-settled) this property reflects the UTC * datetime until which the message is held locked in the queue/subscription. When the lock expires, the {@link * * is read-only. * * @return the datetime at which the lock of this message expires if the message is received using {@link * ReceiveMode * * @see <a href="https: * transfers, locks, and settlement</a> */ public OffsetDateTime getLockedUntil() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME.getValue()); } /** * @return Id of the {@link ServiceBusReceivedMessage}. */ public String getMessageId() { return amqpAnnotatedMessage.getProperties().getMessageId(); } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * * @see <a href="https: * entities</a> */ public String getPartitionKey() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Gets the set of free-form {@link ServiceBusReceivedMessage} properties which may be used for passing metadata * associated with the {@link ServiceBusReceivedMessage} during Service Bus operations. A common use-case for * {@code properties()} is to associate serialization hints for the {@link * who wish to deserialize the binary data. * * @return Application properties associated with this {@link ServiceBusReceivedMessage}. */ public Map<String, Object> getApplicationProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return amqpAnnotatedMessage.getProperties().getReplyTo(); } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public OffsetDateTime getScheduledEnqueueTime() { return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); } /** * Gets the unique number assigned to a message by Service Bus. * <p> * The sequence number is a unique 64-bit integer assigned to a message as it is accepted and stored by the broker * and functions as its true identifier. For partitioned entities, the topmost 16 bits reflect the partition * identifier. Sequence numbers monotonically increase and are gapless. They roll over to 0 when the 48-64 bit range * is exhausted. This property is read-only. * * @return sequence number of this message * * @see <a href="https: * Timestamps</a> */ public long getSequenceNumber() { return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(), SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusReceivedMessage}. */ public String getSessionId() { return getAmqpAnnotatedMessage().getProperties().getGroupId(); } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the datetime the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * * @see <a href="https: */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return amqpAnnotatedMessage.getProperties().getTo(); } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the * transfer queue partition: This is functionally equivalent to {@link * messages are kept together and in order as they are transferred. * * @return partition key on the via queue. * * @see <a href="https: */ public String getViaPartitionKey() { return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(), VIA_PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @see */ void setCorrelationId(String correlationId) { amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId); } /** * Sets the content type of the {@link ServiceBusReceivedMessage}. * * @param contentType of the message. */ void setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); } /** * Sets the dead letter description. * * @param deadLetterErrorDescription Dead letter description. */ void setDeadLetterErrorDescription(String deadLetterErrorDescription) { amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue(), deadLetterErrorDescription); } /** * Sets the dead letter reason. * * @param deadLetterReason Dead letter reason. */ void setDeadLetterReason(String deadLetterReason) { amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_REASON_ANNOTATION_NAME.getValue(), deadLetterReason); } /** * Sets the name of the queue or subscription that this message was enqueued on, before it was * deadlettered. * * @param deadLetterSource the name of the queue or subscription that this message was enqueued on, * before it was deadlettered. */ void setDeadLetterSource(String deadLetterSource) { amqpAnnotatedMessage.getMessageAnnotations().put(DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue(), deadLetterSource); } /** * Sets the number of the times this message was delivered to clients. * * @param deliveryCount the number of the times this message was delivered to clients. */ void setDeliveryCount(long deliveryCount) { amqpAnnotatedMessage.getHeader().setDeliveryCount(deliveryCount); } void setEnqueuedSequenceNumber(long enqueuedSequenceNumber) { amqpAnnotatedMessage.getMessageAnnotations().put(ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), enqueuedSequenceNumber); } /** * Sets the datetime at which this message was enqueued in Azure Service Bus. * * @param enqueuedTime the datetime at which this message was enqueued in Azure Service Bus. */ void setEnqueuedTime(OffsetDateTime enqueuedTime) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME, enqueuedTime); } /** * Sets the subject for the message. * * @param subject The subject to set. */ void setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); } /** * Sets the lock token for the current message. * * @param lockToken the lock token for the current message. */ void setLockToken(UUID lockToken) { this.lockToken = lockToken; } /** * Sets the datetime at which the lock of this message expires. * * @param lockedUntil the datetime at which the lock of this message expires. */ void setLockedUntil(OffsetDateTime lockedUntil) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, lockedUntil); } /** * Sets the message id. * * @param messageId to be set. */ void setMessageId(String messageId) { amqpAnnotatedMessage.getProperties().setMessageId(messageId); } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @see */ void setPartitionKey(String partitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); } /** * Sets the scheduled enqueue time of this message. * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @see */ void setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { setValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME, scheduledEnqueueTime); } /** * Sets the unique number assigned to a message by Service Bus. * * @param sequenceNumber the unique number assigned to a message by Service Bus. */ void setSequenceNumber(long sequenceNumber) { amqpAnnotatedMessage.getMessageAnnotations().put(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), sequenceNumber); } /** * Sets the session id. * * @param sessionId to be set. */ void setSessionId(String sessionId) { amqpAnnotatedMessage.getProperties().setGroupId(sessionId); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @see */ void setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @see */ void setReplyTo(String replyTo) { amqpAnnotatedMessage.getProperties().setReplyTo(replyTo); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message */ void setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message */ void setTo(String to) { amqpAnnotatedMessage.getProperties().setTo(to); } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * * @see */ void setViaPartitionKey(String viaPartitionKey) { amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey); } /* * Gets String value from given map and null if key does not exists. */ private String getStringValue(Map<String, Object> dataMap, String key) { return (String) dataMap.get(key); } /* * Gets long value from given map and 0 if key does not exists. */ private long getLongValue(Map<String, Object> dataMap, String key) { return dataMap.containsKey(key) ? (long) dataMap.get(key) : 0; } /* * Gets OffsetDateTime value from given map and null if key does not exists. */ private OffsetDateTime getOffsetDateTimeValue(Map<String, Object> dataMap, String key) { return dataMap.containsKey(key) ? ((Date) dataMap.get(key)).toInstant().atOffset(ZoneOffset.UTC) : null; } private void setValue(Map<String, Object> dataMap, AmqpMessageConstant key, OffsetDateTime value) { if (value != null) { amqpAnnotatedMessage.getMessageAnnotations().put(key.getValue(), new Date(value.toInstant().toEpochMilli())); } } }
maybe extract once into Map<String, String> once and pull values from there? not a big deal tho
public AzureMonitorExporterBuilder connectionString(String connectionString) { this.instrumentationKey = extractValueFromConnectionString(connectionString, "InstrumentationKey"); this.endpoint(extractValueFromConnectionString(connectionString, "IngestionEndpoint")); return this; }
this.instrumentationKey = extractValueFromConnectionString(connectionString, "InstrumentationKey");
public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } return this; }
class AzureMonitorExporterBuilder { private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * The connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ private String extractValueFromConnectionString(String connectionString, String key) { Objects.requireNonNull(connectionString); return Arrays.stream(connectionString.split(";")) .filter(keyValue -> { String[] keyValuePair = keyValue.split("="); return keyValuePair.length == 2 && keyValuePair[0].equalsIgnoreCase(key); }) .map(instrumentationKeyValue -> instrumentationKeyValue.split("=")[1]) .filter(iKey -> !CoreUtils.isNullOrEmpty(iKey)) .findFirst() .orElseThrow(() -> new IllegalArgumentException(key + " not found in connectionString")); } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorExporter}. * @throws NullPointerException if the instrumentation key is not set. */ public AzureMonitorExporter buildExporter() { Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorExporter(buildClient(), instrumentationKey); } }
class AzureMonitorExporterBuilder { private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * The connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorExporter}. * @throws NullPointerException if the instrumentation key is not set. */ public AzureMonitorExporter buildExporter() { Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorExporter(buildClient(), instrumentationKey); } }
Updated to use the default endpoint if connection string doesn't have one. Although, I am curious when would a connectionString not have the IngestionEndpoint. If it doesn't have one, will that qualify as a valid connectionString?
public AzureMonitorExporterBuilder connectionString(String connectionString) { this.instrumentationKey = extractValueFromConnectionString(connectionString, "InstrumentationKey"); this.endpoint(extractValueFromConnectionString(connectionString, "IngestionEndpoint")); return this; }
return this;
public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } return this; }
class AzureMonitorExporterBuilder { private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * The connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ private String extractValueFromConnectionString(String connectionString, String key) { Objects.requireNonNull(connectionString); return Arrays.stream(connectionString.split(";")) .filter(keyValue -> { String[] keyValuePair = keyValue.split("="); return keyValuePair.length == 2 && keyValuePair[0].equalsIgnoreCase(key); }) .map(instrumentationKeyValue -> instrumentationKeyValue.split("=")[1]) .filter(iKey -> !CoreUtils.isNullOrEmpty(iKey)) .findFirst() .orElseThrow(() -> new IllegalArgumentException(key + " not found in connectionString")); } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorExporter}. * @throws NullPointerException if the instrumentation key is not set. */ public AzureMonitorExporter buildExporter() { Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorExporter(buildClient(), instrumentationKey); } }
class AzureMonitorExporterBuilder { private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * The connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorExporter}. * @throws NullPointerException if the instrumentation key is not set. */ public AzureMonitorExporter buildExporter() { Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorExporter(buildClient(), instrumentationKey); } }
that's a good question, when we originally implemented connection strings, the Portal U/X only included IngestionEndpoint for gov clouds, so the default was important, but now the Portal U/X always includes IngestionEndpoint, so the default is likely not needed anymore. I'll start an internal thread and add you to see if we can find out.
public AzureMonitorExporterBuilder connectionString(String connectionString) { this.instrumentationKey = extractValueFromConnectionString(connectionString, "InstrumentationKey"); this.endpoint(extractValueFromConnectionString(connectionString, "IngestionEndpoint")); return this; }
return this;
public AzureMonitorExporterBuilder connectionString(String connectionString) { Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString); if (!keyValues.containsKey("InstrumentationKey")) { throw logger.logExceptionAsError( new IllegalArgumentException("InstrumentationKey not found in connectionString")); } this.instrumentationKey = keyValues.get("InstrumentationKey"); String endpoint = keyValues.get("IngestionEndpoint"); if (endpoint != null) { this.endpoint(endpoint); } return this; }
class AzureMonitorExporterBuilder { private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * The connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ private String extractValueFromConnectionString(String connectionString, String key) { Objects.requireNonNull(connectionString); return Arrays.stream(connectionString.split(";")) .filter(keyValue -> { String[] keyValuePair = keyValue.split("="); return keyValuePair.length == 2 && keyValuePair[0].equalsIgnoreCase(key); }) .map(instrumentationKeyValue -> instrumentationKeyValue.split("=")[1]) .filter(iKey -> !CoreUtils.isNullOrEmpty(iKey)) .findFirst() .orElseThrow(() -> new IllegalArgumentException(key + " not found in connectionString")); } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorExporter}. * @throws NullPointerException if the instrumentation key is not set. */ public AzureMonitorExporter buildExporter() { Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorExporter(buildClient(), instrumentationKey); } }
class AzureMonitorExporterBuilder { private final ClientLogger logger = new ClientLogger(AzureMonitorExporterBuilder.class); private final ApplicationInsightsClientImplBuilder restServiceClientBuilder; private String instrumentationKey; /** * Creates an instance of {@link AzureMonitorExporterBuilder}. */ public AzureMonitorExporterBuilder() { restServiceClientBuilder = new ApplicationInsightsClientImplBuilder(); } /** * Sets the service endpoint for the Azure Monitor Exporter. * @param endpoint The URL of the Azure Monitor Exporter endpoint. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ AzureMonitorExporterBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { URL url = new URL(endpoint); restServiceClientBuilder.host(url.getProtocol() + ": } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } return this; } /** * Sets the HTTP pipeline to use for the service client. If {@code pipeline} is set, all other settings are * ignored, apart from {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder pipeline(HttpPipeline httpPipeline) { restServiceClientBuilder.pipeline(httpPipeline); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpClient(HttpClient client) { restServiceClientBuilder.httpClient(client); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder httpLogOptions(HttpLogOptions logOptions) { restServiceClientBuilder.httpLogOptions(logOptions); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided to build {@link AzureMonitorExporterBuilder} . * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder retryPolicy(RetryPolicy retryPolicy) { restServiceClientBuilder.retryPolicy(retryPolicy); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * @param policy The retry policy for service requests. * * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public AzureMonitorExporterBuilder addPolicy(HttpPipelinePolicy policy) { restServiceClientBuilder.addPolicy(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * @return The updated {@link AzureMonitorExporterBuilder} object. */ public AzureMonitorExporterBuilder configuration(Configuration configuration) { restServiceClientBuilder.configuration(configuration); return this; } /** * The connection string to use for exporting telemetry events to Azure Monitor. * @param connectionString The connection string for the Azure Monitor resource. * @return The updated {@link AzureMonitorExporterBuilder} object. * @throws NullPointerException If the connection string is {@code null}. * @throws IllegalArgumentException If the connection string is invalid. */ private Map<String, String> extractKeyValuesFromConnectionString(String connectionString) { Objects.requireNonNull(connectionString); Map<String, String> keyValues = new HashMap<>(); String[] splits = connectionString.split(";"); for (String split : splits) { String[] keyValPair = split.split("="); if (keyValPair.length == 2) { keyValues.put(keyValPair[0], keyValPair[1]); } } return keyValues; } /** * Creates a {@link MonitorExporterClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterClient} with the options set from the builder. * @throws NullPointerException if {@link */ MonitorExporterClient buildClient() { return new MonitorExporterClient(buildAsyncClient()); } /** * Creates a {@link MonitorExporterAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link MonitorExporterAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link MonitorExporterAsyncClient client}. All other builder settings are * ignored. * </p> * @return A {@link MonitorExporterAsyncClient} with the options set from the builder. */ MonitorExporterAsyncClient buildAsyncClient() { final SimpleModule ndjsonModule = new SimpleModule("Ndjson List Serializer"); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(ndjsonModule); ndjsonModule.addSerializer(new NdJsonSerializer()); restServiceClientBuilder.serializerAdapter(jacksonAdapter); ApplicationInsightsClientImpl restServiceClient = restServiceClientBuilder.buildClient(); return new MonitorExporterAsyncClient(restServiceClient); } /** * Creates an {@link AzureMonitorExporter} based on the options set in the builder. This exporter is an * implementation of OpenTelemetry {@link SpanExporter}. * * @return An instance of {@link AzureMonitorExporter}. * @throws NullPointerException if the instrumentation key is not set. */ public AzureMonitorExporter buildExporter() { Objects.requireNonNull(instrumentationKey, "'connectionString' cannot be null"); return new AzureMonitorExporter(buildClient(), instrumentationKey); } }
Version is not actually required, but you send it as an empty string? Wouldn't null make more sense, or is that not idiomatic with Java? If null is okay, I wouldn't validate that it's non-null in the overload. If they use that one and still pass null, it should be as acceptable as calling this overload.
public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono);
public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setKeyReleasePolicy(createRsaKeyOptions.getKeyReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setKeyReleasePolicy(createEcKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setKeyReleasePolicy(importKeyOptions.getKeyReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setKeyReleasePolicy(keyProperties.getKeyReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setReleasePolicy(createKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setReleasePolicy(createRsaKeyOptions.getReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setReleasePolicy(createEcKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setReleasePolicy(importKeyOptions.getReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setReleasePolicy(keyProperties.getReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Given the swagger is "release_policy", I think these should actually be ReleasePolicy instead of KeyReleasePolicy. That was in the original bug as well.
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); }
.setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy());
new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = ", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setKeyReleasePolicy(createRsaKeyOptions.getKeyReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setKeyReleasePolicy(createEcKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setKeyReleasePolicy(importKeyOptions.getKeyReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setKeyReleasePolicy(keyProperties.getKeyReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = ", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setReleasePolicy(createKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setReleasePolicy(createRsaKeyOptions.getReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setReleasePolicy(createEcKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setReleasePolicy(importKeyOptions.getReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setReleasePolicy(keyProperties.getReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
No problem, thanks for pointing it out.
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); }
.setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy());
new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = ", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setKeyReleasePolicy(createRsaKeyOptions.getKeyReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setKeyReleasePolicy(createEcKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setKeyReleasePolicy(importKeyOptions.getKeyReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setKeyReleasePolicy(keyProperties.getKeyReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = ", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setReleasePolicy(createKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setReleasePolicy(createRsaKeyOptions.getReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setReleasePolicy(createEcKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setReleasePolicy(importKeyOptions.getReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setReleasePolicy(keyProperties.getReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Given you're copying this around and because `KeyProperties` needs it anyway, perhaps we should just define it on `KeyProperties`, which means `KeyVaultBundle.properties.releasePolicy` is where'd you get it.
Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setKeyReleasePolicy(keyProperties.getKeyReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); }
.setKeyReleasePolicy(keyProperties.getKeyReleasePolicy());
new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = ", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setKeyReleasePolicy(createRsaKeyOptions.getKeyReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setKeyReleasePolicy(createEcKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setKeyReleasePolicy(importKeyOptions.getKeyReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setKeyReleasePolicy(keyProperties.getKeyReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = ", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setReleasePolicy(createKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setReleasePolicy(createRsaKeyOptions.getReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setReleasePolicy(createEcKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setReleasePolicy(importKeyOptions.getReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setReleasePolicy(keyProperties.getReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Agreed based on a separate conversation we had. Let's keep it only in `KeyProperties`.
Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setKeyReleasePolicy(keyProperties.getKeyReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); }
.setKeyReleasePolicy(keyProperties.getKeyReleasePolicy());
new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = ", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setKeyReleasePolicy(createRsaKeyOptions.getKeyReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setKeyReleasePolicy(createEcKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setKeyReleasePolicy(importKeyOptions.getKeyReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setKeyReleasePolicy(keyProperties.getKeyReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = ", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setReleasePolicy(createKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setReleasePolicy(createRsaKeyOptions.getReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setReleasePolicy(createEcKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setReleasePolicy(importKeyOptions.getReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setReleasePolicy(keyProperties.getReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Since it's a part of the path I thought it would be required. Is calling `keys/{key-name}/export` equivalent to calling `keys/{key-name}/{key-version}/export` with the latest key version?
public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono);
public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setKeyReleasePolicy(createRsaKeyOptions.getKeyReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setKeyReleasePolicy(createEcKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setKeyReleasePolicy(importKeyOptions.getKeyReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setKeyReleasePolicy(keyProperties.getKeyReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setReleasePolicy(createKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setReleasePolicy(createRsaKeyOptions.getReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setReleasePolicy(createEcKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setReleasePolicy(importKeyOptions.getReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setReleasePolicy(keyProperties.getReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Yes. I asked about this even with the older APIs. Their resolver on the backend checks the operation against the last path part. All the other APIs with optional versions also list them as required in swagger. You could elide the double slash (e.g. "/keys/{key-name}//export") in the URL in that case, but in my experience with the KV APIs I haven't seen it make a difference.
public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono);
public Mono<KeyVaultKey> exportKey(String name, String environment) { try { return exportKeyWithResponse(name, "", environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setKeyReleasePolicy(createKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setKeyReleasePolicy(createRsaKeyOptions.getKeyReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setKeyReleasePolicy(createEcKeyOptions.getKeyReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setKeyReleasePolicy(importKeyOptions.getKeyReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setKeyReleasePolicy(keyProperties.getKeyReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class KeyAsyncClient { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final KeyService service; private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class); /** * Creates a KeyAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link KeyServiceVersion} of the service to be used when making requests. */ KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl.toString(); this.service = RestProxy.create(KeyService.class, pipeline); apiVersion = version.getVersion(); } /** * Get the vault endpoint url to which service requests are sent to. * @return the vault endpoint url */ public String getVaultUrl() { return vaultUrl; } Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param name The name of the key being created. * @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(String name, KeyType keyType) { try { return withContext(context -> createKeyWithResponse(name, keyType, context)) .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: * {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when * a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws ResourceModifiedException if {@code name} or {@code keyType} is null. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) { try { return withContext(context -> createKeyWithResponse(createKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) { KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType); return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); } /** * Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in * key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the * {@code keys/create} permission. * * <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions * CreateKeyOptions * field is set to true by Azure Key Vault, if not specified.</p> * * <p>The {@link CreateKeyOptions * include: {@link KeyType * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call * asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey * * @param createKeyOptions The key configuration object containing information about the key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code keyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code keyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) { try { return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) { Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createKeyOptions.getKeyType()) .setKeyOps(createKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createKeyOptions)) .setReleasePolicy(createKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error)); } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the * call asynchronously and prints out the newly created key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { try { return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa * key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It * requires the {@code keys/create} permission. * * <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions * optionally specified. The {@link CreateRsaKeyOptions * {@link CreateRsaKeyOptions * CreateRsaKeyOptions * * <p>The {@link CreateRsaKeyOptions * include: {@link KeyType * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse * * @param createRsaKeyOptions The key configuration object containing information about the rsa key being * created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) { try { return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) { Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createRsaKeyOptions.getKeyType()) .setKeySize(createRsaKeyOptions.getKeySize()) .setKeyOps(createRsaKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions)) .setReleasePolicy(createRsaKeyOptions.getReleasePolicy()) .setPublicExponent(createRsaKeyOptions.getPublicExponent()); return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error)); } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * if not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing the {@link KeyVaultKey created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) { try { return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key * type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires * the {@code keys/create} permission. * * <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions * optionally specified. If not specified, default value of {@link KeyCurveName * Vault. The {@link CreateEcKeyOptions * values are optional. The {@link CreateEcKeyOptions * not specified.</p> * * <p>The {@link CreateEcKeyOptions * {@link KeyType * * <p><strong>Code Samples</strong></p> * <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year. * Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been * received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse * * @param createEcKeyOptions The key options object containing information about the ec key being created. * @return A {@link Mono} containing a {@link Response} whose {@link Response * created key}. * @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}. * @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) { try { return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) { Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setKty(createEcKeyOptions.getKeyType()) .setCurve(createEcKeyOptions.getCurveName()) .setKeyOps(createEcKeyOptions.getKeyOperations()) .setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions)) .setReleasePolicy(createEcKeyOptions.getReleasePolicy()); return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws HttpResponseException if {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) { try { return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial); return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * {@link ImportKeyOptions * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing the {@link KeyVaultKey imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) { try { return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Imports an externally created key and stores it in key vault. The import key operation may be used to import any * key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the * key. This operation requires the {@code keys/import} permission. * * <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions * ImportKeyOptions * {@link ImportKeyOptions * no values are set for the fields. The {@link ImportKeyOptions * field is set to true and the {@link ImportKeyOptions * are not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse * * @param importKeyOptions The key import configuration object containing information about the json web key * being imported. * @return A {@link Mono} containing a {@link Response} whose {@link Response * imported key}. * @throws NullPointerException if {@code keyImportOptions} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) { try { return withContext(context -> importKeyWithResponse(importKeyOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) { Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null."); context = context == null ? Context.NONE : context; KeyImportRequestParameters parameters = new KeyImportRequestParameters() .setKey(importKeyOptions.getKey()) .setHsm(importKeyOptions.isHardwareProtected()) .setKeyAttributes(new KeyRequestAttributes(importKeyOptions)) .setReleasePolicy(importKeyOptions.getReleasePolicy()); return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName())) .doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error)); } /** * Exports the latest version of a key from the key vault. The export key operation may be used to import any key * from the Azure Key Vault as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name} or {@code environment} are {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKey * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing the {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> exportKey(String name, String version, String environment) { try { return exportKeyWithResponse(name, version, environment).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Exports a key from the key vault. The export key operation may be used to import any key from the Azure Key Vault * as long as it is marked as exportable and its release policy is satisfied. * * <p><strong>Code Samples</strong></p> * <p>Exports a key from a key vault. Subscribes to the call asynchronously and prints out the newly exported key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.exportKeyWithResponse * * @param name The name of the key to be exported. * @param version The key version. * @param environment The target environment assertion. * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey exported key}. * @throws NullPointerException If the specified {@code name}, {@code version} or {@code environment} are * {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment) { try { return withContext(context -> exportKeyWithResponse(name, version, environment, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> exportKeyWithResponse(String name, String version, String environment, Context context) { Objects.requireNonNull(name, "The key name cannot be null."); Objects.requireNonNull(version, "The key version cannot be null."); Objects.requireNonNull(environment, "The environment parameter cannot be null."); context = context == null ? Context.NONE : context; KeyExportRequestParameters parameters = new KeyExportRequestParameters().setEnvironment(environment); return service.exportKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Exporting key - {}", name)) .doOnSuccess(response -> logger.info("Exported key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to export key - {}", name, error)); } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * The content of the key is null if both {@code name} and {@code version} are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name, String version) { try { return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of the specified key and key version. The get key operation is applicable to all key types * and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse * * @param name The name of the key, cannot be null * @param version The version of the key to retrieve. If this is an empty String or null, this call is * equivalent to calling {@link KeyAsyncClient * @return A {@link Mono} containing a {@link Response} whose {@link Response * {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version} * are null or empty. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or * an empty/null {@code name} and a non null/empty {@code version} is provided. * @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) { try { return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Get the public part of the latest version of the specified key from the key vault. The get key operation is * applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the * returned key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey * * @param name The name of the key. * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null * if {@code name} is null or empty. * @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault. * @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> getKey(String name) { try { return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates the attributes and key operations associated with the specified key, but not the cryptographic key * material of the specified key in the key vault. The update operation changes specified attributes of an existing * stored key and attributes that are not specified in the request are left unchanged. The cryptographic key * material of a key itself cannot be changed. This operation requires the {@code keys/set} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault. * Subscribes to the call asynchronously and prints out the returned key details when a response has been received. * </p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated key operations to associate with the key. * @return A {@link Mono} containing the {@link KeyVaultKey updated key}. * @throws NullPointerException if {@code key} is {@code null}. * @throws ResourceNotFoundException when a key with {@link KeyProperties * version} doesn't exist in the key vault. * @throws HttpResponseException if {@link KeyProperties * string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) { try { return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); context = context == null ? Context.NONE : context; KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)) .setReleasePolicy(keyProperties.getReleasePolicy()); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) { return beginDeleteKey(name, getDefaultPollingInterval()); } /** * Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed * in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The * delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version * of a key. This operation removes the cryptographic material associated with the key, which means the key is not * usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the * {@code keys/delete} permission. * * <p><strong>Code Samples</strong></p> * <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key * details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey * * @param name The name of the key to be deleted. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, activationOperation(name), createPollOperation(name), (context, firstResponse) -> Mono.empty(), (context) -> Mono.empty()); } private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context)) .flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedKeyResponse -> { if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) { return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey * * @param name The name of the deleted key. * @return A {@link Mono} containing the {@link DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DeletedKey> getDeletedKey(String name) { try { return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled * vaults. This operation requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the deleted key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DeletedKey deleted key}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) { try { return withContext(context -> getDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey * * @param name The name of the deleted key. * @return An empty {@link Mono}. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> purgeDeletedKey(String name) { try { return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is * applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission. * * <p><strong>Code Samples</strong></p> * <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the status code from the server response when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse * * @param name The name of the deleted key. * @return A {@link Mono} containing a Response containing status code and HTTP headers. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) { try { return withContext(context -> purgeDeletedKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) { return beginRecoverDeletedKey(name, getDefaultPollingInterval()); } /** * Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete * enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the * delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission. * * <p><strong>Code Samples</strong></p> * <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and * prints out the recovered key details when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey * * @param name The name of the deleted key to be recovered. * @param pollingInterval The interval at which the operation status will be polled for. * @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) { return new PollerFlux<>(pollingInterval, recoverActivationOperation(name), createRecoverPollOperation(name), (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); } private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context)) .flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(keyResponse -> { if (keyResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) { return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey * * @param name The name of the key. * @return A {@link Mono} containing the backed up key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<byte[]> backupKey(String name) { try { return backupKeyWithResponse(name).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from * Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be * used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM * or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure * Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup * operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a * key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a * backup from one geographical area cannot be restored to another geographical area. For example, a backup from the * US geographical area cannot be restored in an EU geographical area. This operation requires the {@code * key/backup} permission. * * <p><strong>Code Samples</strong></p> * <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the * key's backup byte array returned in the response.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse * * @param name The name of the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * key blob. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a key with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<byte[]>> backupKeyWithResponse(String name) { try { return withContext(context -> backupKeyWithResponse(name, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing the {@link KeyVaultKey restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) { try { return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key, * its key identifier, attributes and access control policies. The restore operation may be used to import a * previously backed up key. The individual versions of a key cannot be restored. The key is restored in its * entirety with the same key name as it had when it was backed up. If the key name is not available in the target * Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key * identifier will change if the key is restored to a different vault. Restore will restore all versions and * preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must * be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission * in the target Key Vault. This operation requires the {@code keys/restore} permission. * * <p><strong>Code Samples</strong></p> * <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the * restored key details when a response has been received.</p> * * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse * * @param backup The backup blob associated with the key. * @return A {@link Mono} containing a {@link Response} whose {@link Response * restored key}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) { try { return withContext(context -> restoreKeyBackupWithResponse(backup, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup); return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore key - {}", error)); } /** * List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain * the public part of a stored key. The List operation is applicable to all key types and the individual key * response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are * provided in the response. The key material and individual key versions are not listed in the response. This * operation requires the {@code keys/list} permission. * * <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing * {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys} * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeys() { try { return new PagedFlux<>( () -> withContext(context -> listKeysFirstPage(context)), continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) { return new PagedFlux<>( () -> listKeysFirstPage(context), continuationToken -> listKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) { try { return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing keys")) .doOnSuccess(response -> logger.info("Listed keys")) .doOnError(error -> logger.warning("Failed to list keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures * that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled * for soft-delete. This operation requires the {@code keys/list} permission. * * <p><strong>Code Samples</strong></p> * <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id * of each deleted key when a response has been received.</p> * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys} * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<DeletedKey> listDeletedKeys() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedKeysFirstPage(context)), continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<DeletedKey> listDeletedKeys(Context context) { return new PagedFlux<>( () -> listDeletedKeysFirstPage(context), continuationToken -> listDeletedKeysNextPage(continuationToken, context)); } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) { try { return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) { try { return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing deleted keys")) .doOnSuccess(response -> logger.info("Listed deleted keys")) .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties} * as only the key identifier, attributes and tags are provided in the response. The key material values are * not provided in the response. This operation requires the {@code keys/list} permission. * * <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link * Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using * {@link KeyAsyncClient * * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions} * * @param name The name of the key. * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault. * Flux is empty if key with {@code name} does not exist in key vault. * @throws ResourceNotFoundException when a given key {@code name} is null or an empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listKeyVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) { return new PagedFlux<>( () -> listKeyVersionsFirstPage(name, context), continuationToken -> listKeyVersionsNextPage(continuationToken, context)); } private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) { try { return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) .doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link KeyAsyncClient * * @param continuationToken The {@link PagedResponse * listKeys operations. * @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results. */ private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) { try { return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
should accept be called if AutoComplete is disabled ?
public void onNext(ServiceBusMessageContext serviceBusMessageContext) { if (serviceBusMessageContext.hasError()) { handleError(serviceBusMessageContext.getThrowable()); } else { try { ServiceBusReceivedMessageContext serviceBusReceivedMessageContext = new ServiceBusReceivedMessageContext(receiverClient, serviceBusMessageContext); processMessage.accept(serviceBusReceivedMessageContext); } catch (Exception ex) { handleError(new ServiceBusReceiverException(ex, ServiceBusErrorSource.USER_CALLBACK)); if (!processorOptions.isDisableAutoComplete()) { logger.warning("Error when processing message. Abandoning message.", ex); abandonMessage(serviceBusMessageContext, receiverClient); } } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } }
processMessage.accept(serviceBusReceivedMessageContext);
public void onNext(ServiceBusMessageContext serviceBusMessageContext) { if (serviceBusMessageContext.hasError()) { handleError(serviceBusMessageContext.getThrowable()); } else { try { ServiceBusReceivedMessageContext serviceBusReceivedMessageContext = new ServiceBusReceivedMessageContext(receiverClient, serviceBusMessageContext); processMessage.accept(serviceBusReceivedMessageContext); } catch (Exception ex) { handleError(new ServiceBusReceiverException(ex, ServiceBusErrorSource.USER_CALLBACK)); if (!processorOptions.isDisableAutoComplete()) { logger.warning("Error when processing message. Abandoning message.", ex); abandonMessage(serviceBusMessageContext, receiverClient); } } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } }
class ServiceBusProcessorClient implements AutoCloseable { private static final int SCHEDULER_INTERVAL_IN_SECONDS = 10; private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClient.class); private final ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder; private final ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder; private final Consumer<ServiceBusReceivedMessageContext> processMessage; private final Consumer<Throwable> processError; private final ServiceBusProcessorClientOptions processorOptions; private final AtomicReference<Subscription> receiverSubscription = new AtomicReference<>(); private final AtomicReference<ServiceBusReceiverAsyncClient> asyncClient = new AtomicReference<>(); private final AtomicBoolean isRunning = new AtomicBoolean(); private ScheduledExecutorService scheduledExecutor; /** * Constructor to create a sessions-enabled processor. * * @param sessionReceiverBuilder The session processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.sessionReceiverBuilder = Objects.requireNonNull(sessionReceiverBuilder, "'sessionReceiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(sessionReceiverBuilder.buildAsyncClientForProcessor()); this.receiverBuilder = null; } /** * Constructor to create a processor. * * @param receiverBuilder The processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.receiverBuilder = Objects.requireNonNull(receiverBuilder, "'receiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(receiverBuilder.buildAsyncClient()); this.sessionReceiverBuilder = null; } /** * Starts the processor in the background. When this method is called, the processor will initiate a message * receiver that will invoke the message handler when new messages are available. This method is idempotent i.e * calling {@link * after calling {@link * sessions. Calling {@link * a new set of sessions will be processed. */ public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } receiveMessages(); this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } /** * Stops the message processing for this processor. The receiving links and sessions are kept active and this * processor can resume processing messages by calling {@link */ public synchronized void stop() { isRunning.set(false); } /** * Stops message processing and closes the processor. The receiving links and sessions are closed and calling * {@link */ @Override public synchronized void close() { isRunning.set(false); if (receiverSubscription.get() != null) { receiverSubscription.get().cancel(); } asyncClient.get().close(); scheduledExecutor.shutdown(); } /** * Returns {@code true} if the processor is running. If the processor is stopped or closed, this method returns * {@code false}. * * @return {@code true} if the processor is running. */ public synchronized boolean isRunning() { return isRunning.get(); } private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessagesWithContext() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); } private void abandonMessage(ServiceBusMessageContext serviceBusMessageContext, ServiceBusReceiverAsyncClient receiverClient) { try { receiverClient.abandon(serviceBusMessageContext.getMessage()).block(); } catch (Exception exception) { logger.verbose("Failed to abandon message", exception); } } private void handleError(Throwable throwable) { try { processError.accept(throwable); } catch (Exception ex) { logger.verbose("Error from error handler. Ignoring error.", ex); } } private void restartMessageReceiver() { receiverSubscription.set(null); ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.close(); ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); receiveMessages(); } }
class ServiceBusProcessorClient implements AutoCloseable { private static final int SCHEDULER_INTERVAL_IN_SECONDS = 10; private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClient.class); private final ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder; private final ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder; private final Consumer<ServiceBusReceivedMessageContext> processMessage; private final Consumer<Throwable> processError; private final ServiceBusProcessorClientOptions processorOptions; private final AtomicReference<Subscription> receiverSubscription = new AtomicReference<>(); private final AtomicReference<ServiceBusReceiverAsyncClient> asyncClient = new AtomicReference<>(); private final AtomicBoolean isRunning = new AtomicBoolean(); private ScheduledExecutorService scheduledExecutor; /** * Constructor to create a sessions-enabled processor. * * @param sessionReceiverBuilder The session processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.sessionReceiverBuilder = Objects.requireNonNull(sessionReceiverBuilder, "'sessionReceiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(sessionReceiverBuilder.buildAsyncClientForProcessor()); this.receiverBuilder = null; } /** * Constructor to create a processor. * * @param receiverBuilder The processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.receiverBuilder = Objects.requireNonNull(receiverBuilder, "'receiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(receiverBuilder.buildAsyncClient()); this.sessionReceiverBuilder = null; } /** * Starts the processor in the background. When this method is called, the processor will initiate a message * receiver that will invoke the message handler when new messages are available. This method is idempotent i.e * calling {@link * after calling {@link * sessions. Calling {@link * a new set of sessions will be processed. */ public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } receiveMessages(); this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } /** * Stops the message processing for this processor. The receiving links and sessions are kept active and this * processor can resume processing messages by calling {@link */ public synchronized void stop() { isRunning.set(false); } /** * Stops message processing and closes the processor. The receiving links and sessions are closed and calling * {@link */ @Override public synchronized void close() { isRunning.set(false); if (receiverSubscription.get() != null) { receiverSubscription.get().cancel(); } asyncClient.get().close(); scheduledExecutor.shutdown(); } /** * Returns {@code true} if the processor is running. If the processor is stopped or closed, this method returns * {@code false}. * * @return {@code true} if the processor is running. */ public synchronized boolean isRunning() { return isRunning.get(); } private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessagesWithContext() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); } private void abandonMessage(ServiceBusMessageContext serviceBusMessageContext, ServiceBusReceiverAsyncClient receiverClient) { try { receiverClient.abandon(serviceBusMessageContext.getMessage()).block(); } catch (Exception exception) { logger.verbose("Failed to abandon message", exception); } } private void handleError(Throwable throwable) { try { processError.accept(throwable); } catch (Exception ex) { logger.verbose("Error from error handler. Ignoring error.", ex); } } private void restartMessageReceiver() { receiverSubscription.set(null); ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.close(); ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); receiveMessages(); } }
Do you need to complete the message if isDisableAutoComplete() == false? This statement is from above,"By default, a successfully processed message is * {@link ServiceBusReceivedMessageContext#complete() completed}"
public void onNext(ServiceBusMessageContext serviceBusMessageContext) { if (serviceBusMessageContext.hasError()) { handleError(serviceBusMessageContext.getThrowable()); } else { try { ServiceBusReceivedMessageContext serviceBusReceivedMessageContext = new ServiceBusReceivedMessageContext(receiverClient, serviceBusMessageContext); processMessage.accept(serviceBusReceivedMessageContext); } catch (Exception ex) { handleError(new ServiceBusReceiverException(ex, ServiceBusErrorSource.USER_CALLBACK)); if (!processorOptions.isDisableAutoComplete()) { logger.warning("Error when processing message. Abandoning message.", ex); abandonMessage(serviceBusMessageContext, receiverClient); } } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } }
processMessage.accept(serviceBusReceivedMessageContext);
public void onNext(ServiceBusMessageContext serviceBusMessageContext) { if (serviceBusMessageContext.hasError()) { handleError(serviceBusMessageContext.getThrowable()); } else { try { ServiceBusReceivedMessageContext serviceBusReceivedMessageContext = new ServiceBusReceivedMessageContext(receiverClient, serviceBusMessageContext); processMessage.accept(serviceBusReceivedMessageContext); } catch (Exception ex) { handleError(new ServiceBusReceiverException(ex, ServiceBusErrorSource.USER_CALLBACK)); if (!processorOptions.isDisableAutoComplete()) { logger.warning("Error when processing message. Abandoning message.", ex); abandonMessage(serviceBusMessageContext, receiverClient); } } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } }
class ServiceBusProcessorClient implements AutoCloseable { private static final int SCHEDULER_INTERVAL_IN_SECONDS = 10; private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClient.class); private final ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder; private final ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder; private final Consumer<ServiceBusReceivedMessageContext> processMessage; private final Consumer<Throwable> processError; private final ServiceBusProcessorClientOptions processorOptions; private final AtomicReference<Subscription> receiverSubscription = new AtomicReference<>(); private final AtomicReference<ServiceBusReceiverAsyncClient> asyncClient = new AtomicReference<>(); private final AtomicBoolean isRunning = new AtomicBoolean(); private ScheduledExecutorService scheduledExecutor; /** * Constructor to create a sessions-enabled processor. * * @param sessionReceiverBuilder The session processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.sessionReceiverBuilder = Objects.requireNonNull(sessionReceiverBuilder, "'sessionReceiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(sessionReceiverBuilder.buildAsyncClientForProcessor()); this.receiverBuilder = null; } /** * Constructor to create a processor. * * @param receiverBuilder The processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.receiverBuilder = Objects.requireNonNull(receiverBuilder, "'receiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(receiverBuilder.buildAsyncClient()); this.sessionReceiverBuilder = null; } /** * Starts the processor in the background. When this method is called, the processor will initiate a message * receiver that will invoke the message handler when new messages are available. This method is idempotent i.e * calling {@link * after calling {@link * sessions. Calling {@link * a new set of sessions will be processed. */ public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } receiveMessages(); this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } /** * Stops the message processing for this processor. The receiving links and sessions are kept active and this * processor can resume processing messages by calling {@link */ public synchronized void stop() { isRunning.set(false); } /** * Stops message processing and closes the processor. The receiving links and sessions are closed and calling * {@link */ @Override public synchronized void close() { isRunning.set(false); if (receiverSubscription.get() != null) { receiverSubscription.get().cancel(); } asyncClient.get().close(); scheduledExecutor.shutdown(); } /** * Returns {@code true} if the processor is running. If the processor is stopped or closed, this method returns * {@code false}. * * @return {@code true} if the processor is running. */ public synchronized boolean isRunning() { return isRunning.get(); } private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessagesWithContext() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); } private void abandonMessage(ServiceBusMessageContext serviceBusMessageContext, ServiceBusReceiverAsyncClient receiverClient) { try { receiverClient.abandon(serviceBusMessageContext.getMessage()).block(); } catch (Exception exception) { logger.verbose("Failed to abandon message", exception); } } private void handleError(Throwable throwable) { try { processError.accept(throwable); } catch (Exception ex) { logger.verbose("Error from error handler. Ignoring error.", ex); } } private void restartMessageReceiver() { receiverSubscription.set(null); ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.close(); ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); receiveMessages(); } }
class ServiceBusProcessorClient implements AutoCloseable { private static final int SCHEDULER_INTERVAL_IN_SECONDS = 10; private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClient.class); private final ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder; private final ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder; private final Consumer<ServiceBusReceivedMessageContext> processMessage; private final Consumer<Throwable> processError; private final ServiceBusProcessorClientOptions processorOptions; private final AtomicReference<Subscription> receiverSubscription = new AtomicReference<>(); private final AtomicReference<ServiceBusReceiverAsyncClient> asyncClient = new AtomicReference<>(); private final AtomicBoolean isRunning = new AtomicBoolean(); private ScheduledExecutorService scheduledExecutor; /** * Constructor to create a sessions-enabled processor. * * @param sessionReceiverBuilder The session processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.sessionReceiverBuilder = Objects.requireNonNull(sessionReceiverBuilder, "'sessionReceiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(sessionReceiverBuilder.buildAsyncClientForProcessor()); this.receiverBuilder = null; } /** * Constructor to create a processor. * * @param receiverBuilder The processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.receiverBuilder = Objects.requireNonNull(receiverBuilder, "'receiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(receiverBuilder.buildAsyncClient()); this.sessionReceiverBuilder = null; } /** * Starts the processor in the background. When this method is called, the processor will initiate a message * receiver that will invoke the message handler when new messages are available. This method is idempotent i.e * calling {@link * after calling {@link * sessions. Calling {@link * a new set of sessions will be processed. */ public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } receiveMessages(); this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } /** * Stops the message processing for this processor. The receiving links and sessions are kept active and this * processor can resume processing messages by calling {@link */ public synchronized void stop() { isRunning.set(false); } /** * Stops message processing and closes the processor. The receiving links and sessions are closed and calling * {@link */ @Override public synchronized void close() { isRunning.set(false); if (receiverSubscription.get() != null) { receiverSubscription.get().cancel(); } asyncClient.get().close(); scheduledExecutor.shutdown(); } /** * Returns {@code true} if the processor is running. If the processor is stopped or closed, this method returns * {@code false}. * * @return {@code true} if the processor is running. */ public synchronized boolean isRunning() { return isRunning.get(); } private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessagesWithContext() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); } private void abandonMessage(ServiceBusMessageContext serviceBusMessageContext, ServiceBusReceiverAsyncClient receiverClient) { try { receiverClient.abandon(serviceBusMessageContext.getMessage()).block(); } catch (Exception exception) { logger.verbose("Failed to abandon message", exception); } } private void handleError(Throwable throwable) { try { processError.accept(throwable); } catch (Exception ex) { logger.verbose("Error from error handler. Ignoring error.", ex); } } private void restartMessageReceiver() { receiverSubscription.set(null); ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.close(); ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); receiveMessages(); } }
`accept` calls the user's message handler. It's not related to `autoComplete`
public void onNext(ServiceBusMessageContext serviceBusMessageContext) { if (serviceBusMessageContext.hasError()) { handleError(serviceBusMessageContext.getThrowable()); } else { try { ServiceBusReceivedMessageContext serviceBusReceivedMessageContext = new ServiceBusReceivedMessageContext(receiverClient, serviceBusMessageContext); processMessage.accept(serviceBusReceivedMessageContext); } catch (Exception ex) { handleError(new ServiceBusReceiverException(ex, ServiceBusErrorSource.USER_CALLBACK)); if (!processorOptions.isDisableAutoComplete()) { logger.warning("Error when processing message. Abandoning message.", ex); abandonMessage(serviceBusMessageContext, receiverClient); } } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } }
processMessage.accept(serviceBusReceivedMessageContext);
public void onNext(ServiceBusMessageContext serviceBusMessageContext) { if (serviceBusMessageContext.hasError()) { handleError(serviceBusMessageContext.getThrowable()); } else { try { ServiceBusReceivedMessageContext serviceBusReceivedMessageContext = new ServiceBusReceivedMessageContext(receiverClient, serviceBusMessageContext); processMessage.accept(serviceBusReceivedMessageContext); } catch (Exception ex) { handleError(new ServiceBusReceiverException(ex, ServiceBusErrorSource.USER_CALLBACK)); if (!processorOptions.isDisableAutoComplete()) { logger.warning("Error when processing message. Abandoning message.", ex); abandonMessage(serviceBusMessageContext, receiverClient); } } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } }
class ServiceBusProcessorClient implements AutoCloseable { private static final int SCHEDULER_INTERVAL_IN_SECONDS = 10; private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClient.class); private final ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder; private final ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder; private final Consumer<ServiceBusReceivedMessageContext> processMessage; private final Consumer<Throwable> processError; private final ServiceBusProcessorClientOptions processorOptions; private final AtomicReference<Subscription> receiverSubscription = new AtomicReference<>(); private final AtomicReference<ServiceBusReceiverAsyncClient> asyncClient = new AtomicReference<>(); private final AtomicBoolean isRunning = new AtomicBoolean(); private ScheduledExecutorService scheduledExecutor; /** * Constructor to create a sessions-enabled processor. * * @param sessionReceiverBuilder The session processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.sessionReceiverBuilder = Objects.requireNonNull(sessionReceiverBuilder, "'sessionReceiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(sessionReceiverBuilder.buildAsyncClientForProcessor()); this.receiverBuilder = null; } /** * Constructor to create a processor. * * @param receiverBuilder The processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.receiverBuilder = Objects.requireNonNull(receiverBuilder, "'receiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(receiverBuilder.buildAsyncClient()); this.sessionReceiverBuilder = null; } /** * Starts the processor in the background. When this method is called, the processor will initiate a message * receiver that will invoke the message handler when new messages are available. This method is idempotent i.e * calling {@link * after calling {@link * sessions. Calling {@link * a new set of sessions will be processed. */ public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } receiveMessages(); this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } /** * Stops the message processing for this processor. The receiving links and sessions are kept active and this * processor can resume processing messages by calling {@link */ public synchronized void stop() { isRunning.set(false); } /** * Stops message processing and closes the processor. The receiving links and sessions are closed and calling * {@link */ @Override public synchronized void close() { isRunning.set(false); if (receiverSubscription.get() != null) { receiverSubscription.get().cancel(); } asyncClient.get().close(); scheduledExecutor.shutdown(); } /** * Returns {@code true} if the processor is running. If the processor is stopped or closed, this method returns * {@code false}. * * @return {@code true} if the processor is running. */ public synchronized boolean isRunning() { return isRunning.get(); } private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessagesWithContext() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); } private void abandonMessage(ServiceBusMessageContext serviceBusMessageContext, ServiceBusReceiverAsyncClient receiverClient) { try { receiverClient.abandon(serviceBusMessageContext.getMessage()).block(); } catch (Exception exception) { logger.verbose("Failed to abandon message", exception); } } private void handleError(Throwable throwable) { try { processError.accept(throwable); } catch (Exception ex) { logger.verbose("Error from error handler. Ignoring error.", ex); } } private void restartMessageReceiver() { receiverSubscription.set(null); ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.close(); ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); receiveMessages(); } }
class ServiceBusProcessorClient implements AutoCloseable { private static final int SCHEDULER_INTERVAL_IN_SECONDS = 10; private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClient.class); private final ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder; private final ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder; private final Consumer<ServiceBusReceivedMessageContext> processMessage; private final Consumer<Throwable> processError; private final ServiceBusProcessorClientOptions processorOptions; private final AtomicReference<Subscription> receiverSubscription = new AtomicReference<>(); private final AtomicReference<ServiceBusReceiverAsyncClient> asyncClient = new AtomicReference<>(); private final AtomicBoolean isRunning = new AtomicBoolean(); private ScheduledExecutorService scheduledExecutor; /** * Constructor to create a sessions-enabled processor. * * @param sessionReceiverBuilder The session processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.sessionReceiverBuilder = Objects.requireNonNull(sessionReceiverBuilder, "'sessionReceiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(sessionReceiverBuilder.buildAsyncClientForProcessor()); this.receiverBuilder = null; } /** * Constructor to create a processor. * * @param receiverBuilder The processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.receiverBuilder = Objects.requireNonNull(receiverBuilder, "'receiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(receiverBuilder.buildAsyncClient()); this.sessionReceiverBuilder = null; } /** * Starts the processor in the background. When this method is called, the processor will initiate a message * receiver that will invoke the message handler when new messages are available. This method is idempotent i.e * calling {@link * after calling {@link * sessions. Calling {@link * a new set of sessions will be processed. */ public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } receiveMessages(); this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } /** * Stops the message processing for this processor. The receiving links and sessions are kept active and this * processor can resume processing messages by calling {@link */ public synchronized void stop() { isRunning.set(false); } /** * Stops message processing and closes the processor. The receiving links and sessions are closed and calling * {@link */ @Override public synchronized void close() { isRunning.set(false); if (receiverSubscription.get() != null) { receiverSubscription.get().cancel(); } asyncClient.get().close(); scheduledExecutor.shutdown(); } /** * Returns {@code true} if the processor is running. If the processor is stopped or closed, this method returns * {@code false}. * * @return {@code true} if the processor is running. */ public synchronized boolean isRunning() { return isRunning.get(); } private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessagesWithContext() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); } private void abandonMessage(ServiceBusMessageContext serviceBusMessageContext, ServiceBusReceiverAsyncClient receiverClient) { try { receiverClient.abandon(serviceBusMessageContext.getMessage()).block(); } catch (Exception exception) { logger.verbose("Failed to abandon message", exception); } } private void handleError(Throwable throwable) { try { processError.accept(throwable); } catch (Exception ex) { logger.verbose("Error from error handler. Ignoring error.", ex); } } private void restartMessageReceiver() { receiverSubscription.set(null); ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.close(); ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); receiveMessages(); } }
The underlying async receiver will do that automatically because I delegate that to the async client in the builder.
public void onNext(ServiceBusMessageContext serviceBusMessageContext) { if (serviceBusMessageContext.hasError()) { handleError(serviceBusMessageContext.getThrowable()); } else { try { ServiceBusReceivedMessageContext serviceBusReceivedMessageContext = new ServiceBusReceivedMessageContext(receiverClient, serviceBusMessageContext); processMessage.accept(serviceBusReceivedMessageContext); } catch (Exception ex) { handleError(new ServiceBusReceiverException(ex, ServiceBusErrorSource.USER_CALLBACK)); if (!processorOptions.isDisableAutoComplete()) { logger.warning("Error when processing message. Abandoning message.", ex); abandonMessage(serviceBusMessageContext, receiverClient); } } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } }
processMessage.accept(serviceBusReceivedMessageContext);
public void onNext(ServiceBusMessageContext serviceBusMessageContext) { if (serviceBusMessageContext.hasError()) { handleError(serviceBusMessageContext.getThrowable()); } else { try { ServiceBusReceivedMessageContext serviceBusReceivedMessageContext = new ServiceBusReceivedMessageContext(receiverClient, serviceBusMessageContext); processMessage.accept(serviceBusReceivedMessageContext); } catch (Exception ex) { handleError(new ServiceBusReceiverException(ex, ServiceBusErrorSource.USER_CALLBACK)); if (!processorOptions.isDisableAutoComplete()) { logger.warning("Error when processing message. Abandoning message.", ex); abandonMessage(serviceBusMessageContext, receiverClient); } } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } }
class ServiceBusProcessorClient implements AutoCloseable { private static final int SCHEDULER_INTERVAL_IN_SECONDS = 10; private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClient.class); private final ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder; private final ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder; private final Consumer<ServiceBusReceivedMessageContext> processMessage; private final Consumer<Throwable> processError; private final ServiceBusProcessorClientOptions processorOptions; private final AtomicReference<Subscription> receiverSubscription = new AtomicReference<>(); private final AtomicReference<ServiceBusReceiverAsyncClient> asyncClient = new AtomicReference<>(); private final AtomicBoolean isRunning = new AtomicBoolean(); private ScheduledExecutorService scheduledExecutor; /** * Constructor to create a sessions-enabled processor. * * @param sessionReceiverBuilder The session processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.sessionReceiverBuilder = Objects.requireNonNull(sessionReceiverBuilder, "'sessionReceiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(sessionReceiverBuilder.buildAsyncClientForProcessor()); this.receiverBuilder = null; } /** * Constructor to create a processor. * * @param receiverBuilder The processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.receiverBuilder = Objects.requireNonNull(receiverBuilder, "'receiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(receiverBuilder.buildAsyncClient()); this.sessionReceiverBuilder = null; } /** * Starts the processor in the background. When this method is called, the processor will initiate a message * receiver that will invoke the message handler when new messages are available. This method is idempotent i.e * calling {@link * after calling {@link * sessions. Calling {@link * a new set of sessions will be processed. */ public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } receiveMessages(); this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } /** * Stops the message processing for this processor. The receiving links and sessions are kept active and this * processor can resume processing messages by calling {@link */ public synchronized void stop() { isRunning.set(false); } /** * Stops message processing and closes the processor. The receiving links and sessions are closed and calling * {@link */ @Override public synchronized void close() { isRunning.set(false); if (receiverSubscription.get() != null) { receiverSubscription.get().cancel(); } asyncClient.get().close(); scheduledExecutor.shutdown(); } /** * Returns {@code true} if the processor is running. If the processor is stopped or closed, this method returns * {@code false}. * * @return {@code true} if the processor is running. */ public synchronized boolean isRunning() { return isRunning.get(); } private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessagesWithContext() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); } private void abandonMessage(ServiceBusMessageContext serviceBusMessageContext, ServiceBusReceiverAsyncClient receiverClient) { try { receiverClient.abandon(serviceBusMessageContext.getMessage()).block(); } catch (Exception exception) { logger.verbose("Failed to abandon message", exception); } } private void handleError(Throwable throwable) { try { processError.accept(throwable); } catch (Exception ex) { logger.verbose("Error from error handler. Ignoring error.", ex); } } private void restartMessageReceiver() { receiverSubscription.set(null); ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.close(); ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); receiveMessages(); } }
class ServiceBusProcessorClient implements AutoCloseable { private static final int SCHEDULER_INTERVAL_IN_SECONDS = 10; private final ClientLogger logger = new ClientLogger(ServiceBusProcessorClient.class); private final ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder; private final ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder; private final Consumer<ServiceBusReceivedMessageContext> processMessage; private final Consumer<Throwable> processError; private final ServiceBusProcessorClientOptions processorOptions; private final AtomicReference<Subscription> receiverSubscription = new AtomicReference<>(); private final AtomicReference<ServiceBusReceiverAsyncClient> asyncClient = new AtomicReference<>(); private final AtomicBoolean isRunning = new AtomicBoolean(); private ScheduledExecutorService scheduledExecutor; /** * Constructor to create a sessions-enabled processor. * * @param sessionReceiverBuilder The session processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusSessionReceiverClientBuilder sessionReceiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.sessionReceiverBuilder = Objects.requireNonNull(sessionReceiverBuilder, "'sessionReceiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(sessionReceiverBuilder.buildAsyncClientForProcessor()); this.receiverBuilder = null; } /** * Constructor to create a processor. * * @param receiverBuilder The processor builder to create new instances of async clients. * @param processMessage The message processing callback. * @param processError The error handler. * @param processorOptions Options to configure this instance of the processor. */ ServiceBusProcessorClient(ServiceBusClientBuilder.ServiceBusReceiverClientBuilder receiverBuilder, Consumer<ServiceBusReceivedMessageContext> processMessage, Consumer<Throwable> processError, ServiceBusProcessorClientOptions processorOptions) { this.receiverBuilder = Objects.requireNonNull(receiverBuilder, "'receiverBuilder' cannot be null"); this.processMessage = Objects.requireNonNull(processMessage, "'processMessage' cannot be null"); this.processError = Objects.requireNonNull(processError, "'processError' cannot be null"); this.processorOptions = Objects.requireNonNull(processorOptions, "'processorOptions' cannot be null"); this.asyncClient.set(receiverBuilder.buildAsyncClient()); this.sessionReceiverBuilder = null; } /** * Starts the processor in the background. When this method is called, the processor will initiate a message * receiver that will invoke the message handler when new messages are available. This method is idempotent i.e * calling {@link * after calling {@link * sessions. Calling {@link * a new set of sessions will be processed. */ public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } receiveMessages(); this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } /** * Stops the message processing for this processor. The receiving links and sessions are kept active and this * processor can resume processing messages by calling {@link */ public synchronized void stop() { isRunning.set(false); } /** * Stops message processing and closes the processor. The receiving links and sessions are closed and calling * {@link */ @Override public synchronized void close() { isRunning.set(false); if (receiverSubscription.get() != null) { receiverSubscription.get().cancel(); } asyncClient.get().close(); scheduledExecutor.shutdown(); } /** * Returns {@code true} if the processor is running. If the processor is stopped or closed, this method returns * {@code false}. * * @return {@code true} if the processor is running. */ public synchronized boolean isRunning() { return isRunning.get(); } private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessagesWithContext() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); } private void abandonMessage(ServiceBusMessageContext serviceBusMessageContext, ServiceBusReceiverAsyncClient receiverClient) { try { receiverClient.abandon(serviceBusMessageContext.getMessage()).block(); } catch (Exception exception) { logger.verbose("Failed to abandon message", exception); } } private void handleError(Throwable throwable) { try { processError.accept(throwable); } catch (Exception ex) { logger.verbose("Error from error handler. Ignoring error.", ex); } } private void restartMessageReceiver() { receiverSubscription.set(null); ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.close(); ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); receiveMessages(); } }
also can we replace this with ObjectNode? Some of the existing tests use Document but for new tests it is better to move to the new model.
private Document getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); Document doc = new Document(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , uuid, uuid)); return doc; }
Document doc = new Document(String.format("{ "
private Document getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); Document doc = new Document(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , uuid, uuid)); return doc; }
class ConnectionStateListenerTest { private static int port = 8082; private static String serverUriString = "rntbd: private static final Logger logger = LoggerFactory.getLogger(ConnectionStateListenerTest.class); @DataProvider(name = "connectionStateListenerConfigProvider") public Object[][] connectionStateListenerConfigProvider() { return new Object[][]{ {true, RequestResponseType.CHANNEL_FIN, 1}, {false, RequestResponseType.CHANNEL_FIN, 0}, {true, RequestResponseType.CHANNEL_RST, 0}, {false, RequestResponseType.CHANNEL_RST, 0}, }; } @Test(groups = { "unit" }, dataProvider = "connectionStateListenerConfigProvider") public void connectionStateListener_OnConnectionEvent( boolean isTcpConnectionEndpointRediscoveryEnabled, RequestResponseType responseType, int times) throws ExecutionException, InterruptedException { TcpServer server = TcpServerFactory.startNewRntbdServer(port); server.injectServerResponse(responseType); ConnectionPolicy connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); connectionPolicy.setTcpConnectionEndpointRediscoveryEnabled(isTcpConnectionEndpointRediscoveryEnabled); GlobalAddressResolver addressResolver = Mockito.mock(GlobalAddressResolver.class); SslContext sslContext = SslContextUtils.CreateSslContext("client.jks", false); Configs config = Mockito.mock(Configs.class); Mockito.doReturn(sslContext).when(config).getSslContext(); RntbdTransportClient client = new RntbdTransportClient( config, connectionPolicy, new UserAgentContainer(), addressResolver); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Create, ResourceType.Document, "dbs/fakedb/colls/fakeColls", getDocumentDefinition(), new HashMap<>()); req.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity("fakeCollectionId","fakePartitionKeyRangeId")); Uri targetUri = new Uri(serverUriString); try { client.invokeStoreAsync(targetUri, req).block(); } catch (Exception e) { logger.info("expected failed request with reason {}", e); } finally { Mockito.verify(addressResolver, Mockito.times(times)).updateAddresses(Mockito.any(), Mockito.any()); } TcpServerFactory.shutdownRntbdServer(server); } }
class ConnectionStateListenerTest { private static int port = 8082; private static String serverUriString = "rntbd: private static final Logger logger = LoggerFactory.getLogger(ConnectionStateListenerTest.class); @DataProvider(name = "connectionStateListenerConfigProvider") public Object[][] connectionStateListenerConfigProvider() { return new Object[][]{ {true, RequestResponseType.CHANNEL_FIN, 1}, {false, RequestResponseType.CHANNEL_FIN, 0}, {true, RequestResponseType.CHANNEL_RST, 0}, {false, RequestResponseType.CHANNEL_RST, 0}, }; } @Test(groups = { "unit" }, dataProvider = "connectionStateListenerConfigProvider") public void connectionStateListener_OnConnectionEvent( boolean isTcpConnectionEndpointRediscoveryEnabled, RequestResponseType responseType, int times) throws ExecutionException, InterruptedException { TcpServer server = TcpServerFactory.startNewRntbdServer(port); server.injectServerResponse(responseType); ConnectionPolicy connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); connectionPolicy.setTcpConnectionEndpointRediscoveryEnabled(isTcpConnectionEndpointRediscoveryEnabled); GlobalAddressResolver addressResolver = Mockito.mock(GlobalAddressResolver.class); SslContext sslContext = SslContextUtils.CreateSslContext("client.jks", false); Configs config = Mockito.mock(Configs.class); Mockito.doReturn(sslContext).when(config).getSslContext(); RntbdTransportClient client = new RntbdTransportClient( config, connectionPolicy, new UserAgentContainer(), addressResolver); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Create, ResourceType.Document, "dbs/fakedb/colls/fakeColls", getDocumentDefinition(), new HashMap<>()); req.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity("fakeCollectionId","fakePartitionKeyRangeId")); Uri targetUri = new Uri(serverUriString); try { client.invokeStoreAsync(targetUri, req).block(); } catch (Exception e) { logger.info("expected failed request with reason {}", e); } finally { Mockito.verify(addressResolver, Mockito.times(times)).updateAddresses(Mockito.any(), Mockito.any()); } TcpServerFactory.shutdownRntbdServer(server); } }
@moderakh sorry Mo I merged the PR, I will change this in a following PR, thanks~
private Document getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); Document doc = new Document(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , uuid, uuid)); return doc; }
Document doc = new Document(String.format("{ "
private Document getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); Document doc = new Document(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , uuid, uuid)); return doc; }
class ConnectionStateListenerTest { private static int port = 8082; private static String serverUriString = "rntbd: private static final Logger logger = LoggerFactory.getLogger(ConnectionStateListenerTest.class); @DataProvider(name = "connectionStateListenerConfigProvider") public Object[][] connectionStateListenerConfigProvider() { return new Object[][]{ {true, RequestResponseType.CHANNEL_FIN, 1}, {false, RequestResponseType.CHANNEL_FIN, 0}, {true, RequestResponseType.CHANNEL_RST, 0}, {false, RequestResponseType.CHANNEL_RST, 0}, }; } @Test(groups = { "unit" }, dataProvider = "connectionStateListenerConfigProvider") public void connectionStateListener_OnConnectionEvent( boolean isTcpConnectionEndpointRediscoveryEnabled, RequestResponseType responseType, int times) throws ExecutionException, InterruptedException { TcpServer server = TcpServerFactory.startNewRntbdServer(port); server.injectServerResponse(responseType); ConnectionPolicy connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); connectionPolicy.setTcpConnectionEndpointRediscoveryEnabled(isTcpConnectionEndpointRediscoveryEnabled); GlobalAddressResolver addressResolver = Mockito.mock(GlobalAddressResolver.class); SslContext sslContext = SslContextUtils.CreateSslContext("client.jks", false); Configs config = Mockito.mock(Configs.class); Mockito.doReturn(sslContext).when(config).getSslContext(); RntbdTransportClient client = new RntbdTransportClient( config, connectionPolicy, new UserAgentContainer(), addressResolver); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Create, ResourceType.Document, "dbs/fakedb/colls/fakeColls", getDocumentDefinition(), new HashMap<>()); req.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity("fakeCollectionId","fakePartitionKeyRangeId")); Uri targetUri = new Uri(serverUriString); try { client.invokeStoreAsync(targetUri, req).block(); } catch (Exception e) { logger.info("expected failed request with reason {}", e); } finally { Mockito.verify(addressResolver, Mockito.times(times)).updateAddresses(Mockito.any(), Mockito.any()); } TcpServerFactory.shutdownRntbdServer(server); } }
class ConnectionStateListenerTest { private static int port = 8082; private static String serverUriString = "rntbd: private static final Logger logger = LoggerFactory.getLogger(ConnectionStateListenerTest.class); @DataProvider(name = "connectionStateListenerConfigProvider") public Object[][] connectionStateListenerConfigProvider() { return new Object[][]{ {true, RequestResponseType.CHANNEL_FIN, 1}, {false, RequestResponseType.CHANNEL_FIN, 0}, {true, RequestResponseType.CHANNEL_RST, 0}, {false, RequestResponseType.CHANNEL_RST, 0}, }; } @Test(groups = { "unit" }, dataProvider = "connectionStateListenerConfigProvider") public void connectionStateListener_OnConnectionEvent( boolean isTcpConnectionEndpointRediscoveryEnabled, RequestResponseType responseType, int times) throws ExecutionException, InterruptedException { TcpServer server = TcpServerFactory.startNewRntbdServer(port); server.injectServerResponse(responseType); ConnectionPolicy connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); connectionPolicy.setTcpConnectionEndpointRediscoveryEnabled(isTcpConnectionEndpointRediscoveryEnabled); GlobalAddressResolver addressResolver = Mockito.mock(GlobalAddressResolver.class); SslContext sslContext = SslContextUtils.CreateSslContext("client.jks", false); Configs config = Mockito.mock(Configs.class); Mockito.doReturn(sslContext).when(config).getSslContext(); RntbdTransportClient client = new RntbdTransportClient( config, connectionPolicy, new UserAgentContainer(), addressResolver); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Create, ResourceType.Document, "dbs/fakedb/colls/fakeColls", getDocumentDefinition(), new HashMap<>()); req.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity("fakeCollectionId","fakePartitionKeyRangeId")); Uri targetUri = new Uri(serverUriString); try { client.invokeStoreAsync(targetUri, req).block(); } catch (Exception e) { logger.info("expected failed request with reason {}", e); } finally { Mockito.verify(addressResolver, Mockito.times(times)).updateAddresses(Mockito.any(), Mockito.any()); } TcpServerFactory.shutdownRntbdServer(server); } }
Nit: it's actually "plaintext" in crypto-speak.
Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); Objects.requireNonNull(encryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(encryptOptions.getPlainText(), "Plain text content to be encrypted cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlainText()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
Objects.requireNonNull(encryptOptions.getPlainText(), "Plain text content to be encrypted cannot be null.");
Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlaintext()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); Objects.requireNonNull(decryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(decryptOptions.getCipherText(), "Cipher text content to be decrypted cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCipherText()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCiphertext()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
On that note, I guess I missed this before, but just `getPlaintext` (it's one word).
Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); Objects.requireNonNull(encryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(encryptOptions.getPlainText(), "Plain text content to be encrypted cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlainText()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
.setValue(encryptOptions.getPlainText())
Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlaintext()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); Objects.requireNonNull(decryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(decryptOptions.getCipherText(), "Cipher text content to be decrypted cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCipherText()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCiphertext()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
`getCiphertext` (one word)
Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); Objects.requireNonNull(decryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(decryptOptions.getCipherText(), "Cipher text content to be decrypted cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCipherText()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
Objects.requireNonNull(decryptOptions.getCipherText(), "Cipher text content to be decrypted cannot be null.");
Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCiphertext()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); Objects.requireNonNull(encryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(encryptOptions.getPlainText(), "Plain text content to be encrypted cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlainText()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlaintext()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
We'll keep it as "plaintext" in the new code. Unfortunately, there's a couple APIs [[1](https://github.com/Azure/azure-sdk-for-java/blob/c9449d7bf0ea5c9fa7ca698845d9ce2a5c0c35e1/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/EncryptResult.java#L53)][[2](https://github.com/Azure/azure-sdk-for-java/blob/c9449d7bf0ea5c9fa7ca698845d9ce2a5c0c35e1/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptResult.java#L53)] that have already GA'd using plainText,
Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); Objects.requireNonNull(encryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(encryptOptions.getPlainText(), "Plain text content to be encrypted cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlainText()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
Objects.requireNonNull(encryptOptions.getPlainText(), "Plain text content to be encrypted cannot be null.");
Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlaintext()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); Objects.requireNonNull(decryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(decryptOptions.getCipherText(), "Cipher text content to be decrypted cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCipherText()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCiphertext()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
After talking to @JonathanGiles, in this case he thinks is it's better we remain consistent with what's already been GA'd, given that the difference in capitalization does not make it confusing to understand what the terms refer to.
Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); Objects.requireNonNull(encryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(encryptOptions.getPlainText(), "Plain text content to be encrypted cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlainText()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
Objects.requireNonNull(encryptOptions.getPlainText(), "Plain text content to be encrypted cannot be null.");
Mono<EncryptResult> encrypt(EncryptOptions encryptOptions, Context context) { Objects.requireNonNull(encryptOptions, "'encryptOptions' cannot be null."); EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); byte[] iv = encryptOptions.getIv(); byte[] authenticatedData = encryptOptions.getAdditionalAuthenticatedData(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(encryptOptions.getPlaintext()) .setIv(iv) .setAdditionalAuthenticatedData(authenticatedData); context = context == null ? Context.NONE : context; return service.encrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Encrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved encrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to encrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new EncryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); Objects.requireNonNull(decryptOptions.getAlgorithm(), "Encryption algorithm cannot be null."); Objects.requireNonNull(decryptOptions.getCipherText(), "Cipher text content to be decrypted cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCipherText()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
class CryptographyServiceClient { final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private final ClientLogger logger = new ClientLogger(CryptographyServiceClient.class); private final CryptographyService service; private String vaultUrl; private String version; private String keyName; private final String keyId; CryptographyServiceClient(String keyId, CryptographyService service, CryptographyServiceVersion serviceVersion) { Objects.requireNonNull(keyId); unpackId(keyId); this.keyId = keyId; this.service = service; apiVersion = serviceVersion.getVersion(); } Mono<Response<KeyVaultKey>> getKey(Context context) { if (version == null) { version = ""; } return getKey(keyName, version, context); } private Mono<Response<KeyVaultKey>> getKey(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); } Mono<Response<JsonWebKey>> getSecretKey(Context context) { return service.getSecret(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyName)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get key - {}", keyName, error)) .flatMap((stringResponse -> { KeyVaultKey key = null; try { return Mono.just(new SimpleResponse<>(stringResponse.getRequest(), stringResponse.getStatusCode(), stringResponse.getHeaders(), transformSecretKey(stringResponse.getValue()))); } catch (JsonProcessingException e) { return Mono.error(e); } })); } Mono<Response<SecretKey>> setSecretKey(SecretKey secret, Context context) { context = context == null ? Context.NONE : context; Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } JsonWebKey transformSecretKey(SecretKey secretKey) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); ArrayNode a = mapper.createArrayNode(); a.add(KeyOperation.WRAP_KEY.toString()); a.add(KeyOperation.UNWRAP_KEY.toString()); a.add(KeyOperation.ENCRYPT.toString()); a.add(KeyOperation.DECRYPT.toString()); ((ObjectNode) rootNode).put("k", Base64.getUrlDecoder().decode(secretKey.getValue())); ((ObjectNode) rootNode).put("kid", this.keyId); ((ObjectNode) rootNode).put("kty", KeyType.OCT.toString()); ((ObjectNode) rootNode).put("key_ops", a); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); return mapper.readValue(jsonString, JsonWebKey.class); } Mono<DecryptResult> decrypt(DecryptOptions decryptOptions, Context context) { Objects.requireNonNull(decryptOptions, "'decryptOptions' cannot be null."); EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); byte[] iv = decryptOptions.getIv(); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); KeyOperationParameters parameters = new KeyOperationParameters() .setAlgorithm(algorithm) .setValue(decryptOptions.getCiphertext()) .setIv(iv) .setAdditionalAuthenticatedData(additionalAuthenticatedData) .setAuthenticationTag(authenticationTag); context = context == null ? Context.NONE : context; return service.decrypt(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Decrypting content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved decrypted content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to decrypt content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just( new DecryptResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { KeySignRequest parameters = new KeySignRequest().setAlgorithm(algorithm).setValue(digest); context = context == null ? Context.NONE : context; return service.sign(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Signing content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved signed content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to sign content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new SignResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { KeyVerifyRequest parameters = new KeyVerifyRequest().setAlgorithm(algorithm).setDigest(digest).setSignature(signature); context = context == null ? Context.NONE : context; return service.verify(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Verifying content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved verified content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new VerifyResult(response.getValue().getValue(), algorithm, keyId))); } Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(key); context = context == null ? Context.NONE : context; return service.wrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Wrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved wrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to verify content with algorithm - {}", algorithm.toString(), error)) .flatMap(keyOperationResultResponse -> Mono.just(new WrapResult(keyOperationResultResponse.getValue().getResult(), algorithm, keyId))); } Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { KeyWrapUnwrapRequest parameters = new KeyWrapUnwrapRequest() .setAlgorithm(algorithm) .setValue(encryptedKey); context = context == null ? Context.NONE : context; return service.unwrapKey(vaultUrl, keyName, version, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Unwrapping key content with algorithm - {}", algorithm.toString())) .doOnSuccess(response -> logger.info("Retrieved unwrapped key content with algorithm- {}", algorithm.toString())) .doOnError(error -> logger.warning("Failed to unwrap key content with algorithm - {}", algorithm.toString(), error)) .flatMap(response -> Mono.just(new UnwrapResult(response.getValue().getResult(), algorithm, keyId))); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return sign(algorithm, digest, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { try { HashAlgorithm hashAlgorithm = SignatureHashResolver.DEFAULT.get(algorithm); MessageDigest md = MessageDigest.getInstance(hashAlgorithm.toString()); md.update(data); byte[] digest = md.digest(); return verify(algorithm, digest, signature, context); } catch (NoSuchAlgorithmException e) { return Mono.error(e); } } private void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.vaultUrl = url.getProtocol() + ": this.keyName = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
sessionId can not be null or empty for this method. This branch isn't reachable at runtime?
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.isEnableAutoComplete(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); if (CoreUtils.isNullOrEmpty(sessionId)) { return sessionSpecificManager.getActiveLink().map(receiveLink -> new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager)); } else { ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.getOrCreateConsumerAsync().map(consumer -> new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, consumer)); } }
} else {
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.isEnableAutoComplete(), sessionId, null); ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.createConsumerWithReceiveLink() .thenReturn(sessionSpecificAsyncClient); }
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) 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.isEnableAutoComplete(), 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); })); } /** * 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) @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) 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.isEnableAutoComplete(), 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); })); } /** * 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) @Override public void close() { this.onClientClose.run(); } }
Wait, why are we doing this logic here?
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.isEnableAutoComplete(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); if (CoreUtils.isNullOrEmpty(sessionId)) { return sessionSpecificManager.getActiveLink().map(receiveLink -> new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager)); } else { ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.getOrCreateConsumerAsync().map(consumer -> new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, consumer)); } }
if (CoreUtils.isNullOrEmpty(sessionId)) {
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.isEnableAutoComplete(), sessionId, null); ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.createConsumerWithReceiveLink() .thenReturn(sessionSpecificAsyncClient); }
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) 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.isEnableAutoComplete(), 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); })); } /** * 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) @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) 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.isEnableAutoComplete(), 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); })); } /** * 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) @Override public void close() { this.onClientClose.run(); } }
This is not needed, this is me working late night.
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.isEnableAutoComplete(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); if (CoreUtils.isNullOrEmpty(sessionId)) { return sessionSpecificManager.getActiveLink().map(receiveLink -> new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager)); } else { ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.getOrCreateConsumerAsync().map(consumer -> new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, consumer)); } }
if (CoreUtils.isNullOrEmpty(sessionId)) {
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.isEnableAutoComplete(), sessionId, null); ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.createConsumerWithReceiveLink() .thenReturn(sessionSpecificAsyncClient); }
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) 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.isEnableAutoComplete(), 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); })); } /** * 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) @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) 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.isEnableAutoComplete(), 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); })); } /** * 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) @Override public void close() { this.onClientClose.run(); } }
removed.
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.isEnableAutoComplete(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions); if (CoreUtils.isNullOrEmpty(sessionId)) { return sessionSpecificManager.getActiveLink().map(receiveLink -> new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager)); } else { ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.getOrCreateConsumerAsync().map(consumer -> new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, consumer)); } }
} else {
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.isEnableAutoComplete(), sessionId, null); ServiceBusReceiverAsyncClient sessionSpecificAsyncClient = new ServiceBusReceiverAsyncClient( fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }); return sessionSpecificAsyncClient.createConsumerWithReceiveLink() .thenReturn(sessionSpecificAsyncClient); }
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) 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.isEnableAutoComplete(), 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); })); } /** * 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) @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) 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.isEnableAutoComplete(), 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); })); } /** * 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) @Override public void close() { this.onClientClose.run(); } }
Why are we explicitly completing these? the method suggests that these should be auto completed `receiveTwoMessagesAutoComplete`. Same with the one below.
void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); }
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final List<Long> messagesDeferredPending = new ArrayList<>(); private final boolean isSessionEnabled = false; private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(receiver, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } /** * Verifies that we can create multiple transaction using sender and receiver. */ @Test void createMultipleTransactionTest() { setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); } /** * Verifies that we can create transaction and complete. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2. * receive and settle with transactionContext. 3. commit Rollback this transaction. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) { final MessagingEntityType entityType = MessagingEntityType.QUEUE; setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled); final String messageId1 = UUID.randomUUID().toString(); final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled); final String deadLetterReason = "test reason"; sendMessage(message1).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); final Mono<Void> operation; switch (dispositionStatus) { case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())); messagesPending.decrementAndGet(); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get())); break; case SUSPENDED: DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get()) .setDeadLetterReason(deadLetterReason); operation = receiver.deadLetter(receivedMessage, deadLetterOptions); messagesPending.decrementAndGet(); break; case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get())); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .verifyComplete(); StepVerifier.create(receiver.commitTransaction(transaction.get())) .verifyComplete(); if (dispositionStatus == DispositionStatus.DEFERRED) { messagesDeferredPending.add(receivedMessage.getSequenceNumber()); } } /** * Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using * sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest @Disabled void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) { final boolean shareConnection = true; final boolean useCredentials = false; final int entityIndex = 0; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(sender.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can send and receive two messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest /** * Verifies that we can send and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); StepVerifier.create(receiver.receiveMessages()) .thenAwait(Duration.ofSeconds(35)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 1, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.peekMessage()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can schedule and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2); sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); StepVerifier.create(Mono.delay(Duration.ofSeconds(4)).then(receiver.receiveMessages().next())) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .verifyComplete(); } /** * Verifies that we can cancel a scheduled message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10); final Duration delayDuration = Duration.ofSeconds(3); final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber); assertNotNull(sequenceNumber); Mono.delay(delayDuration) .then(sender.cancelScheduledMessage(sequenceNumber)) .block(TIMEOUT); messagesPending.decrementAndGet(); logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber); StepVerifier.create(receiver.receiveMessages().take(1)) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 3, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); try { StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber())) .assertNext(m -> { assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber()); assertMessageEquals(m, messageId, isSessionEnabled); }) .verifyComplete(); } finally { receiver.complete(receivedMessage) .block(Duration.ofSeconds(10)); messagesPending.decrementAndGet(); } } /** * Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled); final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> { final Map<String, Object> properties = message.getApplicationProperties(); final Object value = properties.get(MESSAGE_POSITION_ID); assertTrue(value instanceof Integer, "Did not contain correct position number: " + value); final int position = (int) value; assertEquals(index, position); }; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES); if (isSessionEnabled) { messages.forEach(m -> m.setSessionId(sessionId)); } sender.sendMessages(messages) .doOnSuccess(aVoid -> { int number = messagesPending.addAndGet(messages.size()); logger.info("Number of messages sent: {}", number); }) .block(TIMEOUT); try { StepVerifier.create(receiver.peekMessages(3)) .assertNext(message -> checkCorrectMessage.accept(message, 0)) .assertNext(message -> checkCorrectMessage.accept(message, 1)) .assertNext(message -> checkCorrectMessage.accept(message, 2)) .verifyComplete(); StepVerifier.create(receiver.peekMessages(4)) .assertNext(message -> checkCorrectMessage.accept(message, 3)) .assertNext(message -> checkCorrectMessage.accept(message, 4)) .assertNext(message -> checkCorrectMessage.accept(message, 5)) .assertNext(message -> checkCorrectMessage.accept(message, 6)) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .assertNext(message -> checkCorrectMessage.accept(message, 7)) .verifyComplete(); } finally { StepVerifier.create(receiver.receiveMessages().take(messages.size())) .thenConsumeWhile(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); return true; }) .thenCancel() .verify(); messagesPending.addAndGet(-messages.size()); } } /** * Verifies that we can send and peek a batch of messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .expectNextCount(maxMessages) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int maxMessages = 10; final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can dead-letter a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } /** * Verifies that we can renew message lock on a non-session receiver. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndRenewLock(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); assertNotNull(receivedMessage.getLockedUntil()); final OffsetDateTime initialLock = receivedMessage.getLockedUntil(); logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock); try { StepVerifier.create(Mono.delay(Duration.ofSeconds(7)) .then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage)))) .assertNext(lockedUntil -> { assertTrue(lockedUntil.isAfter(initialLock), String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]", lockedUntil, initialLock)); }) .verifyComplete(); } finally { logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber()); receiver.complete(receivedMessage) .doOnSuccess(aVoid -> messagesPending.decrementAndGet()) .block(TIMEOUT); } } /** * Verifies that the lock can be automatically renewed. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); if (isSessionEnabled) { message.setSessionId(sessionId); } sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockedUntil()); assertNotNull(received.getLockToken()); logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(), received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now()); final OffsetDateTime initial = received.getLockedUntil(); final OffsetDateTime timeToStop = initial.plusSeconds(20); final AtomicInteger iteration = new AtomicInteger(); while (iteration.get() < 4) { logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException error) { logger.error("Error occurred while sleeping: " + error); } } logger.info(new Date() + " . Completing message after delay ....."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .thenCancel() .verify(Duration.ofMinutes(2)); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.abandon(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.defer(receivedMessage)) .verifyComplete(); receiver.receiveDeferredMessage(receivedMessage.getSequenceNumber()) .flatMap(m -> receiver.complete(m)) .block(TIMEOUT); messagesPending.decrementAndGet(); } /** * Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); receiver.defer(receivedMessage).block(TIMEOUT); final ServiceBusReceivedMessage receivedDeferredMessage = receiver .receiveDeferredMessage(receivedMessage.getSequenceNumber()) .block(TIMEOUT); assertNotNull(receivedDeferredMessage); assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber()); final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedDeferredMessage); messagesDeferredPending.add(receivedDeferredMessage.getSequenceNumber()); break; case SUSPENDED: operation = receiver.deadLetter(receivedDeferredMessage); break; case COMPLETED: operation = receiver.complete(receivedDeferredMessage); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .expectComplete() .verify(); if (dispositionStatus != DispositionStatus.COMPLETED) { messagesPending.decrementAndGet(); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) { final boolean isSessionEnabled = true; setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled); Map<String, Object> sentProperties = messageToSend.getApplicationProperties(); sentProperties.put("NullProperty", null); sentProperties.put("BooleanProperty", true); sentProperties.put("ByteProperty", (byte) 1); sentProperties.put("ShortProperty", (short) 2); sentProperties.put("IntProperty", 3); sentProperties.put("LongProperty", 4L); sentProperties.put("FloatProperty", 5.5f); sentProperties.put("DoubleProperty", 6.6f); sentProperties.put("CharProperty", 'z'); sentProperties.put("UUIDProperty", UUID.randomUUID()); sentProperties.put("StringProperty", "string"); sendMessage(messageToSend).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { messagesPending.decrementAndGet(); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); final Map<String, Object> received = receivedMessage.getApplicationProperties(); assertEquals(sentProperties.size(), received.size()); for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) { if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) { assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey())); } else { final Object expected = sentEntry.getValue(); final Object actual = received.get(sentEntry.getKey()); assertEquals(expected, actual, String.format( "Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected, actual)); } } receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void setAndGetSessionState(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, true); final byte[] sessionState = "Finished".getBytes(UTF_8); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, true); sendMessage(messageToSend).block(Duration.ofSeconds(10)); AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>(); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(message -> { logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.", message.getSessionId(), message.getLockToken(), message.getLockedUntil()); receivedMessage.set(message); return receiver.setSessionState(sessionState); })) .expectComplete() .verify(); StepVerifier.create(receiver.getSessionState()) .assertNext(state -> { logger.info("State received: {}", new String(state, UTF_8)); assertArrayEquals(sessionState, state); }) .verifyComplete(); receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } /** * Verifies that we can receive a message from dead letter queue. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveFromDeadLetter(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final ServiceBusReceiverAsyncClient deadLetterReceiver; switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .topicName(topicName) .subscriptionName(subscriptionName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>(); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next() .block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); try { StepVerifier.create(deadLetterReceiver.receiveMessages().take(1)) .assertNext(serviceBusReceivedMessage -> { receivedMessages.add(serviceBusReceivedMessage); assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } finally { int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages); messagesPending.addAndGet(-numberCompleted); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void renewMessageLock(MessagingEntityType entityType) { final boolean isSessionEnabled = false; setSenderAndReceiver(entityType, 0, isSessionEnabled); final Duration maximumDuration = Duration.ofSeconds(35); final Duration sleepDuration = maximumDuration.plusMillis(500); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final ServiceBusReceivedMessage receivedMessage = sendMessage(message) .then(receiver.receiveMessages().next()) .block(TIMEOUT); assertNotNull(receivedMessage); final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil(); assertNotNull(lockedUntil); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration)) .thenAwait(sleepDuration) .then(() -> { logger.info("Completing message."); int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage)); messagesPending.addAndGet(-numberCompleted); }) .expectComplete() .verify(Duration.ofMinutes(3)); } /** * Verifies that we can receive a message which have different section set (i.e header, footer, annotations, * application properties etc). */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndValidateProperties(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final String subject = "subject"; final Map<String, Object> footer = new HashMap<>(); footer.put("footer-key-1", "footer-value-1"); footer.put("footer-key-2", "footer-value-2"); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put("ap-key-1", "ap-value-1"); applicationProperties.put("ap-key-2", "ap-value-2"); final Map<String, Object> deliveryAnnotation = new HashMap<>(); deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1"); deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2"); setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(CONTENTS_BYTES))); expectedAmqpProperties.getProperties().setSubject(subject); expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid"); expectedAmqpProperties.getProperties().setReplyTo("reply-to"); expectedAmqpProperties.getProperties().setContentType("content-type"); expectedAmqpProperties.getProperties().setCorrelationId("correlation-id"); expectedAmqpProperties.getProperties().setTo("to"); expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60)); expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes()); expectedAmqpProperties.getProperties().setContentEncoding("string"); expectedAmqpProperties.getProperties().setGroupSequence(2L); expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30)); expectedAmqpProperties.getHeader().setPriority((short) 2); expectedAmqpProperties.getHeader().setFirstAcquirer(true); expectedAmqpProperties.getHeader().setDurable(true); expectedAmqpProperties.getFooter().putAll(footer); expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation); expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties); final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage(); amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations()); amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties()); amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations()); amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter()); final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader(); header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer()); header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive()); header.setDurable(expectedAmqpProperties.getHeader().isDurable()); header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount()); header.setPriority(expectedAmqpProperties.getHeader().getPriority()); final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties(); amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo())); amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding())); amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime())); amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject())); amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType()); amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId()); amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo()); amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence()); amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId()); amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()); amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime()); amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId()); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockToken()); AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage(); try { assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority()); assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer()); assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId()); assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo()); assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType()); assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId()); assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo()); assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding()); assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence()); assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond()); assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId()); assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations()); assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations()); assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties()); assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter()); } finally { logger.info("Completing message."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } }) .thenCancel() .verify(Duration.ofMinutes(2)); } /** * Verifies we can autocomplete for a queue. * * @param entityType Entity Type. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoComplete(MessagingEntityType entityType) { final int index = TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES; setSenderAndReceiver(entityType, index, false); final ServiceBusReceiverAsyncClient autoCompleteReceiver = getReceiverBuilder(false, entityType, index, false) .buildAsyncClient(); final int numberOfEvents = 3; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId); final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT); Mono.when(messages.stream().map(this::sendMessage) .collect(Collectors.toList())) .block(TIMEOUT); try { StepVerifier.create(autoCompleteReceiver.receiveMessages()) .assertNext(receivedMessage -> { if (lastMessage != null) { assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId()); } else { assertEquals(messageId, receivedMessage.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .thenCancel() .verify(TIMEOUT); } finally { autoCompleteReceiver.close(); } final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT); if (lastMessage == null) { assertNull(newLastMessage, String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a")); } else { assertNotNull(newLastMessage); assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber()); } } /** * Asserts the length and values with in the map. */ private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) { assertTrue(actualMap.size() >= expectedMap.size()); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key); } } /** * Sets the sender and receiver. If session is enabled, then a single-named session receiver is created. */ private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient(); } } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) { Mono.when(messages.stream().map(e -> client.complete(e)) .collect(Collectors.toList())) .block(TIMEOUT); return messages.size(); } }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final boolean isSessionEnabled = false; private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(receiver, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } /** * Verifies that we can create multiple transaction using sender and receiver. */ @Test void createMultipleTransactionTest() { setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); } /** * Verifies that we can create transaction and complete. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2. * receive and settle with transactionContext. 3. commit Rollback this transaction. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) { final MessagingEntityType entityType = MessagingEntityType.QUEUE; setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled); final String messageId1 = UUID.randomUUID().toString(); final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled); final String deadLetterReason = "test reason"; sendMessage(message1).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); final Mono<Void> operation; switch (dispositionStatus) { case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())); messagesPending.decrementAndGet(); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get())); break; case SUSPENDED: DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get()) .setDeadLetterReason(deadLetterReason); operation = receiver.deadLetter(receivedMessage, deadLetterOptions); messagesPending.decrementAndGet(); break; case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get())); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .verifyComplete(); StepVerifier.create(receiver.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using * sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest @Disabled void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) { final boolean shareConnection = true; final boolean useCredentials = false; final int entityIndex = 0; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(sender.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can send and receive two messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest /** * Verifies that we can send and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .thenCancel() .verify(); StepVerifier.create(receiver.receiveMessages()) .thenAwait(Duration.ofSeconds(35)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 1, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.peekMessage()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> receiver.complete(receivedMessage).block(OPERATION_TIMEOUT)) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can schedule and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2); sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); StepVerifier.create(Mono.delay(Duration.ofSeconds(4)).then(receiver.receiveMessages().next())) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); messagesPending.decrementAndGet(); }) .verifyComplete(); } /** * Verifies that we can cancel a scheduled message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10); final Duration delayDuration = Duration.ofSeconds(3); final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber); assertNotNull(sequenceNumber); Mono.delay(delayDuration) .then(sender.cancelScheduledMessage(sequenceNumber)) .block(TIMEOUT); messagesPending.decrementAndGet(); logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber); StepVerifier.create(receiver.receiveMessages().take(1)) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 3, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); try { StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber())) .assertNext(m -> { assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber()); assertMessageEquals(m, messageId, isSessionEnabled); }) .verifyComplete(); } finally { receiver.complete(receivedMessage) .block(Duration.ofSeconds(10)); messagesPending.decrementAndGet(); } } /** * Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled); final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> { final Map<String, Object> properties = message.getApplicationProperties(); final Object value = properties.get(MESSAGE_POSITION_ID); assertTrue(value instanceof Integer, "Did not contain correct position number: " + value); final int position = (int) value; assertEquals(index, position); }; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES); if (isSessionEnabled) { messages.forEach(m -> m.setSessionId(sessionId)); } sender.sendMessages(messages) .doOnSuccess(aVoid -> { int number = messagesPending.addAndGet(messages.size()); logger.info("Number of messages sent: {}", number); }) .block(TIMEOUT); try { StepVerifier.create(receiver.peekMessages(3)) .assertNext(message -> checkCorrectMessage.accept(message, 0)) .assertNext(message -> checkCorrectMessage.accept(message, 1)) .assertNext(message -> checkCorrectMessage.accept(message, 2)) .verifyComplete(); StepVerifier.create(receiver.peekMessages(4)) .assertNext(message -> checkCorrectMessage.accept(message, 3)) .assertNext(message -> checkCorrectMessage.accept(message, 4)) .assertNext(message -> checkCorrectMessage.accept(message, 5)) .assertNext(message -> checkCorrectMessage.accept(message, 6)) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .assertNext(message -> checkCorrectMessage.accept(message, 7)) .verifyComplete(); } finally { AtomicInteger completed = new AtomicInteger(); StepVerifier.create(receiver.receiveMessages().take(messages.size())) .thenConsumeWhile(receivedMessage -> { completed.incrementAndGet(); receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); return completed.get() <= messages.size(); }) .expectComplete() .verify(); messagesPending.addAndGet(-messages.size()); } } /** * Verifies that we can send and peek a batch of messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .expectNextCount(maxMessages) .verifyComplete(); StepVerifier.create(receiver.receiveMessages().take(maxMessages)) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .expectComplete() .verify(TIMEOUT); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int maxMessages = 10; final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can dead-letter a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } /** * Verifies that we can renew message lock on a non-session receiver. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndRenewLock(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); assertNotNull(receivedMessage.getLockedUntil()); final OffsetDateTime initialLock = receivedMessage.getLockedUntil(); logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock); try { StepVerifier.create(Mono.delay(Duration.ofSeconds(7)) .then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage)))) .assertNext(lockedUntil -> { assertTrue(lockedUntil.isAfter(initialLock), String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]", lockedUntil, initialLock)); }) .verifyComplete(); } finally { logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber()); receiver.complete(receivedMessage) .doOnSuccess(aVoid -> messagesPending.decrementAndGet()) .block(TIMEOUT); } } /** * Verifies that the lock can be automatically renewed. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); if (isSessionEnabled) { message.setSessionId(sessionId); } sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockedUntil()); assertNotNull(received.getLockToken()); logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(), received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now()); final OffsetDateTime initial = received.getLockedUntil(); final OffsetDateTime timeToStop = initial.plusSeconds(20); final AtomicInteger iteration = new AtomicInteger(); while (iteration.get() < 4) { logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException error) { logger.error("Error occurred while sleeping: " + error); } } logger.info(new Date() + " . Completing message after delay ....."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .thenCancel() .verify(Duration.ofMinutes(2)); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.abandon(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.defer(receivedMessage)) .verifyComplete(); receiver.receiveDeferredMessage(receivedMessage.getSequenceNumber()) .flatMap(m -> receiver.complete(m)) .block(TIMEOUT); messagesPending.decrementAndGet(); } /** * Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); receiver.defer(receivedMessage).block(TIMEOUT); final ServiceBusReceivedMessage receivedDeferredMessage = receiver .receiveDeferredMessage(receivedMessage.getSequenceNumber()) .block(TIMEOUT); assertNotNull(receivedDeferredMessage); assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber()); final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedDeferredMessage); break; case SUSPENDED: operation = receiver.deadLetter(receivedDeferredMessage); break; case COMPLETED: operation = receiver.complete(receivedDeferredMessage); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .expectComplete() .verify(); if (dispositionStatus != DispositionStatus.COMPLETED) { messagesPending.decrementAndGet(); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) { final boolean isSessionEnabled = true; setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled); Map<String, Object> sentProperties = messageToSend.getApplicationProperties(); sentProperties.put("NullProperty", null); sentProperties.put("BooleanProperty", true); sentProperties.put("ByteProperty", (byte) 1); sentProperties.put("ShortProperty", (short) 2); sentProperties.put("IntProperty", 3); sentProperties.put("LongProperty", 4L); sentProperties.put("FloatProperty", 5.5f); sentProperties.put("DoubleProperty", 6.6f); sentProperties.put("CharProperty", 'z'); sentProperties.put("UUIDProperty", UUID.randomUUID()); sentProperties.put("StringProperty", "string"); sendMessage(messageToSend).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { messagesPending.decrementAndGet(); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); final Map<String, Object> received = receivedMessage.getApplicationProperties(); assertEquals(sentProperties.size(), received.size()); for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) { if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) { assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey())); } else { final Object expected = sentEntry.getValue(); final Object actual = received.get(sentEntry.getKey()); assertEquals(expected, actual, String.format( "Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected, actual)); } } receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); }) .thenCancel() .verify(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void setAndGetSessionState(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, true); final byte[] sessionState = "Finished".getBytes(UTF_8); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, true); sendMessage(messageToSend).block(Duration.ofSeconds(10)); AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>(); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(message -> { logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.", message.getSessionId(), message.getLockToken(), message.getLockedUntil()); receivedMessage.set(message); return receiver.setSessionState(sessionState); })) .expectComplete() .verify(); StepVerifier.create(receiver.getSessionState()) .assertNext(state -> { logger.info("State received: {}", new String(state, UTF_8)); assertArrayEquals(sessionState, state); }) .verifyComplete(); receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } /** * Verifies that we can receive a message from dead letter queue. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveFromDeadLetter(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final ServiceBusReceiverAsyncClient deadLetterReceiver; switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .topicName(topicName) .subscriptionName(subscriptionName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>(); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next() .block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); try { StepVerifier.create(deadLetterReceiver.receiveMessages().take(1)) .assertNext(serviceBusReceivedMessage -> { receivedMessages.add(serviceBusReceivedMessage); assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } finally { int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages); messagesPending.addAndGet(-numberCompleted); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void renewMessageLock(MessagingEntityType entityType) { final boolean isSessionEnabled = false; setSenderAndReceiver(entityType, 0, isSessionEnabled); final Duration maximumDuration = Duration.ofSeconds(35); final Duration sleepDuration = maximumDuration.plusMillis(500); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final ServiceBusReceivedMessage receivedMessage = sendMessage(message) .then(receiver.receiveMessages().next()) .block(TIMEOUT); assertNotNull(receivedMessage); final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil(); assertNotNull(lockedUntil); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration)) .thenAwait(sleepDuration) .then(() -> { logger.info("Completing message."); int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage)); messagesPending.addAndGet(-numberCompleted); }) .expectComplete() .verify(Duration.ofMinutes(3)); } /** * Verifies that we can receive a message which have different section set (i.e header, footer, annotations, * application properties etc). */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndValidateProperties(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final String subject = "subject"; final Map<String, Object> footer = new HashMap<>(); footer.put("footer-key-1", "footer-value-1"); footer.put("footer-key-2", "footer-value-2"); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put("ap-key-1", "ap-value-1"); applicationProperties.put("ap-key-2", "ap-value-2"); final Map<String, Object> deliveryAnnotation = new HashMap<>(); deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1"); deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2"); setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(CONTENTS_BYTES))); expectedAmqpProperties.getProperties().setSubject(subject); expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid"); expectedAmqpProperties.getProperties().setReplyTo("reply-to"); expectedAmqpProperties.getProperties().setContentType("content-type"); expectedAmqpProperties.getProperties().setCorrelationId("correlation-id"); expectedAmqpProperties.getProperties().setTo("to"); expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60)); expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes()); expectedAmqpProperties.getProperties().setContentEncoding("string"); expectedAmqpProperties.getProperties().setGroupSequence(2L); expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30)); expectedAmqpProperties.getHeader().setPriority((short) 2); expectedAmqpProperties.getHeader().setFirstAcquirer(true); expectedAmqpProperties.getHeader().setDurable(true); expectedAmqpProperties.getFooter().putAll(footer); expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation); expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties); final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage(); amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations()); amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties()); amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations()); amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter()); final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader(); header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer()); header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive()); header.setDurable(expectedAmqpProperties.getHeader().isDurable()); header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount()); header.setPriority(expectedAmqpProperties.getHeader().getPriority()); final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties(); amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo())); amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding())); amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime())); amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject())); amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType()); amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId()); amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo()); amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence()); amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId()); amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()); amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime()); amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId()); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockToken()); AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage(); try { assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority()); assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer()); assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId()); assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo()); assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType()); assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId()); assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo()); assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding()); assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence()); assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond()); assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId()); assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations()); assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations()); assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties()); assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter()); } finally { logger.info("Completing message."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } }) .thenCancel() .verify(Duration.ofMinutes(2)); } /** * Verifies we can autocomplete for a queue. * * @param entityType Entity Type. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoComplete(MessagingEntityType entityType) { final int index = TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES; setSenderAndReceiver(entityType, index, false); final ServiceBusReceiverAsyncClient autoCompleteReceiver = getReceiverBuilder(false, entityType, index, false) .buildAsyncClient(); final int numberOfEvents = 3; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId); final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT); Mono.when(messages.stream().map(this::sendMessage) .collect(Collectors.toList())) .block(TIMEOUT); try { StepVerifier.create(autoCompleteReceiver.receiveMessages()) .assertNext(receivedMessage -> { if (lastMessage != null) { assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId()); } else { assertEquals(messageId, receivedMessage.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .thenCancel() .verify(TIMEOUT); } finally { autoCompleteReceiver.close(); } final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT); if (lastMessage == null) { assertNull(newLastMessage, String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a")); } else { assertNotNull(newLastMessage); assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber()); } } /** * Asserts the length and values with in the map. */ private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) { assertTrue(actualMap.size() >= expectedMap.size()); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key); } } /** * Sets the sender and receiver. If session is enabled, then a single-named session receiver is created. */ private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient(); } } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) { Mono.when(messages.stream().map(e -> client.complete(e)) .collect(Collectors.toList())) .block(TIMEOUT); return messages.size(); } }
Then consume while always returns true? Shouldn't we assert that `completed < messages.size()` and then stop when `completed >= messages.size()`? And instead of thenCancel(), expect a complete?
void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled); final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> { final Map<String, Object> properties = message.getApplicationProperties(); final Object value = properties.get(MESSAGE_POSITION_ID); assertTrue(value instanceof Integer, "Did not contain correct position number: " + value); final int position = (int) value; assertEquals(index, position); }; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES); if (isSessionEnabled) { messages.forEach(m -> m.setSessionId(sessionId)); } sender.sendMessages(messages) .doOnSuccess(aVoid -> { int number = messagesPending.addAndGet(messages.size()); logger.info("Number of messages sent: {}", number); }) .block(TIMEOUT); try { StepVerifier.create(receiver.peekMessages(3)) .assertNext(message -> checkCorrectMessage.accept(message, 0)) .assertNext(message -> checkCorrectMessage.accept(message, 1)) .assertNext(message -> checkCorrectMessage.accept(message, 2)) .verifyComplete(); StepVerifier.create(receiver.peekMessages(4)) .assertNext(message -> checkCorrectMessage.accept(message, 3)) .assertNext(message -> checkCorrectMessage.accept(message, 4)) .assertNext(message -> checkCorrectMessage.accept(message, 5)) .assertNext(message -> checkCorrectMessage.accept(message, 6)) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .assertNext(message -> checkCorrectMessage.accept(message, 7)) .verifyComplete(); } finally { StepVerifier.create(receiver.receiveMessages().take(messages.size())) .thenConsumeWhile(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); return true; }) .thenCancel() .verify(); messagesPending.addAndGet(-messages.size()); } }
.thenConsumeWhile(receivedMessage -> {
void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled); final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> { final Map<String, Object> properties = message.getApplicationProperties(); final Object value = properties.get(MESSAGE_POSITION_ID); assertTrue(value instanceof Integer, "Did not contain correct position number: " + value); final int position = (int) value; assertEquals(index, position); }; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES); if (isSessionEnabled) { messages.forEach(m -> m.setSessionId(sessionId)); } sender.sendMessages(messages) .doOnSuccess(aVoid -> { int number = messagesPending.addAndGet(messages.size()); logger.info("Number of messages sent: {}", number); }) .block(TIMEOUT); try { StepVerifier.create(receiver.peekMessages(3)) .assertNext(message -> checkCorrectMessage.accept(message, 0)) .assertNext(message -> checkCorrectMessage.accept(message, 1)) .assertNext(message -> checkCorrectMessage.accept(message, 2)) .verifyComplete(); StepVerifier.create(receiver.peekMessages(4)) .assertNext(message -> checkCorrectMessage.accept(message, 3)) .assertNext(message -> checkCorrectMessage.accept(message, 4)) .assertNext(message -> checkCorrectMessage.accept(message, 5)) .assertNext(message -> checkCorrectMessage.accept(message, 6)) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .assertNext(message -> checkCorrectMessage.accept(message, 7)) .verifyComplete(); } finally { AtomicInteger completed = new AtomicInteger(); StepVerifier.create(receiver.receiveMessages().take(messages.size())) .thenConsumeWhile(receivedMessage -> { completed.incrementAndGet(); receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); return completed.get() <= messages.size(); }) .expectComplete() .verify(); messagesPending.addAndGet(-messages.size()); } }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final List<Long> messagesDeferredPending = new ArrayList<>(); private final boolean isSessionEnabled = false; private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(receiver, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } /** * Verifies that we can create multiple transaction using sender and receiver. */ @Test void createMultipleTransactionTest() { setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); } /** * Verifies that we can create transaction and complete. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2. * receive and settle with transactionContext. 3. commit Rollback this transaction. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) { final MessagingEntityType entityType = MessagingEntityType.QUEUE; setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled); final String messageId1 = UUID.randomUUID().toString(); final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled); final String deadLetterReason = "test reason"; sendMessage(message1).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); final Mono<Void> operation; switch (dispositionStatus) { case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())); messagesPending.decrementAndGet(); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get())); break; case SUSPENDED: DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get()) .setDeadLetterReason(deadLetterReason); operation = receiver.deadLetter(receivedMessage, deadLetterOptions); messagesPending.decrementAndGet(); break; case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get())); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .verifyComplete(); StepVerifier.create(receiver.commitTransaction(transaction.get())) .verifyComplete(); if (dispositionStatus == DispositionStatus.DEFERRED) { messagesDeferredPending.add(receivedMessage.getSequenceNumber()); } } /** * Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using * sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest @Disabled void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) { final boolean shareConnection = true; final boolean useCredentials = false; final int entityIndex = 0; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(sender.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can send and receive two messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that we can send and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); StepVerifier.create(receiver.receiveMessages()) .thenAwait(Duration.ofSeconds(35)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 1, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.peekMessage()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can schedule and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2); sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); StepVerifier.create(Mono.delay(Duration.ofSeconds(4)).then(receiver.receiveMessages().next())) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .verifyComplete(); } /** * Verifies that we can cancel a scheduled message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10); final Duration delayDuration = Duration.ofSeconds(3); final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber); assertNotNull(sequenceNumber); Mono.delay(delayDuration) .then(sender.cancelScheduledMessage(sequenceNumber)) .block(TIMEOUT); messagesPending.decrementAndGet(); logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber); StepVerifier.create(receiver.receiveMessages().take(1)) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 3, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); try { StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber())) .assertNext(m -> { assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber()); assertMessageEquals(m, messageId, isSessionEnabled); }) .verifyComplete(); } finally { receiver.complete(receivedMessage) .block(Duration.ofSeconds(10)); messagesPending.decrementAndGet(); } } /** * Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest /** * Verifies that we can send and peek a batch of messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .expectNextCount(maxMessages) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int maxMessages = 10; final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can dead-letter a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } /** * Verifies that we can renew message lock on a non-session receiver. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndRenewLock(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); assertNotNull(receivedMessage.getLockedUntil()); final OffsetDateTime initialLock = receivedMessage.getLockedUntil(); logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock); try { StepVerifier.create(Mono.delay(Duration.ofSeconds(7)) .then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage)))) .assertNext(lockedUntil -> { assertTrue(lockedUntil.isAfter(initialLock), String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]", lockedUntil, initialLock)); }) .verifyComplete(); } finally { logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber()); receiver.complete(receivedMessage) .doOnSuccess(aVoid -> messagesPending.decrementAndGet()) .block(TIMEOUT); } } /** * Verifies that the lock can be automatically renewed. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); if (isSessionEnabled) { message.setSessionId(sessionId); } sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockedUntil()); assertNotNull(received.getLockToken()); logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(), received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now()); final OffsetDateTime initial = received.getLockedUntil(); final OffsetDateTime timeToStop = initial.plusSeconds(20); final AtomicInteger iteration = new AtomicInteger(); while (iteration.get() < 4) { logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException error) { logger.error("Error occurred while sleeping: " + error); } } logger.info(new Date() + " . Completing message after delay ....."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .thenCancel() .verify(Duration.ofMinutes(2)); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.abandon(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.defer(receivedMessage)) .verifyComplete(); receiver.receiveDeferredMessage(receivedMessage.getSequenceNumber()) .flatMap(m -> receiver.complete(m)) .block(TIMEOUT); messagesPending.decrementAndGet(); } /** * Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); receiver.defer(receivedMessage).block(TIMEOUT); final ServiceBusReceivedMessage receivedDeferredMessage = receiver .receiveDeferredMessage(receivedMessage.getSequenceNumber()) .block(TIMEOUT); assertNotNull(receivedDeferredMessage); assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber()); final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedDeferredMessage); messagesDeferredPending.add(receivedDeferredMessage.getSequenceNumber()); break; case SUSPENDED: operation = receiver.deadLetter(receivedDeferredMessage); break; case COMPLETED: operation = receiver.complete(receivedDeferredMessage); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .expectComplete() .verify(); if (dispositionStatus != DispositionStatus.COMPLETED) { messagesPending.decrementAndGet(); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) { final boolean isSessionEnabled = true; setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled); Map<String, Object> sentProperties = messageToSend.getApplicationProperties(); sentProperties.put("NullProperty", null); sentProperties.put("BooleanProperty", true); sentProperties.put("ByteProperty", (byte) 1); sentProperties.put("ShortProperty", (short) 2); sentProperties.put("IntProperty", 3); sentProperties.put("LongProperty", 4L); sentProperties.put("FloatProperty", 5.5f); sentProperties.put("DoubleProperty", 6.6f); sentProperties.put("CharProperty", 'z'); sentProperties.put("UUIDProperty", UUID.randomUUID()); sentProperties.put("StringProperty", "string"); sendMessage(messageToSend).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { messagesPending.decrementAndGet(); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); final Map<String, Object> received = receivedMessage.getApplicationProperties(); assertEquals(sentProperties.size(), received.size()); for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) { if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) { assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey())); } else { final Object expected = sentEntry.getValue(); final Object actual = received.get(sentEntry.getKey()); assertEquals(expected, actual, String.format( "Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected, actual)); } } receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void setAndGetSessionState(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, true); final byte[] sessionState = "Finished".getBytes(UTF_8); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, true); sendMessage(messageToSend).block(Duration.ofSeconds(10)); AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>(); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(message -> { logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.", message.getSessionId(), message.getLockToken(), message.getLockedUntil()); receivedMessage.set(message); return receiver.setSessionState(sessionState); })) .expectComplete() .verify(); StepVerifier.create(receiver.getSessionState()) .assertNext(state -> { logger.info("State received: {}", new String(state, UTF_8)); assertArrayEquals(sessionState, state); }) .verifyComplete(); receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } /** * Verifies that we can receive a message from dead letter queue. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveFromDeadLetter(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final ServiceBusReceiverAsyncClient deadLetterReceiver; switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .topicName(topicName) .subscriptionName(subscriptionName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>(); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next() .block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); try { StepVerifier.create(deadLetterReceiver.receiveMessages().take(1)) .assertNext(serviceBusReceivedMessage -> { receivedMessages.add(serviceBusReceivedMessage); assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } finally { int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages); messagesPending.addAndGet(-numberCompleted); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void renewMessageLock(MessagingEntityType entityType) { final boolean isSessionEnabled = false; setSenderAndReceiver(entityType, 0, isSessionEnabled); final Duration maximumDuration = Duration.ofSeconds(35); final Duration sleepDuration = maximumDuration.plusMillis(500); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final ServiceBusReceivedMessage receivedMessage = sendMessage(message) .then(receiver.receiveMessages().next()) .block(TIMEOUT); assertNotNull(receivedMessage); final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil(); assertNotNull(lockedUntil); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration)) .thenAwait(sleepDuration) .then(() -> { logger.info("Completing message."); int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage)); messagesPending.addAndGet(-numberCompleted); }) .expectComplete() .verify(Duration.ofMinutes(3)); } /** * Verifies that we can receive a message which have different section set (i.e header, footer, annotations, * application properties etc). */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndValidateProperties(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final String subject = "subject"; final Map<String, Object> footer = new HashMap<>(); footer.put("footer-key-1", "footer-value-1"); footer.put("footer-key-2", "footer-value-2"); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put("ap-key-1", "ap-value-1"); applicationProperties.put("ap-key-2", "ap-value-2"); final Map<String, Object> deliveryAnnotation = new HashMap<>(); deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1"); deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2"); setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(CONTENTS_BYTES))); expectedAmqpProperties.getProperties().setSubject(subject); expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid"); expectedAmqpProperties.getProperties().setReplyTo("reply-to"); expectedAmqpProperties.getProperties().setContentType("content-type"); expectedAmqpProperties.getProperties().setCorrelationId("correlation-id"); expectedAmqpProperties.getProperties().setTo("to"); expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60)); expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes()); expectedAmqpProperties.getProperties().setContentEncoding("string"); expectedAmqpProperties.getProperties().setGroupSequence(2L); expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30)); expectedAmqpProperties.getHeader().setPriority((short) 2); expectedAmqpProperties.getHeader().setFirstAcquirer(true); expectedAmqpProperties.getHeader().setDurable(true); expectedAmqpProperties.getFooter().putAll(footer); expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation); expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties); final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage(); amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations()); amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties()); amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations()); amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter()); final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader(); header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer()); header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive()); header.setDurable(expectedAmqpProperties.getHeader().isDurable()); header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount()); header.setPriority(expectedAmqpProperties.getHeader().getPriority()); final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties(); amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo())); amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding())); amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime())); amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject())); amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType()); amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId()); amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo()); amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence()); amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId()); amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()); amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime()); amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId()); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockToken()); AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage(); try { assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority()); assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer()); assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId()); assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo()); assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType()); assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId()); assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo()); assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding()); assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence()); assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond()); assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId()); assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations()); assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations()); assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties()); assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter()); } finally { logger.info("Completing message."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } }) .thenCancel() .verify(Duration.ofMinutes(2)); } /** * Verifies we can autocomplete for a queue. * * @param entityType Entity Type. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoComplete(MessagingEntityType entityType) { final int index = TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES; setSenderAndReceiver(entityType, index, false); final ServiceBusReceiverAsyncClient autoCompleteReceiver = getReceiverBuilder(false, entityType, index, false) .buildAsyncClient(); final int numberOfEvents = 3; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId); final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT); Mono.when(messages.stream().map(this::sendMessage) .collect(Collectors.toList())) .block(TIMEOUT); try { StepVerifier.create(autoCompleteReceiver.receiveMessages()) .assertNext(receivedMessage -> { if (lastMessage != null) { assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId()); } else { assertEquals(messageId, receivedMessage.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .thenCancel() .verify(TIMEOUT); } finally { autoCompleteReceiver.close(); } final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT); if (lastMessage == null) { assertNull(newLastMessage, String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a")); } else { assertNotNull(newLastMessage); assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber()); } } /** * Asserts the length and values with in the map. */ private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) { assertTrue(actualMap.size() >= expectedMap.size()); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key); } } /** * Sets the sender and receiver. If session is enabled, then a single-named session receiver is created. */ private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient(); } } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) { Mono.when(messages.stream().map(e -> client.complete(e)) .collect(Collectors.toList())) .block(TIMEOUT); return messages.size(); } }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final boolean isSessionEnabled = false; private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(receiver, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } /** * Verifies that we can create multiple transaction using sender and receiver. */ @Test void createMultipleTransactionTest() { setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); } /** * Verifies that we can create transaction and complete. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2. * receive and settle with transactionContext. 3. commit Rollback this transaction. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) { final MessagingEntityType entityType = MessagingEntityType.QUEUE; setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled); final String messageId1 = UUID.randomUUID().toString(); final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled); final String deadLetterReason = "test reason"; sendMessage(message1).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); final Mono<Void> operation; switch (dispositionStatus) { case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())); messagesPending.decrementAndGet(); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get())); break; case SUSPENDED: DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get()) .setDeadLetterReason(deadLetterReason); operation = receiver.deadLetter(receivedMessage, deadLetterOptions); messagesPending.decrementAndGet(); break; case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get())); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .verifyComplete(); StepVerifier.create(receiver.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using * sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest @Disabled void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) { final boolean shareConnection = true; final boolean useCredentials = false; final int entityIndex = 0; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(sender.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can send and receive two messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } /** * Verifies that we can send and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .thenCancel() .verify(); StepVerifier.create(receiver.receiveMessages()) .thenAwait(Duration.ofSeconds(35)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 1, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.peekMessage()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> receiver.complete(receivedMessage).block(OPERATION_TIMEOUT)) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can schedule and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2); sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); StepVerifier.create(Mono.delay(Duration.ofSeconds(4)).then(receiver.receiveMessages().next())) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); messagesPending.decrementAndGet(); }) .verifyComplete(); } /** * Verifies that we can cancel a scheduled message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10); final Duration delayDuration = Duration.ofSeconds(3); final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber); assertNotNull(sequenceNumber); Mono.delay(delayDuration) .then(sender.cancelScheduledMessage(sequenceNumber)) .block(TIMEOUT); messagesPending.decrementAndGet(); logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber); StepVerifier.create(receiver.receiveMessages().take(1)) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 3, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); try { StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber())) .assertNext(m -> { assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber()); assertMessageEquals(m, messageId, isSessionEnabled); }) .verifyComplete(); } finally { receiver.complete(receivedMessage) .block(Duration.ofSeconds(10)); messagesPending.decrementAndGet(); } } /** * Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest /** * Verifies that we can send and peek a batch of messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .expectNextCount(maxMessages) .verifyComplete(); StepVerifier.create(receiver.receiveMessages().take(maxMessages)) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .expectComplete() .verify(TIMEOUT); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int maxMessages = 10; final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can dead-letter a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } /** * Verifies that we can renew message lock on a non-session receiver. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndRenewLock(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); assertNotNull(receivedMessage.getLockedUntil()); final OffsetDateTime initialLock = receivedMessage.getLockedUntil(); logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock); try { StepVerifier.create(Mono.delay(Duration.ofSeconds(7)) .then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage)))) .assertNext(lockedUntil -> { assertTrue(lockedUntil.isAfter(initialLock), String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]", lockedUntil, initialLock)); }) .verifyComplete(); } finally { logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber()); receiver.complete(receivedMessage) .doOnSuccess(aVoid -> messagesPending.decrementAndGet()) .block(TIMEOUT); } } /** * Verifies that the lock can be automatically renewed. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); if (isSessionEnabled) { message.setSessionId(sessionId); } sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockedUntil()); assertNotNull(received.getLockToken()); logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(), received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now()); final OffsetDateTime initial = received.getLockedUntil(); final OffsetDateTime timeToStop = initial.plusSeconds(20); final AtomicInteger iteration = new AtomicInteger(); while (iteration.get() < 4) { logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException error) { logger.error("Error occurred while sleeping: " + error); } } logger.info(new Date() + " . Completing message after delay ....."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .thenCancel() .verify(Duration.ofMinutes(2)); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.abandon(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.defer(receivedMessage)) .verifyComplete(); receiver.receiveDeferredMessage(receivedMessage.getSequenceNumber()) .flatMap(m -> receiver.complete(m)) .block(TIMEOUT); messagesPending.decrementAndGet(); } /** * Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); receiver.defer(receivedMessage).block(TIMEOUT); final ServiceBusReceivedMessage receivedDeferredMessage = receiver .receiveDeferredMessage(receivedMessage.getSequenceNumber()) .block(TIMEOUT); assertNotNull(receivedDeferredMessage); assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber()); final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedDeferredMessage); break; case SUSPENDED: operation = receiver.deadLetter(receivedDeferredMessage); break; case COMPLETED: operation = receiver.complete(receivedDeferredMessage); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .expectComplete() .verify(); if (dispositionStatus != DispositionStatus.COMPLETED) { messagesPending.decrementAndGet(); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) { final boolean isSessionEnabled = true; setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled); Map<String, Object> sentProperties = messageToSend.getApplicationProperties(); sentProperties.put("NullProperty", null); sentProperties.put("BooleanProperty", true); sentProperties.put("ByteProperty", (byte) 1); sentProperties.put("ShortProperty", (short) 2); sentProperties.put("IntProperty", 3); sentProperties.put("LongProperty", 4L); sentProperties.put("FloatProperty", 5.5f); sentProperties.put("DoubleProperty", 6.6f); sentProperties.put("CharProperty", 'z'); sentProperties.put("UUIDProperty", UUID.randomUUID()); sentProperties.put("StringProperty", "string"); sendMessage(messageToSend).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { messagesPending.decrementAndGet(); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); final Map<String, Object> received = receivedMessage.getApplicationProperties(); assertEquals(sentProperties.size(), received.size()); for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) { if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) { assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey())); } else { final Object expected = sentEntry.getValue(); final Object actual = received.get(sentEntry.getKey()); assertEquals(expected, actual, String.format( "Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected, actual)); } } receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); }) .thenCancel() .verify(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void setAndGetSessionState(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, true); final byte[] sessionState = "Finished".getBytes(UTF_8); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, true); sendMessage(messageToSend).block(Duration.ofSeconds(10)); AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>(); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(message -> { logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.", message.getSessionId(), message.getLockToken(), message.getLockedUntil()); receivedMessage.set(message); return receiver.setSessionState(sessionState); })) .expectComplete() .verify(); StepVerifier.create(receiver.getSessionState()) .assertNext(state -> { logger.info("State received: {}", new String(state, UTF_8)); assertArrayEquals(sessionState, state); }) .verifyComplete(); receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } /** * Verifies that we can receive a message from dead letter queue. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveFromDeadLetter(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final ServiceBusReceiverAsyncClient deadLetterReceiver; switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .topicName(topicName) .subscriptionName(subscriptionName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>(); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next() .block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); try { StepVerifier.create(deadLetterReceiver.receiveMessages().take(1)) .assertNext(serviceBusReceivedMessage -> { receivedMessages.add(serviceBusReceivedMessage); assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } finally { int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages); messagesPending.addAndGet(-numberCompleted); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void renewMessageLock(MessagingEntityType entityType) { final boolean isSessionEnabled = false; setSenderAndReceiver(entityType, 0, isSessionEnabled); final Duration maximumDuration = Duration.ofSeconds(35); final Duration sleepDuration = maximumDuration.plusMillis(500); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final ServiceBusReceivedMessage receivedMessage = sendMessage(message) .then(receiver.receiveMessages().next()) .block(TIMEOUT); assertNotNull(receivedMessage); final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil(); assertNotNull(lockedUntil); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration)) .thenAwait(sleepDuration) .then(() -> { logger.info("Completing message."); int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage)); messagesPending.addAndGet(-numberCompleted); }) .expectComplete() .verify(Duration.ofMinutes(3)); } /** * Verifies that we can receive a message which have different section set (i.e header, footer, annotations, * application properties etc). */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndValidateProperties(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final String subject = "subject"; final Map<String, Object> footer = new HashMap<>(); footer.put("footer-key-1", "footer-value-1"); footer.put("footer-key-2", "footer-value-2"); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put("ap-key-1", "ap-value-1"); applicationProperties.put("ap-key-2", "ap-value-2"); final Map<String, Object> deliveryAnnotation = new HashMap<>(); deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1"); deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2"); setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(CONTENTS_BYTES))); expectedAmqpProperties.getProperties().setSubject(subject); expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid"); expectedAmqpProperties.getProperties().setReplyTo("reply-to"); expectedAmqpProperties.getProperties().setContentType("content-type"); expectedAmqpProperties.getProperties().setCorrelationId("correlation-id"); expectedAmqpProperties.getProperties().setTo("to"); expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60)); expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes()); expectedAmqpProperties.getProperties().setContentEncoding("string"); expectedAmqpProperties.getProperties().setGroupSequence(2L); expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30)); expectedAmqpProperties.getHeader().setPriority((short) 2); expectedAmqpProperties.getHeader().setFirstAcquirer(true); expectedAmqpProperties.getHeader().setDurable(true); expectedAmqpProperties.getFooter().putAll(footer); expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation); expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties); final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage(); amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations()); amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties()); amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations()); amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter()); final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader(); header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer()); header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive()); header.setDurable(expectedAmqpProperties.getHeader().isDurable()); header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount()); header.setPriority(expectedAmqpProperties.getHeader().getPriority()); final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties(); amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo())); amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding())); amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime())); amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject())); amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType()); amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId()); amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo()); amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence()); amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId()); amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()); amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime()); amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId()); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockToken()); AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage(); try { assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority()); assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer()); assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId()); assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo()); assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType()); assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId()); assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo()); assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding()); assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence()); assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond()); assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId()); assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations()); assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations()); assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties()); assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter()); } finally { logger.info("Completing message."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } }) .thenCancel() .verify(Duration.ofMinutes(2)); } /** * Verifies we can autocomplete for a queue. * * @param entityType Entity Type. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoComplete(MessagingEntityType entityType) { final int index = TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES; setSenderAndReceiver(entityType, index, false); final ServiceBusReceiverAsyncClient autoCompleteReceiver = getReceiverBuilder(false, entityType, index, false) .buildAsyncClient(); final int numberOfEvents = 3; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId); final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT); Mono.when(messages.stream().map(this::sendMessage) .collect(Collectors.toList())) .block(TIMEOUT); try { StepVerifier.create(autoCompleteReceiver.receiveMessages()) .assertNext(receivedMessage -> { if (lastMessage != null) { assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId()); } else { assertEquals(messageId, receivedMessage.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .thenCancel() .verify(TIMEOUT); } finally { autoCompleteReceiver.close(); } final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT); if (lastMessage == null) { assertNull(newLastMessage, String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a")); } else { assertNotNull(newLastMessage); assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber()); } } /** * Asserts the length and values with in the map. */ private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) { assertTrue(actualMap.size() >= expectedMap.size()); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key); } } /** * Sets the sender and receiver. If session is enabled, then a single-named session receiver is created. */ private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient(); } } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) { Mono.when(messages.stream().map(e -> client.complete(e)) .collect(Collectors.toList())) .block(TIMEOUT); return messages.size(); } }
We have a TIMEOUT duration already defined. We can replace all instances of this Duration.ofSeconds.
void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2); sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); StepVerifier.create(Mono.delay(Duration.ofSeconds(4)).then(receiver.receiveMessages().next())) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .verifyComplete(); }
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2); sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); StepVerifier.create(Mono.delay(Duration.ofSeconds(4)).then(receiver.receiveMessages().next())) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); messagesPending.decrementAndGet(); }) .verifyComplete(); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final List<Long> messagesDeferredPending = new ArrayList<>(); private final boolean isSessionEnabled = false; private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(receiver, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } /** * Verifies that we can create multiple transaction using sender and receiver. */ @Test void createMultipleTransactionTest() { setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); } /** * Verifies that we can create transaction and complete. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2. * receive and settle with transactionContext. 3. commit Rollback this transaction. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) { final MessagingEntityType entityType = MessagingEntityType.QUEUE; setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled); final String messageId1 = UUID.randomUUID().toString(); final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled); final String deadLetterReason = "test reason"; sendMessage(message1).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); final Mono<Void> operation; switch (dispositionStatus) { case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())); messagesPending.decrementAndGet(); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get())); break; case SUSPENDED: DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get()) .setDeadLetterReason(deadLetterReason); operation = receiver.deadLetter(receivedMessage, deadLetterOptions); messagesPending.decrementAndGet(); break; case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get())); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .verifyComplete(); StepVerifier.create(receiver.commitTransaction(transaction.get())) .verifyComplete(); if (dispositionStatus == DispositionStatus.DEFERRED) { messagesDeferredPending.add(receivedMessage.getSequenceNumber()); } } /** * Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using * sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest @Disabled void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) { final boolean shareConnection = true; final boolean useCredentials = false; final int entityIndex = 0; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(sender.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can send and receive two messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that we can send and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); StepVerifier.create(receiver.receiveMessages()) .thenAwait(Duration.ofSeconds(35)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 1, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.peekMessage()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can schedule and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest /** * Verifies that we can cancel a scheduled message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10); final Duration delayDuration = Duration.ofSeconds(3); final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber); assertNotNull(sequenceNumber); Mono.delay(delayDuration) .then(sender.cancelScheduledMessage(sequenceNumber)) .block(TIMEOUT); messagesPending.decrementAndGet(); logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber); StepVerifier.create(receiver.receiveMessages().take(1)) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 3, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); try { StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber())) .assertNext(m -> { assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber()); assertMessageEquals(m, messageId, isSessionEnabled); }) .verifyComplete(); } finally { receiver.complete(receivedMessage) .block(Duration.ofSeconds(10)); messagesPending.decrementAndGet(); } } /** * Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled); final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> { final Map<String, Object> properties = message.getApplicationProperties(); final Object value = properties.get(MESSAGE_POSITION_ID); assertTrue(value instanceof Integer, "Did not contain correct position number: " + value); final int position = (int) value; assertEquals(index, position); }; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES); if (isSessionEnabled) { messages.forEach(m -> m.setSessionId(sessionId)); } sender.sendMessages(messages) .doOnSuccess(aVoid -> { int number = messagesPending.addAndGet(messages.size()); logger.info("Number of messages sent: {}", number); }) .block(TIMEOUT); try { StepVerifier.create(receiver.peekMessages(3)) .assertNext(message -> checkCorrectMessage.accept(message, 0)) .assertNext(message -> checkCorrectMessage.accept(message, 1)) .assertNext(message -> checkCorrectMessage.accept(message, 2)) .verifyComplete(); StepVerifier.create(receiver.peekMessages(4)) .assertNext(message -> checkCorrectMessage.accept(message, 3)) .assertNext(message -> checkCorrectMessage.accept(message, 4)) .assertNext(message -> checkCorrectMessage.accept(message, 5)) .assertNext(message -> checkCorrectMessage.accept(message, 6)) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .assertNext(message -> checkCorrectMessage.accept(message, 7)) .verifyComplete(); } finally { StepVerifier.create(receiver.receiveMessages().take(messages.size())) .thenConsumeWhile(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); return true; }) .thenCancel() .verify(); messagesPending.addAndGet(-messages.size()); } } /** * Verifies that we can send and peek a batch of messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .expectNextCount(maxMessages) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int maxMessages = 10; final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can dead-letter a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } /** * Verifies that we can renew message lock on a non-session receiver. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndRenewLock(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); assertNotNull(receivedMessage.getLockedUntil()); final OffsetDateTime initialLock = receivedMessage.getLockedUntil(); logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock); try { StepVerifier.create(Mono.delay(Duration.ofSeconds(7)) .then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage)))) .assertNext(lockedUntil -> { assertTrue(lockedUntil.isAfter(initialLock), String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]", lockedUntil, initialLock)); }) .verifyComplete(); } finally { logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber()); receiver.complete(receivedMessage) .doOnSuccess(aVoid -> messagesPending.decrementAndGet()) .block(TIMEOUT); } } /** * Verifies that the lock can be automatically renewed. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); if (isSessionEnabled) { message.setSessionId(sessionId); } sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockedUntil()); assertNotNull(received.getLockToken()); logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(), received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now()); final OffsetDateTime initial = received.getLockedUntil(); final OffsetDateTime timeToStop = initial.plusSeconds(20); final AtomicInteger iteration = new AtomicInteger(); while (iteration.get() < 4) { logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException error) { logger.error("Error occurred while sleeping: " + error); } } logger.info(new Date() + " . Completing message after delay ....."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .thenCancel() .verify(Duration.ofMinutes(2)); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.abandon(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.defer(receivedMessage)) .verifyComplete(); receiver.receiveDeferredMessage(receivedMessage.getSequenceNumber()) .flatMap(m -> receiver.complete(m)) .block(TIMEOUT); messagesPending.decrementAndGet(); } /** * Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); receiver.defer(receivedMessage).block(TIMEOUT); final ServiceBusReceivedMessage receivedDeferredMessage = receiver .receiveDeferredMessage(receivedMessage.getSequenceNumber()) .block(TIMEOUT); assertNotNull(receivedDeferredMessage); assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber()); final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedDeferredMessage); messagesDeferredPending.add(receivedDeferredMessage.getSequenceNumber()); break; case SUSPENDED: operation = receiver.deadLetter(receivedDeferredMessage); break; case COMPLETED: operation = receiver.complete(receivedDeferredMessage); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .expectComplete() .verify(); if (dispositionStatus != DispositionStatus.COMPLETED) { messagesPending.decrementAndGet(); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) { final boolean isSessionEnabled = true; setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled); Map<String, Object> sentProperties = messageToSend.getApplicationProperties(); sentProperties.put("NullProperty", null); sentProperties.put("BooleanProperty", true); sentProperties.put("ByteProperty", (byte) 1); sentProperties.put("ShortProperty", (short) 2); sentProperties.put("IntProperty", 3); sentProperties.put("LongProperty", 4L); sentProperties.put("FloatProperty", 5.5f); sentProperties.put("DoubleProperty", 6.6f); sentProperties.put("CharProperty", 'z'); sentProperties.put("UUIDProperty", UUID.randomUUID()); sentProperties.put("StringProperty", "string"); sendMessage(messageToSend).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { messagesPending.decrementAndGet(); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); final Map<String, Object> received = receivedMessage.getApplicationProperties(); assertEquals(sentProperties.size(), received.size()); for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) { if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) { assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey())); } else { final Object expected = sentEntry.getValue(); final Object actual = received.get(sentEntry.getKey()); assertEquals(expected, actual, String.format( "Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected, actual)); } } receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void setAndGetSessionState(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, true); final byte[] sessionState = "Finished".getBytes(UTF_8); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, true); sendMessage(messageToSend).block(Duration.ofSeconds(10)); AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>(); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(message -> { logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.", message.getSessionId(), message.getLockToken(), message.getLockedUntil()); receivedMessage.set(message); return receiver.setSessionState(sessionState); })) .expectComplete() .verify(); StepVerifier.create(receiver.getSessionState()) .assertNext(state -> { logger.info("State received: {}", new String(state, UTF_8)); assertArrayEquals(sessionState, state); }) .verifyComplete(); receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } /** * Verifies that we can receive a message from dead letter queue. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveFromDeadLetter(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final ServiceBusReceiverAsyncClient deadLetterReceiver; switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .topicName(topicName) .subscriptionName(subscriptionName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>(); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next() .block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); try { StepVerifier.create(deadLetterReceiver.receiveMessages().take(1)) .assertNext(serviceBusReceivedMessage -> { receivedMessages.add(serviceBusReceivedMessage); assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } finally { int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages); messagesPending.addAndGet(-numberCompleted); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void renewMessageLock(MessagingEntityType entityType) { final boolean isSessionEnabled = false; setSenderAndReceiver(entityType, 0, isSessionEnabled); final Duration maximumDuration = Duration.ofSeconds(35); final Duration sleepDuration = maximumDuration.plusMillis(500); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final ServiceBusReceivedMessage receivedMessage = sendMessage(message) .then(receiver.receiveMessages().next()) .block(TIMEOUT); assertNotNull(receivedMessage); final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil(); assertNotNull(lockedUntil); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration)) .thenAwait(sleepDuration) .then(() -> { logger.info("Completing message."); int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage)); messagesPending.addAndGet(-numberCompleted); }) .expectComplete() .verify(Duration.ofMinutes(3)); } /** * Verifies that we can receive a message which have different section set (i.e header, footer, annotations, * application properties etc). */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndValidateProperties(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final String subject = "subject"; final Map<String, Object> footer = new HashMap<>(); footer.put("footer-key-1", "footer-value-1"); footer.put("footer-key-2", "footer-value-2"); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put("ap-key-1", "ap-value-1"); applicationProperties.put("ap-key-2", "ap-value-2"); final Map<String, Object> deliveryAnnotation = new HashMap<>(); deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1"); deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2"); setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(CONTENTS_BYTES))); expectedAmqpProperties.getProperties().setSubject(subject); expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid"); expectedAmqpProperties.getProperties().setReplyTo("reply-to"); expectedAmqpProperties.getProperties().setContentType("content-type"); expectedAmqpProperties.getProperties().setCorrelationId("correlation-id"); expectedAmqpProperties.getProperties().setTo("to"); expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60)); expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes()); expectedAmqpProperties.getProperties().setContentEncoding("string"); expectedAmqpProperties.getProperties().setGroupSequence(2L); expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30)); expectedAmqpProperties.getHeader().setPriority((short) 2); expectedAmqpProperties.getHeader().setFirstAcquirer(true); expectedAmqpProperties.getHeader().setDurable(true); expectedAmqpProperties.getFooter().putAll(footer); expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation); expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties); final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage(); amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations()); amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties()); amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations()); amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter()); final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader(); header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer()); header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive()); header.setDurable(expectedAmqpProperties.getHeader().isDurable()); header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount()); header.setPriority(expectedAmqpProperties.getHeader().getPriority()); final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties(); amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo())); amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding())); amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime())); amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject())); amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType()); amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId()); amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo()); amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence()); amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId()); amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()); amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime()); amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId()); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockToken()); AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage(); try { assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority()); assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer()); assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId()); assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo()); assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType()); assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId()); assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo()); assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding()); assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence()); assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond()); assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId()); assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations()); assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations()); assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties()); assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter()); } finally { logger.info("Completing message."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } }) .thenCancel() .verify(Duration.ofMinutes(2)); } /** * Verifies we can autocomplete for a queue. * * @param entityType Entity Type. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoComplete(MessagingEntityType entityType) { final int index = TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES; setSenderAndReceiver(entityType, index, false); final ServiceBusReceiverAsyncClient autoCompleteReceiver = getReceiverBuilder(false, entityType, index, false) .buildAsyncClient(); final int numberOfEvents = 3; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId); final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT); Mono.when(messages.stream().map(this::sendMessage) .collect(Collectors.toList())) .block(TIMEOUT); try { StepVerifier.create(autoCompleteReceiver.receiveMessages()) .assertNext(receivedMessage -> { if (lastMessage != null) { assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId()); } else { assertEquals(messageId, receivedMessage.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .thenCancel() .verify(TIMEOUT); } finally { autoCompleteReceiver.close(); } final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT); if (lastMessage == null) { assertNull(newLastMessage, String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a")); } else { assertNotNull(newLastMessage); assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber()); } } /** * Asserts the length and values with in the map. */ private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) { assertTrue(actualMap.size() >= expectedMap.size()); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key); } } /** * Sets the sender and receiver. If session is enabled, then a single-named session receiver is created. */ private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient(); } } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) { Mono.when(messages.stream().map(e -> client.complete(e)) .collect(Collectors.toList())) .block(TIMEOUT); return messages.size(); } }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final boolean isSessionEnabled = false; private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(receiver, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } /** * Verifies that we can create multiple transaction using sender and receiver. */ @Test void createMultipleTransactionTest() { setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); } /** * Verifies that we can create transaction and complete. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2. * receive and settle with transactionContext. 3. commit Rollback this transaction. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) { final MessagingEntityType entityType = MessagingEntityType.QUEUE; setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled); final String messageId1 = UUID.randomUUID().toString(); final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled); final String deadLetterReason = "test reason"; sendMessage(message1).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); final Mono<Void> operation; switch (dispositionStatus) { case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())); messagesPending.decrementAndGet(); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get())); break; case SUSPENDED: DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get()) .setDeadLetterReason(deadLetterReason); operation = receiver.deadLetter(receivedMessage, deadLetterOptions); messagesPending.decrementAndGet(); break; case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get())); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .verifyComplete(); StepVerifier.create(receiver.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using * sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest @Disabled void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) { final boolean shareConnection = true; final boolean useCredentials = false; final int entityIndex = 0; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(sender.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can send and receive two messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } /** * Verifies that we can send and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .thenCancel() .verify(); StepVerifier.create(receiver.receiveMessages()) .thenAwait(Duration.ofSeconds(35)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 1, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.peekMessage()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> receiver.complete(receivedMessage).block(OPERATION_TIMEOUT)) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can schedule and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest /** * Verifies that we can cancel a scheduled message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10); final Duration delayDuration = Duration.ofSeconds(3); final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber); assertNotNull(sequenceNumber); Mono.delay(delayDuration) .then(sender.cancelScheduledMessage(sequenceNumber)) .block(TIMEOUT); messagesPending.decrementAndGet(); logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber); StepVerifier.create(receiver.receiveMessages().take(1)) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 3, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); try { StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber())) .assertNext(m -> { assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber()); assertMessageEquals(m, messageId, isSessionEnabled); }) .verifyComplete(); } finally { receiver.complete(receivedMessage) .block(Duration.ofSeconds(10)); messagesPending.decrementAndGet(); } } /** * Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled); final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> { final Map<String, Object> properties = message.getApplicationProperties(); final Object value = properties.get(MESSAGE_POSITION_ID); assertTrue(value instanceof Integer, "Did not contain correct position number: " + value); final int position = (int) value; assertEquals(index, position); }; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES); if (isSessionEnabled) { messages.forEach(m -> m.setSessionId(sessionId)); } sender.sendMessages(messages) .doOnSuccess(aVoid -> { int number = messagesPending.addAndGet(messages.size()); logger.info("Number of messages sent: {}", number); }) .block(TIMEOUT); try { StepVerifier.create(receiver.peekMessages(3)) .assertNext(message -> checkCorrectMessage.accept(message, 0)) .assertNext(message -> checkCorrectMessage.accept(message, 1)) .assertNext(message -> checkCorrectMessage.accept(message, 2)) .verifyComplete(); StepVerifier.create(receiver.peekMessages(4)) .assertNext(message -> checkCorrectMessage.accept(message, 3)) .assertNext(message -> checkCorrectMessage.accept(message, 4)) .assertNext(message -> checkCorrectMessage.accept(message, 5)) .assertNext(message -> checkCorrectMessage.accept(message, 6)) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .assertNext(message -> checkCorrectMessage.accept(message, 7)) .verifyComplete(); } finally { AtomicInteger completed = new AtomicInteger(); StepVerifier.create(receiver.receiveMessages().take(messages.size())) .thenConsumeWhile(receivedMessage -> { completed.incrementAndGet(); receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); return completed.get() <= messages.size(); }) .expectComplete() .verify(); messagesPending.addAndGet(-messages.size()); } } /** * Verifies that we can send and peek a batch of messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .expectNextCount(maxMessages) .verifyComplete(); StepVerifier.create(receiver.receiveMessages().take(maxMessages)) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .expectComplete() .verify(TIMEOUT); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int maxMessages = 10; final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can dead-letter a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } /** * Verifies that we can renew message lock on a non-session receiver. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndRenewLock(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); assertNotNull(receivedMessage.getLockedUntil()); final OffsetDateTime initialLock = receivedMessage.getLockedUntil(); logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock); try { StepVerifier.create(Mono.delay(Duration.ofSeconds(7)) .then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage)))) .assertNext(lockedUntil -> { assertTrue(lockedUntil.isAfter(initialLock), String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]", lockedUntil, initialLock)); }) .verifyComplete(); } finally { logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber()); receiver.complete(receivedMessage) .doOnSuccess(aVoid -> messagesPending.decrementAndGet()) .block(TIMEOUT); } } /** * Verifies that the lock can be automatically renewed. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); if (isSessionEnabled) { message.setSessionId(sessionId); } sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockedUntil()); assertNotNull(received.getLockToken()); logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(), received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now()); final OffsetDateTime initial = received.getLockedUntil(); final OffsetDateTime timeToStop = initial.plusSeconds(20); final AtomicInteger iteration = new AtomicInteger(); while (iteration.get() < 4) { logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException error) { logger.error("Error occurred while sleeping: " + error); } } logger.info(new Date() + " . Completing message after delay ....."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .thenCancel() .verify(Duration.ofMinutes(2)); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.abandon(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.defer(receivedMessage)) .verifyComplete(); receiver.receiveDeferredMessage(receivedMessage.getSequenceNumber()) .flatMap(m -> receiver.complete(m)) .block(TIMEOUT); messagesPending.decrementAndGet(); } /** * Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); receiver.defer(receivedMessage).block(TIMEOUT); final ServiceBusReceivedMessage receivedDeferredMessage = receiver .receiveDeferredMessage(receivedMessage.getSequenceNumber()) .block(TIMEOUT); assertNotNull(receivedDeferredMessage); assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber()); final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedDeferredMessage); break; case SUSPENDED: operation = receiver.deadLetter(receivedDeferredMessage); break; case COMPLETED: operation = receiver.complete(receivedDeferredMessage); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .expectComplete() .verify(); if (dispositionStatus != DispositionStatus.COMPLETED) { messagesPending.decrementAndGet(); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) { final boolean isSessionEnabled = true; setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled); Map<String, Object> sentProperties = messageToSend.getApplicationProperties(); sentProperties.put("NullProperty", null); sentProperties.put("BooleanProperty", true); sentProperties.put("ByteProperty", (byte) 1); sentProperties.put("ShortProperty", (short) 2); sentProperties.put("IntProperty", 3); sentProperties.put("LongProperty", 4L); sentProperties.put("FloatProperty", 5.5f); sentProperties.put("DoubleProperty", 6.6f); sentProperties.put("CharProperty", 'z'); sentProperties.put("UUIDProperty", UUID.randomUUID()); sentProperties.put("StringProperty", "string"); sendMessage(messageToSend).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { messagesPending.decrementAndGet(); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); final Map<String, Object> received = receivedMessage.getApplicationProperties(); assertEquals(sentProperties.size(), received.size()); for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) { if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) { assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey())); } else { final Object expected = sentEntry.getValue(); final Object actual = received.get(sentEntry.getKey()); assertEquals(expected, actual, String.format( "Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected, actual)); } } receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); }) .thenCancel() .verify(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void setAndGetSessionState(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, true); final byte[] sessionState = "Finished".getBytes(UTF_8); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, true); sendMessage(messageToSend).block(Duration.ofSeconds(10)); AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>(); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(message -> { logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.", message.getSessionId(), message.getLockToken(), message.getLockedUntil()); receivedMessage.set(message); return receiver.setSessionState(sessionState); })) .expectComplete() .verify(); StepVerifier.create(receiver.getSessionState()) .assertNext(state -> { logger.info("State received: {}", new String(state, UTF_8)); assertArrayEquals(sessionState, state); }) .verifyComplete(); receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } /** * Verifies that we can receive a message from dead letter queue. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveFromDeadLetter(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final ServiceBusReceiverAsyncClient deadLetterReceiver; switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .topicName(topicName) .subscriptionName(subscriptionName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>(); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next() .block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); try { StepVerifier.create(deadLetterReceiver.receiveMessages().take(1)) .assertNext(serviceBusReceivedMessage -> { receivedMessages.add(serviceBusReceivedMessage); assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } finally { int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages); messagesPending.addAndGet(-numberCompleted); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void renewMessageLock(MessagingEntityType entityType) { final boolean isSessionEnabled = false; setSenderAndReceiver(entityType, 0, isSessionEnabled); final Duration maximumDuration = Duration.ofSeconds(35); final Duration sleepDuration = maximumDuration.plusMillis(500); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final ServiceBusReceivedMessage receivedMessage = sendMessage(message) .then(receiver.receiveMessages().next()) .block(TIMEOUT); assertNotNull(receivedMessage); final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil(); assertNotNull(lockedUntil); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration)) .thenAwait(sleepDuration) .then(() -> { logger.info("Completing message."); int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage)); messagesPending.addAndGet(-numberCompleted); }) .expectComplete() .verify(Duration.ofMinutes(3)); } /** * Verifies that we can receive a message which have different section set (i.e header, footer, annotations, * application properties etc). */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndValidateProperties(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final String subject = "subject"; final Map<String, Object> footer = new HashMap<>(); footer.put("footer-key-1", "footer-value-1"); footer.put("footer-key-2", "footer-value-2"); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put("ap-key-1", "ap-value-1"); applicationProperties.put("ap-key-2", "ap-value-2"); final Map<String, Object> deliveryAnnotation = new HashMap<>(); deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1"); deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2"); setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(CONTENTS_BYTES))); expectedAmqpProperties.getProperties().setSubject(subject); expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid"); expectedAmqpProperties.getProperties().setReplyTo("reply-to"); expectedAmqpProperties.getProperties().setContentType("content-type"); expectedAmqpProperties.getProperties().setCorrelationId("correlation-id"); expectedAmqpProperties.getProperties().setTo("to"); expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60)); expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes()); expectedAmqpProperties.getProperties().setContentEncoding("string"); expectedAmqpProperties.getProperties().setGroupSequence(2L); expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30)); expectedAmqpProperties.getHeader().setPriority((short) 2); expectedAmqpProperties.getHeader().setFirstAcquirer(true); expectedAmqpProperties.getHeader().setDurable(true); expectedAmqpProperties.getFooter().putAll(footer); expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation); expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties); final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage(); amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations()); amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties()); amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations()); amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter()); final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader(); header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer()); header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive()); header.setDurable(expectedAmqpProperties.getHeader().isDurable()); header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount()); header.setPriority(expectedAmqpProperties.getHeader().getPriority()); final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties(); amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo())); amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding())); amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime())); amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject())); amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType()); amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId()); amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo()); amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence()); amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId()); amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()); amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime()); amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId()); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockToken()); AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage(); try { assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority()); assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer()); assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId()); assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo()); assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType()); assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId()); assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo()); assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding()); assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence()); assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond()); assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId()); assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations()); assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations()); assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties()); assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter()); } finally { logger.info("Completing message."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } }) .thenCancel() .verify(Duration.ofMinutes(2)); } /** * Verifies we can autocomplete for a queue. * * @param entityType Entity Type. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoComplete(MessagingEntityType entityType) { final int index = TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES; setSenderAndReceiver(entityType, index, false); final ServiceBusReceiverAsyncClient autoCompleteReceiver = getReceiverBuilder(false, entityType, index, false) .buildAsyncClient(); final int numberOfEvents = 3; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId); final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT); Mono.when(messages.stream().map(this::sendMessage) .collect(Collectors.toList())) .block(TIMEOUT); try { StepVerifier.create(autoCompleteReceiver.receiveMessages()) .assertNext(receivedMessage -> { if (lastMessage != null) { assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId()); } else { assertEquals(messageId, receivedMessage.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .thenCancel() .verify(TIMEOUT); } finally { autoCompleteReceiver.close(); } final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT); if (lastMessage == null) { assertNull(newLastMessage, String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a")); } else { assertNotNull(newLastMessage); assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber()); } } /** * Asserts the length and values with in the map. */ private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) { assertTrue(actualMap.size() >= expectedMap.size()); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key); } } /** * Sets the sender and receiver. If session is enabled, then a single-named session receiver is created. */ private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient(); } } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) { Mono.when(messages.stream().map(e -> client.complete(e)) .collect(Collectors.toList())) .block(TIMEOUT); return messages.size(); } }
Same with this... wouldn't we expect `receiver.receiveMessages().take(2)` then not cancel?
void peekMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .expectNextCount(maxMessages) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); }
StepVerifier.create(receiver.receiveMessages())
void peekMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .expectNextCount(maxMessages) .verifyComplete(); StepVerifier.create(receiver.receiveMessages().take(maxMessages)) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .expectComplete() .verify(TIMEOUT); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final List<Long> messagesDeferredPending = new ArrayList<>(); private final boolean isSessionEnabled = false; private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(receiver, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } /** * Verifies that we can create multiple transaction using sender and receiver. */ @Test void createMultipleTransactionTest() { setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); } /** * Verifies that we can create transaction and complete. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2. * receive and settle with transactionContext. 3. commit Rollback this transaction. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) { final MessagingEntityType entityType = MessagingEntityType.QUEUE; setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled); final String messageId1 = UUID.randomUUID().toString(); final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled); final String deadLetterReason = "test reason"; sendMessage(message1).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); final Mono<Void> operation; switch (dispositionStatus) { case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())); messagesPending.decrementAndGet(); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get())); break; case SUSPENDED: DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get()) .setDeadLetterReason(deadLetterReason); operation = receiver.deadLetter(receivedMessage, deadLetterOptions); messagesPending.decrementAndGet(); break; case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get())); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .verifyComplete(); StepVerifier.create(receiver.commitTransaction(transaction.get())) .verifyComplete(); if (dispositionStatus == DispositionStatus.DEFERRED) { messagesDeferredPending.add(receivedMessage.getSequenceNumber()); } } /** * Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using * sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest @Disabled void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) { final boolean shareConnection = true; final boolean useCredentials = false; final int entityIndex = 0; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(sender.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can send and receive two messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that we can send and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); StepVerifier.create(receiver.receiveMessages()) .thenAwait(Duration.ofSeconds(35)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 1, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.peekMessage()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can schedule and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2); sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); StepVerifier.create(Mono.delay(Duration.ofSeconds(4)).then(receiver.receiveMessages().next())) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .verifyComplete(); } /** * Verifies that we can cancel a scheduled message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10); final Duration delayDuration = Duration.ofSeconds(3); final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber); assertNotNull(sequenceNumber); Mono.delay(delayDuration) .then(sender.cancelScheduledMessage(sequenceNumber)) .block(TIMEOUT); messagesPending.decrementAndGet(); logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber); StepVerifier.create(receiver.receiveMessages().take(1)) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 3, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); try { StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber())) .assertNext(m -> { assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber()); assertMessageEquals(m, messageId, isSessionEnabled); }) .verifyComplete(); } finally { receiver.complete(receivedMessage) .block(Duration.ofSeconds(10)); messagesPending.decrementAndGet(); } } /** * Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled); final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> { final Map<String, Object> properties = message.getApplicationProperties(); final Object value = properties.get(MESSAGE_POSITION_ID); assertTrue(value instanceof Integer, "Did not contain correct position number: " + value); final int position = (int) value; assertEquals(index, position); }; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES); if (isSessionEnabled) { messages.forEach(m -> m.setSessionId(sessionId)); } sender.sendMessages(messages) .doOnSuccess(aVoid -> { int number = messagesPending.addAndGet(messages.size()); logger.info("Number of messages sent: {}", number); }) .block(TIMEOUT); try { StepVerifier.create(receiver.peekMessages(3)) .assertNext(message -> checkCorrectMessage.accept(message, 0)) .assertNext(message -> checkCorrectMessage.accept(message, 1)) .assertNext(message -> checkCorrectMessage.accept(message, 2)) .verifyComplete(); StepVerifier.create(receiver.peekMessages(4)) .assertNext(message -> checkCorrectMessage.accept(message, 3)) .assertNext(message -> checkCorrectMessage.accept(message, 4)) .assertNext(message -> checkCorrectMessage.accept(message, 5)) .assertNext(message -> checkCorrectMessage.accept(message, 6)) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .assertNext(message -> checkCorrectMessage.accept(message, 7)) .verifyComplete(); } finally { StepVerifier.create(receiver.receiveMessages().take(messages.size())) .thenConsumeWhile(receivedMessage -> { receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); return true; }) .thenCancel() .verify(); messagesPending.addAndGet(-messages.size()); } } /** * Verifies that we can send and peek a batch of messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int maxMessages = 10; final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can dead-letter a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } /** * Verifies that we can renew message lock on a non-session receiver. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndRenewLock(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); assertNotNull(receivedMessage.getLockedUntil()); final OffsetDateTime initialLock = receivedMessage.getLockedUntil(); logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock); try { StepVerifier.create(Mono.delay(Duration.ofSeconds(7)) .then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage)))) .assertNext(lockedUntil -> { assertTrue(lockedUntil.isAfter(initialLock), String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]", lockedUntil, initialLock)); }) .verifyComplete(); } finally { logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber()); receiver.complete(receivedMessage) .doOnSuccess(aVoid -> messagesPending.decrementAndGet()) .block(TIMEOUT); } } /** * Verifies that the lock can be automatically renewed. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); if (isSessionEnabled) { message.setSessionId(sessionId); } sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockedUntil()); assertNotNull(received.getLockToken()); logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(), received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now()); final OffsetDateTime initial = received.getLockedUntil(); final OffsetDateTime timeToStop = initial.plusSeconds(20); final AtomicInteger iteration = new AtomicInteger(); while (iteration.get() < 4) { logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException error) { logger.error("Error occurred while sleeping: " + error); } } logger.info(new Date() + " . Completing message after delay ....."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .thenCancel() .verify(Duration.ofMinutes(2)); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.abandon(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.defer(receivedMessage)) .verifyComplete(); receiver.receiveDeferredMessage(receivedMessage.getSequenceNumber()) .flatMap(m -> receiver.complete(m)) .block(TIMEOUT); messagesPending.decrementAndGet(); } /** * Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); receiver.defer(receivedMessage).block(TIMEOUT); final ServiceBusReceivedMessage receivedDeferredMessage = receiver .receiveDeferredMessage(receivedMessage.getSequenceNumber()) .block(TIMEOUT); assertNotNull(receivedDeferredMessage); assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber()); final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedDeferredMessage); messagesDeferredPending.add(receivedDeferredMessage.getSequenceNumber()); break; case SUSPENDED: operation = receiver.deadLetter(receivedDeferredMessage); break; case COMPLETED: operation = receiver.complete(receivedDeferredMessage); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .expectComplete() .verify(); if (dispositionStatus != DispositionStatus.COMPLETED) { messagesPending.decrementAndGet(); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) { final boolean isSessionEnabled = true; setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled); Map<String, Object> sentProperties = messageToSend.getApplicationProperties(); sentProperties.put("NullProperty", null); sentProperties.put("BooleanProperty", true); sentProperties.put("ByteProperty", (byte) 1); sentProperties.put("ShortProperty", (short) 2); sentProperties.put("IntProperty", 3); sentProperties.put("LongProperty", 4L); sentProperties.put("FloatProperty", 5.5f); sentProperties.put("DoubleProperty", 6.6f); sentProperties.put("CharProperty", 'z'); sentProperties.put("UUIDProperty", UUID.randomUUID()); sentProperties.put("StringProperty", "string"); sendMessage(messageToSend).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { messagesPending.decrementAndGet(); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); final Map<String, Object> received = receivedMessage.getApplicationProperties(); assertEquals(sentProperties.size(), received.size()); for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) { if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) { assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey())); } else { final Object expected = sentEntry.getValue(); final Object actual = received.get(sentEntry.getKey()); assertEquals(expected, actual, String.format( "Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected, actual)); } } receiver.complete(receivedMessage).block(Duration.ofSeconds(15)); }) .thenCancel() .verify(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void setAndGetSessionState(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, true); final byte[] sessionState = "Finished".getBytes(UTF_8); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, true); sendMessage(messageToSend).block(Duration.ofSeconds(10)); AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>(); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(message -> { logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.", message.getSessionId(), message.getLockToken(), message.getLockedUntil()); receivedMessage.set(message); return receiver.setSessionState(sessionState); })) .expectComplete() .verify(); StepVerifier.create(receiver.getSessionState()) .assertNext(state -> { logger.info("State received: {}", new String(state, UTF_8)); assertArrayEquals(sessionState, state); }) .verifyComplete(); receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } /** * Verifies that we can receive a message from dead letter queue. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveFromDeadLetter(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final ServiceBusReceiverAsyncClient deadLetterReceiver; switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .topicName(topicName) .subscriptionName(subscriptionName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>(); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next() .block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); try { StepVerifier.create(deadLetterReceiver.receiveMessages().take(1)) .assertNext(serviceBusReceivedMessage -> { receivedMessages.add(serviceBusReceivedMessage); assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } finally { int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages); messagesPending.addAndGet(-numberCompleted); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void renewMessageLock(MessagingEntityType entityType) { final boolean isSessionEnabled = false; setSenderAndReceiver(entityType, 0, isSessionEnabled); final Duration maximumDuration = Duration.ofSeconds(35); final Duration sleepDuration = maximumDuration.plusMillis(500); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final ServiceBusReceivedMessage receivedMessage = sendMessage(message) .then(receiver.receiveMessages().next()) .block(TIMEOUT); assertNotNull(receivedMessage); final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil(); assertNotNull(lockedUntil); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration)) .thenAwait(sleepDuration) .then(() -> { logger.info("Completing message."); int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage)); messagesPending.addAndGet(-numberCompleted); }) .expectComplete() .verify(Duration.ofMinutes(3)); } /** * Verifies that we can receive a message which have different section set (i.e header, footer, annotations, * application properties etc). */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndValidateProperties(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final String subject = "subject"; final Map<String, Object> footer = new HashMap<>(); footer.put("footer-key-1", "footer-value-1"); footer.put("footer-key-2", "footer-value-2"); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put("ap-key-1", "ap-value-1"); applicationProperties.put("ap-key-2", "ap-value-2"); final Map<String, Object> deliveryAnnotation = new HashMap<>(); deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1"); deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2"); setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(CONTENTS_BYTES))); expectedAmqpProperties.getProperties().setSubject(subject); expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid"); expectedAmqpProperties.getProperties().setReplyTo("reply-to"); expectedAmqpProperties.getProperties().setContentType("content-type"); expectedAmqpProperties.getProperties().setCorrelationId("correlation-id"); expectedAmqpProperties.getProperties().setTo("to"); expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60)); expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes()); expectedAmqpProperties.getProperties().setContentEncoding("string"); expectedAmqpProperties.getProperties().setGroupSequence(2L); expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30)); expectedAmqpProperties.getHeader().setPriority((short) 2); expectedAmqpProperties.getHeader().setFirstAcquirer(true); expectedAmqpProperties.getHeader().setDurable(true); expectedAmqpProperties.getFooter().putAll(footer); expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation); expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties); final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage(); amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations()); amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties()); amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations()); amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter()); final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader(); header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer()); header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive()); header.setDurable(expectedAmqpProperties.getHeader().isDurable()); header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount()); header.setPriority(expectedAmqpProperties.getHeader().getPriority()); final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties(); amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo())); amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding())); amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime())); amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject())); amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType()); amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId()); amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo()); amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence()); amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId()); amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()); amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime()); amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId()); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockToken()); AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage(); try { assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority()); assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer()); assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId()); assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo()); assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType()); assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId()); assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo()); assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding()); assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence()); assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond()); assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId()); assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations()); assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations()); assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties()); assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter()); } finally { logger.info("Completing message."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } }) .thenCancel() .verify(Duration.ofMinutes(2)); } /** * Verifies we can autocomplete for a queue. * * @param entityType Entity Type. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoComplete(MessagingEntityType entityType) { final int index = TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES; setSenderAndReceiver(entityType, index, false); final ServiceBusReceiverAsyncClient autoCompleteReceiver = getReceiverBuilder(false, entityType, index, false) .buildAsyncClient(); final int numberOfEvents = 3; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId); final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT); Mono.when(messages.stream().map(this::sendMessage) .collect(Collectors.toList())) .block(TIMEOUT); try { StepVerifier.create(autoCompleteReceiver.receiveMessages()) .assertNext(receivedMessage -> { if (lastMessage != null) { assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId()); } else { assertEquals(messageId, receivedMessage.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .thenCancel() .verify(TIMEOUT); } finally { autoCompleteReceiver.close(); } final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT); if (lastMessage == null) { assertNull(newLastMessage, String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a")); } else { assertNotNull(newLastMessage); assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber()); } } /** * Asserts the length and values with in the map. */ private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) { assertTrue(actualMap.size() >= expectedMap.size()); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key); } } /** * Sets the sender and receiver. If session is enabled, then a single-named session receiver is created. */ private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient(); } } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) { Mono.when(messages.stream().map(e -> client.complete(e)) .collect(Collectors.toList())) .block(TIMEOUT); return messages.size(); } }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class); private final AtomicInteger messagesPending = new AtomicInteger(); private final boolean isSessionEnabled = false; private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { sessionId = UUID.randomUUID().toString(); } @Override protected void afterTest() { sharedBuilder = null; try { dispose(receiver, sender); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } /** * Verifies that we can create multiple transaction using sender and receiver. */ @Test void createMultipleTransactionTest() { setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(receiver.createTransaction()) .assertNext(Assertions::assertNotNull) .verifyComplete(); } /** * Verifies that we can create transaction and complete. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2. * receive and settle with transactionContext. 3. commit Rollback this transaction. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) { final MessagingEntityType entityType = MessagingEntityType.QUEUE; setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled); final String messageId1 = UUID.randomUUID().toString(); final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled); final String deadLetterReason = "test reason"; sendMessage(message1).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); final Mono<Void> operation; switch (dispositionStatus) { case COMPLETED: operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())); messagesPending.decrementAndGet(); break; case ABANDONED: operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get())); break; case SUSPENDED: DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get()) .setDeadLetterReason(deadLetterReason); operation = receiver.deadLetter(receivedMessage, deadLetterOptions); messagesPending.decrementAndGet(); break; case DEFERRED: operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get())); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .verifyComplete(); StepVerifier.create(receiver.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using * sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest @Disabled void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) { final boolean shareConnection = true; final boolean useCredentials = false; final int entityIndex = 0; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()))) .verifyComplete(); StepVerifier.create(sender.commitTransaction(transaction.get())) .verifyComplete(); } /** * Verifies that we can send and receive two messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } /** * Verifies that we can send and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { final int entityIndex = 0; final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .buildAsyncClient(); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .thenCancel() .verify(); StepVerifier.create(receiver.receiveMessages()) .thenAwait(Duration.ofSeconds(35)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 1, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.peekMessage()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .verifyComplete(); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> receiver.complete(receivedMessage).block(OPERATION_TIMEOUT)) .thenCancel() .verify(); } /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can schedule and receive a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2); sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); StepVerifier.create(Mono.delay(Duration.ofSeconds(4)).then(receiver.receiveMessages().next())) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); messagesPending.decrementAndGet(); }) .verifyComplete(); } /** * Verifies that we can cancel a scheduled message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10); final Duration delayDuration = Duration.ofSeconds(3); final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT); logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber); assertNotNull(sequenceNumber); Mono.delay(delayDuration) .then(sender.cancelScheduledMessage(sequenceNumber)) .block(TIMEOUT); messagesPending.decrementAndGet(); logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber); StepVerifier.create(receiver.receiveMessages().take(1)) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } /** * Verifies that we can send and peek a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 3, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); try { StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber())) .assertNext(m -> { assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber()); assertMessageEquals(m, messageId, isSessionEnabled); }) .verifyComplete(); } finally { receiver.complete(receivedMessage) .block(Duration.ofSeconds(10)); messagesPending.decrementAndGet(); } } /** * Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled); final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> { final Map<String, Object> properties = message.getApplicationProperties(); final Object value = properties.get(MESSAGE_POSITION_ID); assertTrue(value instanceof Integer, "Did not contain correct position number: " + value); final int position = (int) value; assertEquals(index, position); }; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES); if (isSessionEnabled) { messages.forEach(m -> m.setSessionId(sessionId)); } sender.sendMessages(messages) .doOnSuccess(aVoid -> { int number = messagesPending.addAndGet(messages.size()); logger.info("Number of messages sent: {}", number); }) .block(TIMEOUT); try { StepVerifier.create(receiver.peekMessages(3)) .assertNext(message -> checkCorrectMessage.accept(message, 0)) .assertNext(message -> checkCorrectMessage.accept(message, 1)) .assertNext(message -> checkCorrectMessage.accept(message, 2)) .verifyComplete(); StepVerifier.create(receiver.peekMessages(4)) .assertNext(message -> checkCorrectMessage.accept(message, 3)) .assertNext(message -> checkCorrectMessage.accept(message, 4)) .assertNext(message -> checkCorrectMessage.accept(message, 5)) .assertNext(message -> checkCorrectMessage.accept(message, 6)) .verifyComplete(); StepVerifier.create(receiver.peekMessage()) .assertNext(message -> checkCorrectMessage.accept(message, 7)) .verifyComplete(); } finally { AtomicInteger completed = new AtomicInteger(); StepVerifier.create(receiver.receiveMessages().take(messages.size())) .thenConsumeWhile(receivedMessage -> { completed.incrementAndGet(); receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); return completed.get() <= messages.size(); }) .expectComplete() .verify(); messagesPending.addAndGet(-messages.size()); } } /** * Verifies that we can send and peek a batch of messages. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest /** * Verifies that an empty entity does not error when peeking. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled); final int maxMessages = 10; final int fromSequenceNumber = 1; StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber)) .verifyComplete(); } /** * Verifies that we can dead-letter a message. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } /** * Verifies that we can renew message lock on a non-session receiver. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndRenewLock(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); assertNotNull(receivedMessage.getLockedUntil()); final OffsetDateTime initialLock = receivedMessage.getLockedUntil(); logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock); try { StepVerifier.create(Mono.delay(Duration.ofSeconds(7)) .then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage)))) .assertNext(lockedUntil -> { assertTrue(lockedUntil.isAfter(initialLock), String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]", lockedUntil, initialLock)); }) .verifyComplete(); } finally { logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber()); receiver.complete(receivedMessage) .doOnSuccess(aVoid -> messagesPending.decrementAndGet()) .block(TIMEOUT); } } /** * Verifies that the lock can be automatically renewed. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); if (isSessionEnabled) { message.setSessionId(sessionId); } sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockedUntil()); assertNotNull(received.getLockToken()); logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(), received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now()); final OffsetDateTime initial = received.getLockedUntil(); final OffsetDateTime timeToStop = initial.plusSeconds(20); final AtomicInteger iteration = new AtomicInteger(); while (iteration.get() < 4) { logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException error) { logger.error("Error occurred while sleeping: " + error); } } logger.info(new Date() + " . Completing message after delay ....."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); }) .thenCancel() .verify(Duration.ofMinutes(2)); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.abandon(receivedMessage)) .verifyComplete(); messagesPending.decrementAndGet(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.defer(receivedMessage)) .verifyComplete(); receiver.receiveDeferredMessage(receivedMessage.getSequenceNumber()) .flatMap(m -> receiver.complete(m)) .block(TIMEOUT); messagesPending.decrementAndGet(); } /** * Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) { setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT); assertNotNull(receivedMessage); receiver.defer(receivedMessage).block(TIMEOUT); final ServiceBusReceivedMessage receivedDeferredMessage = receiver .receiveDeferredMessage(receivedMessage.getSequenceNumber()) .block(TIMEOUT); assertNotNull(receivedDeferredMessage); assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber()); final Mono<Void> operation; switch (dispositionStatus) { case ABANDONED: operation = receiver.abandon(receivedDeferredMessage); break; case SUSPENDED: operation = receiver.deadLetter(receivedDeferredMessage); break; case COMPLETED: operation = receiver.complete(receivedDeferredMessage); break; default: throw logger.logExceptionAsError(new IllegalArgumentException( "Disposition status not recognized for this test case: " + dispositionStatus)); } StepVerifier.create(operation) .expectComplete() .verify(); if (dispositionStatus != DispositionStatus.COMPLETED) { messagesPending.decrementAndGet(); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) { final boolean isSessionEnabled = true; setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled); Map<String, Object> sentProperties = messageToSend.getApplicationProperties(); sentProperties.put("NullProperty", null); sentProperties.put("BooleanProperty", true); sentProperties.put("ByteProperty", (byte) 1); sentProperties.put("ShortProperty", (short) 2); sentProperties.put("IntProperty", 3); sentProperties.put("LongProperty", 4L); sentProperties.put("FloatProperty", 5.5f); sentProperties.put("DoubleProperty", 6.6f); sentProperties.put("CharProperty", 'z'); sentProperties.put("UUIDProperty", UUID.randomUUID()); sentProperties.put("StringProperty", "string"); sendMessage(messageToSend).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(receivedMessage -> { messagesPending.decrementAndGet(); assertMessageEquals(receivedMessage, messageId, isSessionEnabled); final Map<String, Object> received = receivedMessage.getApplicationProperties(); assertEquals(sentProperties.size(), received.size()); for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) { if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) { assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey())); } else { final Object expected = sentEntry.getValue(); final Object actual = received.get(sentEntry.getKey()); assertEquals(expected, actual, String.format( "Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected, actual)); } } receiver.complete(receivedMessage).block(OPERATION_TIMEOUT); }) .thenCancel() .verify(); } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void setAndGetSessionState(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, true); final byte[] sessionState = "Finished".getBytes(UTF_8); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage messageToSend = getMessage(messageId, true); sendMessage(messageToSend).block(Duration.ofSeconds(10)); AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>(); StepVerifier.create(receiver.receiveMessages() .take(1) .flatMap(message -> { logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.", message.getSessionId(), message.getLockToken(), message.getLockedUntil()); receivedMessage.set(message); return receiver.setSessionState(sessionState); })) .expectComplete() .verify(); StepVerifier.create(receiver.getSessionState()) .assertNext(state -> { logger.info("State received: {}", new String(state, UTF_8)); assertArrayEquals(sessionState, state); }) .verifyComplete(); receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } /** * Verifies that we can receive a message from dead letter queue. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveFromDeadLetter(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final int entityIndex = 0; setSenderAndReceiver(entityType, entityIndex, isSessionEnabled); final ServiceBusReceiverAsyncClient deadLetterReceiver; switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); deadLetterReceiver = getBuilder(false).receiver() .topicName(topicName) .subscriptionName(subscriptionName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>(); sendMessage(message).block(TIMEOUT); final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next() .block(OPERATION_TIMEOUT); assertNotNull(receivedMessage); StepVerifier.create(receiver.deadLetter(receivedMessage)) .verifyComplete(); try { StepVerifier.create(deadLetterReceiver.receiveMessages().take(1)) .assertNext(serviceBusReceivedMessage -> { receivedMessages.add(serviceBusReceivedMessage); assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled); }) .thenCancel() .verify(); } finally { int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages); messagesPending.addAndGet(-numberCompleted); } } @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void renewMessageLock(MessagingEntityType entityType) { final boolean isSessionEnabled = false; setSenderAndReceiver(entityType, 0, isSessionEnabled); final Duration maximumDuration = Duration.ofSeconds(35); final Duration sleepDuration = maximumDuration.plusMillis(500); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final ServiceBusReceivedMessage receivedMessage = sendMessage(message) .then(receiver.receiveMessages().next()) .block(TIMEOUT); assertNotNull(receivedMessage); final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil(); assertNotNull(lockedUntil); StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration)) .thenAwait(sleepDuration) .then(() -> { logger.info("Completing message."); int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage)); messagesPending.addAndGet(-numberCompleted); }) .expectComplete() .verify(Duration.ofMinutes(3)); } /** * Verifies that we can receive a message which have different section set (i.e header, footer, annotations, * application properties etc). */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void receiveAndValidateProperties(MessagingEntityType entityType) { final boolean isSessionEnabled = false; final String subject = "subject"; final Map<String, Object> footer = new HashMap<>(); footer.put("footer-key-1", "footer-value-1"); footer.put("footer-key-2", "footer-value-2"); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put("ap-key-1", "ap-value-1"); applicationProperties.put("ap-key-2", "ap-value-2"); final Map<String, Object> deliveryAnnotation = new HashMap<>(); deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1"); deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2"); setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage( new AmqpDataBody(Collections.singletonList(CONTENTS_BYTES))); expectedAmqpProperties.getProperties().setSubject(subject); expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid"); expectedAmqpProperties.getProperties().setReplyTo("reply-to"); expectedAmqpProperties.getProperties().setContentType("content-type"); expectedAmqpProperties.getProperties().setCorrelationId("correlation-id"); expectedAmqpProperties.getProperties().setTo("to"); expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60)); expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes()); expectedAmqpProperties.getProperties().setContentEncoding("string"); expectedAmqpProperties.getProperties().setGroupSequence(2L); expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30)); expectedAmqpProperties.getHeader().setPriority((short) 2); expectedAmqpProperties.getHeader().setFirstAcquirer(true); expectedAmqpProperties.getHeader().setDurable(true); expectedAmqpProperties.getFooter().putAll(footer); expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation); expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties); final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage(); amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations()); amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties()); amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations()); amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter()); final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader(); header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer()); header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive()); header.setDurable(expectedAmqpProperties.getHeader().isDurable()); header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount()); header.setPriority(expectedAmqpProperties.getHeader().getPriority()); final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties(); amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo())); amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding())); amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime())); amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject())); amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType()); amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId()); amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo()); amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence()); amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId()); amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()); amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime()); amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId()); sendMessage(message).block(TIMEOUT); StepVerifier.create(receiver.receiveMessages()) .assertNext(received -> { assertNotNull(received.getLockToken()); AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage(); try { assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority()); assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer()); assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId()); assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo()); assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType()); assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId()); assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo()); assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond()); assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject()); assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding()); assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence()); assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond()); assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId()); assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations()); assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations()); assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties()); assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter()); } finally { logger.info("Completing message."); receiver.complete(received).block(Duration.ofSeconds(15)); messagesPending.decrementAndGet(); } }) .thenCancel() .verify(Duration.ofMinutes(2)); } /** * Verifies we can autocomplete for a queue. * * @param entityType Entity Type. */ @MethodSource("com.azure.messaging.servicebus.IntegrationTestBase @ParameterizedTest void autoComplete(MessagingEntityType entityType) { final int index = TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES; setSenderAndReceiver(entityType, index, false); final ServiceBusReceiverAsyncClient autoCompleteReceiver = getReceiverBuilder(false, entityType, index, false) .buildAsyncClient(); final int numberOfEvents = 3; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId); final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT); Mono.when(messages.stream().map(this::sendMessage) .collect(Collectors.toList())) .block(TIMEOUT); try { StepVerifier.create(autoCompleteReceiver.receiveMessages()) .assertNext(receivedMessage -> { if (lastMessage != null) { assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId()); } else { assertEquals(messageId, receivedMessage.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .assertNext(context -> { if (lastMessage == null) { assertEquals(messageId, context.getMessageId()); } }) .thenCancel() .verify(TIMEOUT); } finally { autoCompleteReceiver.close(); } final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT); if (lastMessage == null) { assertNull(newLastMessage, String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a")); } else { assertNotNull(newLastMessage); assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber()); } } /** * Asserts the length and values with in the map. */ private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) { assertTrue(actualMap.size() >= expectedMap.size()); for (String key : expectedMap.keySet()) { assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key); } } /** * Sets the sender and receiver. If session is enabled, then a single-named session receiver is created. */ private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) { final boolean shareConnection = false; final boolean useCredentials = false; this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection) .buildAsyncClient(); if (isSessionEnabled) { assertNotNull(sessionId, "'sessionId' should have been set."); this.receiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient().acceptSession(sessionId).block(); } else { this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection) .disableAutoComplete() .buildAsyncClient(); } } private Mono<Void> sendMessage(ServiceBusMessage message) { return sender.sendMessage(message).doOnSuccess(aVoid -> { int number = messagesPending.incrementAndGet(); logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number); }); } private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) { Mono.when(messages.stream().map(e -> client.complete(e)) .collect(Collectors.toList())) .block(TIMEOUT); return messages.size(); } }
We are not providing immutable `AmqpMessageBody` . So I do not copy bytes when user create this object and also in getters. Matching how dotnet is doing. Srikanta also commented in his comment above. https://github.com/Azure/azure-sdk-for-java/pull/17464#discussion_r524866610
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = Collections.singletonList(data); return body; }
body.data = Collections.singletonList(data);
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private List<byte[]> data; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can only be called for body type [%s]. Track this issue, " + "https: + "future.", AmqpMessageBodyType.DATA.toString()))); } return new IterableStream<>(data); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can only be called for body type [%s]. Track this issue, " + "https: + "future.", AmqpMessageBodyType.DATA.toString()))); } return data.get(0); } }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; } }
Should we use `Collections.emptyMap()` here to use a singleton instead of creating a new instance?
public TaggedBlobItem(String containerName, String name) { this(containerName, name, new HashMap<>()); }
this(containerName, name, new HashMap<>());
public TaggedBlobItem(String containerName, String name) { this(containerName, name, Collections.emptyMap()); }
class TaggedBlobItem { /** * Constructor to create a new TaggedBlobItem * @param containerName The container name * @param name The blob name */ /** * Constructor to create a new TaggedBlobItem * @param containerName The container name * @param name The blob name * @param tags The blob tags */ public TaggedBlobItem(String containerName, String name, Map<String, String> tags) { this.name = name; this.containerName = containerName; this.tags = tags; } /* * The name property. */ private final String name; /* * The containerName property. */ private final String containerName; private final Map<String, String> tags; /** * Get the name property: The name property. * * @return the name value. */ public String getName() { return this.name; } /** * Get the containerName property: The containerName property. * * @return the containerName value. */ public String getContainerName() { return this.containerName; } /** * Get the tags property: The tags property. * * @return the tags value. */ public Map<String, String> getTags() { return this.tags; } }
class TaggedBlobItem { /** * Constructor to create a new TaggedBlobItem * @param containerName The container name * @param name The blob name */ /** * Constructor to create a new TaggedBlobItem * @param containerName The container name * @param name The blob name * @param tags The blob tags */ public TaggedBlobItem(String containerName, String name, Map<String, String> tags) { this.name = name; this.containerName = containerName; this.tags = tags; } /* * The name property. */ private final String name; /* * The containerName property. */ private final String containerName; private final Map<String, String> tags; /** * Get the name property: The name property. * * @return the name value. */ public String getName() { return this.name; } /** * Get the containerName property: The containerName property. * * @return the containerName value. */ public String getContainerName() { return this.containerName; } /** * Get the tags property: The tags property. * * @return the tags value. */ public Map<String, String> getTags() { return this.tags; } }
@rickle-msft FYI this discussion here is still developing https://github.com/Azure/azure-sdk-for-net/pull/16123#discussion_r518945485 . We might need to loosen this validation if it turns out that new protocols can be returned with old service version in the future.
public static ShareEnabledProtocols parse(String str) { if (str == null) { return null; } if (str.equals(Constants.HeaderConstants.SMB_PROTOCOL)) { return new ShareEnabledProtocols().setSmb(true); } else if (str.equals(Constants.HeaderConstants.NFS_PROTOCOL)) { return new ShareEnabledProtocols().setNfs(true); } throw new IllegalArgumentException("String is not an understood protocol: " + str); }
throw new IllegalArgumentException("String is not an understood protocol: " + str);
public static ShareEnabledProtocols parse(String str) { if (str == null) { return null; } if (str.equals(Constants.HeaderConstants.SMB_PROTOCOL)) { return new ShareEnabledProtocols().setSmb(true); } else if (str.equals(Constants.HeaderConstants.NFS_PROTOCOL)) { return new ShareEnabledProtocols().setNfs(true); } throw new IllegalArgumentException("String is not an understood protocol: " + str); }
class ShareEnabledProtocols { private boolean smb; private boolean nfs; /** * @return Enable SMB */ public boolean isSmb() { return smb; } /** * @return Enable NFS */ public boolean isNfs() { return nfs; } /** * @param smb Enable SMB * @return The updated object */ public ShareEnabledProtocols setSmb(boolean smb) { this.smb = smb; return this; } /** * @param nfs Enable NFS * @return The updated object */ public ShareEnabledProtocols setNfs(boolean nfs) { this.nfs = nfs; return this; } /** * Converts the given protocols to a {@code String}. * * @return A {@code String} which represents the enabled protocols. * @throws IllegalArgumentException If both SMB and NFS are set. */ public String toString() { if (this.smb) { if (this.nfs) { throw new IllegalArgumentException("SMB and NFS cannot both be set."); } return Constants.HeaderConstants.SMB_PROTOCOL; } if (this.nfs) { return Constants.HeaderConstants.NFS_PROTOCOL; } return null; } /** * Parses a {@code String} into a {@code SharEnabledProtocol}. * * @param str The string to parse. * @return A {@code ShareEnabledProtocol} represented by the string. * @throws IllegalArgumentException If the String is not a recognized protocol. */ }
class ShareEnabledProtocols { private final ClientLogger logger = new ClientLogger(ShareEnabledProtocols.class); private boolean smb; private boolean nfs; /** * @return Enable SMB */ public boolean isSmb() { return smb; } /** * @return Enable NFS */ public boolean isNfs() { return nfs; } /** * @param smb Enable SMB * @return The updated object */ public ShareEnabledProtocols setSmb(boolean smb) { this.smb = smb; return this; } /** * @param nfs Enable NFS * @return The updated object */ public ShareEnabledProtocols setNfs(boolean nfs) { this.nfs = nfs; return this; } /** * Converts the given protocols to a {@code String}. * * @return A {@code String} which represents the enabled protocols. * @throws IllegalArgumentException If both SMB and NFS are set. */ public String toString() { if (this.smb) { if (this.nfs) { throw logger.logExceptionAsError(new IllegalArgumentException("SMB and NFS cannot both be set.")); } return Constants.HeaderConstants.SMB_PROTOCOL; } if (this.nfs) { return Constants.HeaderConstants.NFS_PROTOCOL; } return ""; } /** * Parses a {@code String} into a {@code SharEnabledProtocol}. * * @param str The string to parse. * @return A {@code ShareEnabledProtocol} represented by the string. * @throws IllegalArgumentException If the String is not a recognized protocol. */ }
Maybe this should be `ExpandableStringEnum` like this thing https://github.com/Azure/azure-sdk-for-java/blob/7e6e16499bd02077e9159245ce5b43e43ebf9af7/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/models/AccessTier.java#L14
public static ShareEnabledProtocols parse(String str) { if (str == null) { return null; } if (str.equals(Constants.HeaderConstants.SMB_PROTOCOL)) { return new ShareEnabledProtocols().setSmb(true); } else if (str.equals(Constants.HeaderConstants.NFS_PROTOCOL)) { return new ShareEnabledProtocols().setNfs(true); } throw new IllegalArgumentException("String is not an understood protocol: " + str); }
throw new IllegalArgumentException("String is not an understood protocol: " + str);
public static ShareEnabledProtocols parse(String str) { if (str == null) { return null; } if (str.equals(Constants.HeaderConstants.SMB_PROTOCOL)) { return new ShareEnabledProtocols().setSmb(true); } else if (str.equals(Constants.HeaderConstants.NFS_PROTOCOL)) { return new ShareEnabledProtocols().setNfs(true); } throw new IllegalArgumentException("String is not an understood protocol: " + str); }
class ShareEnabledProtocols { private boolean smb; private boolean nfs; /** * @return Enable SMB */ public boolean isSmb() { return smb; } /** * @return Enable NFS */ public boolean isNfs() { return nfs; } /** * @param smb Enable SMB * @return The updated object */ public ShareEnabledProtocols setSmb(boolean smb) { this.smb = smb; return this; } /** * @param nfs Enable NFS * @return The updated object */ public ShareEnabledProtocols setNfs(boolean nfs) { this.nfs = nfs; return this; } /** * Converts the given protocols to a {@code String}. * * @return A {@code String} which represents the enabled protocols. * @throws IllegalArgumentException If both SMB and NFS are set. */ public String toString() { if (this.smb) { if (this.nfs) { throw new IllegalArgumentException("SMB and NFS cannot both be set."); } return Constants.HeaderConstants.SMB_PROTOCOL; } if (this.nfs) { return Constants.HeaderConstants.NFS_PROTOCOL; } return null; } /** * Parses a {@code String} into a {@code SharEnabledProtocol}. * * @param str The string to parse. * @return A {@code ShareEnabledProtocol} represented by the string. * @throws IllegalArgumentException If the String is not a recognized protocol. */ }
class ShareEnabledProtocols { private final ClientLogger logger = new ClientLogger(ShareEnabledProtocols.class); private boolean smb; private boolean nfs; /** * @return Enable SMB */ public boolean isSmb() { return smb; } /** * @return Enable NFS */ public boolean isNfs() { return nfs; } /** * @param smb Enable SMB * @return The updated object */ public ShareEnabledProtocols setSmb(boolean smb) { this.smb = smb; return this; } /** * @param nfs Enable NFS * @return The updated object */ public ShareEnabledProtocols setNfs(boolean nfs) { this.nfs = nfs; return this; } /** * Converts the given protocols to a {@code String}. * * @return A {@code String} which represents the enabled protocols. * @throws IllegalArgumentException If both SMB and NFS are set. */ public String toString() { if (this.smb) { if (this.nfs) { throw logger.logExceptionAsError(new IllegalArgumentException("SMB and NFS cannot both be set.")); } return Constants.HeaderConstants.SMB_PROTOCOL; } if (this.nfs) { return Constants.HeaderConstants.NFS_PROTOCOL; } return ""; } /** * Parses a {@code String} into a {@code SharEnabledProtocol}. * * @param str The string to parse. * @return A {@code ShareEnabledProtocol} represented by the string. * @throws IllegalArgumentException If the String is not a recognized protocol. */ }
I don't think ExpandableStringEnum lets you set more than one?
public static ShareEnabledProtocols parse(String str) { if (str == null) { return null; } if (str.equals(Constants.HeaderConstants.SMB_PROTOCOL)) { return new ShareEnabledProtocols().setSmb(true); } else if (str.equals(Constants.HeaderConstants.NFS_PROTOCOL)) { return new ShareEnabledProtocols().setNfs(true); } throw new IllegalArgumentException("String is not an understood protocol: " + str); }
throw new IllegalArgumentException("String is not an understood protocol: " + str);
public static ShareEnabledProtocols parse(String str) { if (str == null) { return null; } if (str.equals(Constants.HeaderConstants.SMB_PROTOCOL)) { return new ShareEnabledProtocols().setSmb(true); } else if (str.equals(Constants.HeaderConstants.NFS_PROTOCOL)) { return new ShareEnabledProtocols().setNfs(true); } throw new IllegalArgumentException("String is not an understood protocol: " + str); }
class ShareEnabledProtocols { private boolean smb; private boolean nfs; /** * @return Enable SMB */ public boolean isSmb() { return smb; } /** * @return Enable NFS */ public boolean isNfs() { return nfs; } /** * @param smb Enable SMB * @return The updated object */ public ShareEnabledProtocols setSmb(boolean smb) { this.smb = smb; return this; } /** * @param nfs Enable NFS * @return The updated object */ public ShareEnabledProtocols setNfs(boolean nfs) { this.nfs = nfs; return this; } /** * Converts the given protocols to a {@code String}. * * @return A {@code String} which represents the enabled protocols. * @throws IllegalArgumentException If both SMB and NFS are set. */ public String toString() { if (this.smb) { if (this.nfs) { throw new IllegalArgumentException("SMB and NFS cannot both be set."); } return Constants.HeaderConstants.SMB_PROTOCOL; } if (this.nfs) { return Constants.HeaderConstants.NFS_PROTOCOL; } return null; } /** * Parses a {@code String} into a {@code SharEnabledProtocol}. * * @param str The string to parse. * @return A {@code ShareEnabledProtocol} represented by the string. * @throws IllegalArgumentException If the String is not a recognized protocol. */ }
class ShareEnabledProtocols { private final ClientLogger logger = new ClientLogger(ShareEnabledProtocols.class); private boolean smb; private boolean nfs; /** * @return Enable SMB */ public boolean isSmb() { return smb; } /** * @return Enable NFS */ public boolean isNfs() { return nfs; } /** * @param smb Enable SMB * @return The updated object */ public ShareEnabledProtocols setSmb(boolean smb) { this.smb = smb; return this; } /** * @param nfs Enable NFS * @return The updated object */ public ShareEnabledProtocols setNfs(boolean nfs) { this.nfs = nfs; return this; } /** * Converts the given protocols to a {@code String}. * * @return A {@code String} which represents the enabled protocols. * @throws IllegalArgumentException If both SMB and NFS are set. */ public String toString() { if (this.smb) { if (this.nfs) { throw logger.logExceptionAsError(new IllegalArgumentException("SMB and NFS cannot both be set.")); } return Constants.HeaderConstants.SMB_PROTOCOL; } if (this.nfs) { return Constants.HeaderConstants.NFS_PROTOCOL; } return ""; } /** * Parses a {@code String} into a {@code SharEnabledProtocol}. * * @param str The string to parse. * @return A {@code ShareEnabledProtocol} represented by the string. * @throws IllegalArgumentException If the String is not a recognized protocol. */ }
That would bring us back to `ExpandableStringEnum<ShareProtocol>` and `Set<ShareProtocol>` (a variation of enumset). Question is if we want to expose future expansion to older SDK users or not. Btw. Let's not block on this here as we are yet to hear from the service team. we can address this later.
public static ShareEnabledProtocols parse(String str) { if (str == null) { return null; } if (str.equals(Constants.HeaderConstants.SMB_PROTOCOL)) { return new ShareEnabledProtocols().setSmb(true); } else if (str.equals(Constants.HeaderConstants.NFS_PROTOCOL)) { return new ShareEnabledProtocols().setNfs(true); } throw new IllegalArgumentException("String is not an understood protocol: " + str); }
throw new IllegalArgumentException("String is not an understood protocol: " + str);
public static ShareEnabledProtocols parse(String str) { if (str == null) { return null; } if (str.equals(Constants.HeaderConstants.SMB_PROTOCOL)) { return new ShareEnabledProtocols().setSmb(true); } else if (str.equals(Constants.HeaderConstants.NFS_PROTOCOL)) { return new ShareEnabledProtocols().setNfs(true); } throw new IllegalArgumentException("String is not an understood protocol: " + str); }
class ShareEnabledProtocols { private boolean smb; private boolean nfs; /** * @return Enable SMB */ public boolean isSmb() { return smb; } /** * @return Enable NFS */ public boolean isNfs() { return nfs; } /** * @param smb Enable SMB * @return The updated object */ public ShareEnabledProtocols setSmb(boolean smb) { this.smb = smb; return this; } /** * @param nfs Enable NFS * @return The updated object */ public ShareEnabledProtocols setNfs(boolean nfs) { this.nfs = nfs; return this; } /** * Converts the given protocols to a {@code String}. * * @return A {@code String} which represents the enabled protocols. * @throws IllegalArgumentException If both SMB and NFS are set. */ public String toString() { if (this.smb) { if (this.nfs) { throw new IllegalArgumentException("SMB and NFS cannot both be set."); } return Constants.HeaderConstants.SMB_PROTOCOL; } if (this.nfs) { return Constants.HeaderConstants.NFS_PROTOCOL; } return null; } /** * Parses a {@code String} into a {@code SharEnabledProtocol}. * * @param str The string to parse. * @return A {@code ShareEnabledProtocol} represented by the string. * @throws IllegalArgumentException If the String is not a recognized protocol. */ }
class ShareEnabledProtocols { private final ClientLogger logger = new ClientLogger(ShareEnabledProtocols.class); private boolean smb; private boolean nfs; /** * @return Enable SMB */ public boolean isSmb() { return smb; } /** * @return Enable NFS */ public boolean isNfs() { return nfs; } /** * @param smb Enable SMB * @return The updated object */ public ShareEnabledProtocols setSmb(boolean smb) { this.smb = smb; return this; } /** * @param nfs Enable NFS * @return The updated object */ public ShareEnabledProtocols setNfs(boolean nfs) { this.nfs = nfs; return this; } /** * Converts the given protocols to a {@code String}. * * @return A {@code String} which represents the enabled protocols. * @throws IllegalArgumentException If both SMB and NFS are set. */ public String toString() { if (this.smb) { if (this.nfs) { throw logger.logExceptionAsError(new IllegalArgumentException("SMB and NFS cannot both be set.")); } return Constants.HeaderConstants.SMB_PROTOCOL; } if (this.nfs) { return Constants.HeaderConstants.NFS_PROTOCOL; } return ""; } /** * Parses a {@code String} into a {@code SharEnabledProtocol}. * * @param str The string to parse. * @return A {@code ShareEnabledProtocol} represented by the string. * @throws IllegalArgumentException If the String is not a recognized protocol. */ }
does the order of action matters?
private void handleResponse(List<TryTrackingIndexAction<T>> actions, IndexBatchResponse batchResponse) { /* * Batch has been split until it had one document in it and it returned a 413 response. */ if (batchResponse.getStatusCode() == HttpURLConnection.HTTP_ENTITY_TOO_LARGE && batchResponse.getCount() == 1) { IndexAction<T> action = actions.get(batchResponse.getOffset()).getAction(); onActionErrorBiConsumer.accept(action, new RuntimeException("Document is too large to be indexed and won't be tried again.")); return; } List<TryTrackingIndexAction<T>> actionsToRetry = new ArrayList<>(); boolean has503 = batchResponse.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (batchResponse.getResults() == null) { /* * Null results indicates that the entire request failed. Retry all documents. */ int offset = batchResponse.getOffset(); actionsToRetry.addAll(actions.subList(offset, offset + batchResponse.getCount())); } else { /* * We got back a result set, correlate responses to their request document and add retryable actions back * into the queue. */ for (IndexingResult result : batchResponse.getResults()) { String key = result.getKey(); TryTrackingIndexAction<T> action = actions.stream().skip(batchResponse.getOffset()) .filter(a -> key.equals(a.getKey())) .findFirst() .orElse(null); if (action == null) { logger.warning("Unable to correlate result key {} to initial document.", key); continue; } if (isSuccess(result.getStatusCode())) { onActionSucceededConsumer.accept(action.getAction()); } else if (isRetryable(result.getStatusCode())) { has503 |= result.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (action.getTryCount() < maxRetries) { action.incrementTryCount(); actionsToRetry.add(action); } else { onActionErrorBiConsumer.accept(action.getAction(), new RuntimeException("Document has reached retry limit and won't be tried again.")); } } else { onActionErrorBiConsumer.accept(action.getAction(), new RuntimeException(result.getErrorMessage())); } } } if (has503) { currentRetryDelay = calculateRetryDelay(backoffCount.getAndIncrement()); } else { backoffCount.set(0); currentRetryDelay = Duration.ZERO; } if (!CoreUtils.isNullOrEmpty(actionsToRetry)) { synchronized (actionsMutex) { for (int i = actionsToRetry.size() - 1; i >= 0; i--) { this.actions.push(actionsToRetry.get(i)); } } } }
actionsToRetry.addAll(actions.subList(offset, offset + batchResponse.getCount()));
private void handleResponse(List<TryTrackingIndexAction<T>> actions, IndexBatchResponse batchResponse) { /* * Batch has been split until it had one document in it and it returned a 413 response. */ if (batchResponse.getStatusCode() == HttpURLConnection.HTTP_ENTITY_TOO_LARGE && batchResponse.getCount() == 1) { IndexAction<T> action = actions.get(batchResponse.getOffset()).getAction(); onActionErrorBiConsumer.accept(action, new RuntimeException("Document is too large to be indexed and won't be tried again.")); return; } List<TryTrackingIndexAction<T>> actionsToRetry = new ArrayList<>(); boolean has503 = batchResponse.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (batchResponse.getResults() == null) { /* * Null results indicates that the entire request failed. Retry all documents. */ int offset = batchResponse.getOffset(); actionsToRetry.addAll(actions.subList(offset, offset + batchResponse.getCount())); } else { /* * We got back a result set, correlate responses to their request document and add retryable actions back * into the queue. */ for (IndexingResult result : batchResponse.getResults()) { String key = result.getKey(); TryTrackingIndexAction<T> action = actions.stream().skip(batchResponse.getOffset()) .filter(a -> key.equals(a.getKey())) .findFirst() .orElse(null); if (action == null) { logger.warning("Unable to correlate result key {} to initial document.", key); continue; } if (isSuccess(result.getStatusCode())) { onActionSucceededConsumer.accept(action.getAction()); } else if (isRetryable(result.getStatusCode())) { has503 |= result.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (action.getTryCount() < maxRetries) { action.incrementTryCount(); actionsToRetry.add(action); } else { onActionErrorBiConsumer.accept(action.getAction(), new RuntimeException("Document has reached retry limit and won't be tried again.")); } } else { onActionErrorBiConsumer.accept(action.getAction(), new RuntimeException(result.getErrorMessage())); } } } if (has503) { currentRetryDelay = calculateRetryDelay(backoffCount.getAndIncrement()); } else { backoffCount.set(0); currentRetryDelay = Duration.ZERO; } if (!CoreUtils.isNullOrEmpty(actionsToRetry)) { synchronized (actionsMutex) { for (int i = actionsToRetry.size() - 1; i >= 0; i--) { this.actions.push(actionsToRetry.get(i)); } } } }
class SearchIndexingPublisher<T> { private static final double JITTER_FACTOR = 0.05; private final ClientLogger logger = new ClientLogger(SearchIndexingPublisher.class); private final SearchAsyncClient client; private final boolean autoFlush; private final int batchActionCount; private final int maxRetries; private final Duration retryDelay; private final Duration maxRetryDelay; private final Consumer<IndexAction<T>> onActionAddedConsumer; private final Consumer<IndexAction<T>> onActionSentConsumer; private final Consumer<IndexAction<T>> onActionSucceededConsumer; private final BiConsumer<IndexAction<T>, Throwable> onActionErrorBiConsumer; private final Function<T, String> documentKeyRetriever; private final Object actionsMutex = new Object(); private final Deque<TryTrackingIndexAction<T>> actions = new LinkedList<>(); private final Semaphore processingSemaphore = new Semaphore(1); volatile AtomicInteger backoffCount = new AtomicInteger(); volatile Duration currentRetryDelay = Duration.ZERO; SearchIndexingPublisher(SearchAsyncClient client, SearchIndexingBufferedSenderOptions<T> options) { Objects.requireNonNull(options, "'options' cannot be null."); this.documentKeyRetriever = Objects.requireNonNull(options.getDocumentKeyRetriever(), "'options.documentKeyRetriever' cannot be null"); this.client = client; this.autoFlush = options.getAutoFlush(); this.batchActionCount = options.getInitialBatchActionCount(); this.maxRetries = options.getMaxRetries(); this.retryDelay = options.getRetryDelay(); this.maxRetryDelay = (options.getMaxRetryDelay().compareTo(retryDelay) < 0) ? retryDelay : options.getMaxRetryDelay(); this.onActionAddedConsumer = (action) -> { if (options.getOnActionAdded() != null) { options.getOnActionAdded().accept(action); } }; this.onActionSentConsumer = (action) -> { if (options.getOnActionSent() != null) { options.getOnActionSent().accept(action); } }; this.onActionSucceededConsumer = (action) -> { if (options.getOnActionSucceeded() != null) { options.getOnActionSucceeded().accept(action); } }; this.onActionErrorBiConsumer = (action, throwable) -> { if (options.getOnActionError() != null) { options.getOnActionError().accept(action, throwable); } }; } synchronized Collection<IndexAction<?>> getActions() { return actions.stream().map(TryTrackingIndexAction::getAction).collect(Collectors.toList()); } int getBatchActionCount() { return batchActionCount; } synchronized Mono<Void> addActions(Collection<IndexAction<T>> actions, Context context, Runnable rescheduleFlush) { actions.stream() .map(action -> new TryTrackingIndexAction<>(action, documentKeyRetriever.apply(action.getDocument()))) .forEach(action -> { onActionAddedConsumer.accept(action.getAction()); this.actions.add(action); }); if (autoFlush && batchAvailableForProcessing()) { rescheduleFlush.run(); return flush(context, false); } return Mono.empty(); } Mono<Void> flush(Context context, boolean awaitLock) { if (awaitLock) { processingSemaphore.acquireUninterruptibly(); return createAndProcessBatch(context) .doFinally(ignored -> processingSemaphore.release()); } else if (processingSemaphore.tryAcquire()) { return createAndProcessBatch(context) .doFinally(ignored -> processingSemaphore.release()); } else { return Mono.empty(); } } private Mono<Void> createAndProcessBatch(Context context) { final List<TryTrackingIndexAction<T>> batchActions = new ArrayList<>(batchActionCount); synchronized (actionsMutex) { int size = Math.min(batchActionCount, this.actions.size()); for (int i = 0; i < size; i++) { TryTrackingIndexAction<T> action = actions.pop(); onActionSentConsumer.accept(action.getAction()); batchActions.add(action); } } if (CoreUtils.isNullOrEmpty(batchActions)) { return Mono.empty(); } List<com.azure.search.documents.implementation.models.IndexAction> convertedActions = batchActions.stream() .map(action -> IndexActionConverter.map(action.getAction(), client.serializer)) .collect(Collectors.toList()); return sendBatch(convertedActions, 0, context) .map(response -> { handleResponse(batchActions, response); return response; }).then(Mono.defer(() -> batchAvailableForProcessing() ? createAndProcessBatch(context) : Mono.empty())); } /* * This may result in more than one service call in the case where the index batch is too large and we attempt to * split it. */ private Flux<IndexBatchResponse> sendBatch( List<com.azure.search.documents.implementation.models.IndexAction> actions, int actionsOffset, Context context) { return client.indexDocumentsWithResponse(actions, true, context) .delaySubscription(currentRetryDelay) .flatMapMany(response -> Flux.just( new IndexBatchResponse(response.getStatusCode(), response.getValue().getResults(), actionsOffset, actions.size(), false))) .onErrorResume(IndexBatchException.class, exception -> Flux .just(new IndexBatchResponse(207, exception.getIndexingResults(), actionsOffset, actions.size(), true))) .onErrorResume(HttpResponseException.class, exception -> { /* * If we received an error response where the payload was too large split it into two smaller payloads * and attempt to index again. If the number of index actions was one raise the error as we cannot split * that any further. */ int statusCode = exception.getResponse().getStatusCode(); if (exception.getResponse().getStatusCode() == HttpURLConnection.HTTP_ENTITY_TOO_LARGE) { int actionCount = actions.size(); if (actionCount == 1) { return Flux.just(new IndexBatchResponse(statusCode, null, actionsOffset, actionCount, true)); } int splitOffset = Math.round(actionCount / 2.0f); return Flux.concat( sendBatch(actions.subList(0, splitOffset), 0, context), sendBatch(actions.subList(splitOffset, actionCount), splitOffset, context) ); } return Flux.just(new IndexBatchResponse(statusCode, null, actionsOffset, actions.size(), true)); }); } private boolean batchAvailableForProcessing() { return actions.size() >= batchActionCount; } private static boolean isSuccess(int statusCode) { return statusCode == 200 || statusCode == 201; } private static boolean isRetryable(int statusCode) { return statusCode == 409 || statusCode == 422 || statusCode == 503; } /* * Helper class which contains the IndexAction and the number of times it has tried to be indexed. */ private static final class TryTrackingIndexAction<T> { private final IndexAction<T> action; private final String key; private int tryCount = 0; private TryTrackingIndexAction(IndexAction<T> action, String key) { this.action = action; this.key = key; } public IndexAction<T> getAction() { return action; } public String getKey() { return key; } public int getTryCount() { return tryCount; } public void incrementTryCount() { tryCount++; } } /* * Helper class which keeps track of the service results, the offset from the initial request set if it was split, * and whether the response is an error status. */ private static final class IndexBatchResponse { private final int statusCode; private final List<IndexingResult> results; private final int offset; private final int count; private final boolean isError; private IndexBatchResponse(int statusCode, List<IndexingResult> results, int offset, int count, boolean isError) { this.statusCode = statusCode; this.results = results; this.offset = offset; this.count = count; this.isError = isError; } public int getStatusCode() { return statusCode; } public List<IndexingResult> getResults() { return results; } public int getOffset() { return offset; } public int getCount() { return count; } public boolean isError() { return isError; } } private Duration calculateRetryDelay(int backoffCount) { long delayWithJitterInNanos = ThreadLocalRandom.current() .nextLong((long) (retryDelay.toNanos() * (1 - JITTER_FACTOR)), (long) (retryDelay.toNanos() * (1 + JITTER_FACTOR))); return Duration.ofNanos(Math.min((1 << backoffCount) * delayWithJitterInNanos, maxRetryDelay.toNanos())); } }
class SearchIndexingPublisher<T> { private static final double JITTER_FACTOR = 0.05; private final ClientLogger logger = new ClientLogger(SearchIndexingPublisher.class); private final SearchAsyncClient client; private final boolean autoFlush; private final int batchActionCount; private final int maxRetries; private final Duration retryDelay; private final Duration maxRetryDelay; private final Consumer<IndexAction<T>> onActionAddedConsumer; private final Consumer<IndexAction<T>> onActionSentConsumer; private final Consumer<IndexAction<T>> onActionSucceededConsumer; private final BiConsumer<IndexAction<T>, Throwable> onActionErrorBiConsumer; private final Function<T, String> documentKeyRetriever; private final Object actionsMutex = new Object(); private final Deque<TryTrackingIndexAction<T>> actions = new LinkedList<>(); private final Semaphore processingSemaphore = new Semaphore(1); volatile AtomicInteger backoffCount = new AtomicInteger(); volatile Duration currentRetryDelay = Duration.ZERO; SearchIndexingPublisher(SearchAsyncClient client, SearchIndexingBufferedSenderOptions<T> options) { Objects.requireNonNull(options, "'options' cannot be null."); this.documentKeyRetriever = Objects.requireNonNull(options.getDocumentKeyRetriever(), "'options.documentKeyRetriever' cannot be null"); this.client = client; this.autoFlush = options.getAutoFlush(); this.batchActionCount = options.getInitialBatchActionCount(); this.maxRetries = options.getMaxRetries(); this.retryDelay = options.getRetryDelay(); this.maxRetryDelay = (options.getMaxRetryDelay().compareTo(retryDelay) < 0) ? retryDelay : options.getMaxRetryDelay(); this.onActionAddedConsumer = (action) -> { if (options.getOnActionAdded() != null) { options.getOnActionAdded().accept(action); } }; this.onActionSentConsumer = (action) -> { if (options.getOnActionSent() != null) { options.getOnActionSent().accept(action); } }; this.onActionSucceededConsumer = (action) -> { if (options.getOnActionSucceeded() != null) { options.getOnActionSucceeded().accept(action); } }; this.onActionErrorBiConsumer = (action, throwable) -> { if (options.getOnActionError() != null) { options.getOnActionError().accept(action, throwable); } }; } synchronized Collection<IndexAction<?>> getActions() { return actions.stream().map(TryTrackingIndexAction::getAction).collect(Collectors.toList()); } int getBatchActionCount() { return batchActionCount; } synchronized Mono<Void> addActions(Collection<IndexAction<T>> actions, Context context, Runnable rescheduleFlush) { actions.stream() .map(action -> new TryTrackingIndexAction<>(action, documentKeyRetriever.apply(action.getDocument()))) .forEach(action -> { onActionAddedConsumer.accept(action.getAction()); this.actions.add(action); }); if (autoFlush && batchAvailableForProcessing()) { rescheduleFlush.run(); return flush(context, false); } return Mono.empty(); } Mono<Void> flush(Context context, boolean awaitLock) { if (awaitLock) { processingSemaphore.acquireUninterruptibly(); return createAndProcessBatch(context) .doFinally(ignored -> processingSemaphore.release()); } else if (processingSemaphore.tryAcquire()) { return createAndProcessBatch(context) .doFinally(ignored -> processingSemaphore.release()); } else { return Mono.empty(); } } private Mono<Void> createAndProcessBatch(Context context) { final List<TryTrackingIndexAction<T>> batchActions = new ArrayList<>(batchActionCount); synchronized (actionsMutex) { int size = Math.min(batchActionCount, this.actions.size()); for (int i = 0; i < size; i++) { TryTrackingIndexAction<T> action = actions.pop(); onActionSentConsumer.accept(action.getAction()); batchActions.add(action); } } if (CoreUtils.isNullOrEmpty(batchActions)) { return Mono.empty(); } List<com.azure.search.documents.implementation.models.IndexAction> convertedActions = batchActions.stream() .map(action -> IndexActionConverter.map(action.getAction(), client.serializer)) .collect(Collectors.toList()); return sendBatch(convertedActions, 0, context) .map(response -> { handleResponse(batchActions, response); return response; }).then(Mono.defer(() -> batchAvailableForProcessing() ? createAndProcessBatch(context) : Mono.empty())); } /* * This may result in more than one service call in the case where the index batch is too large and we attempt to * split it. */ private Flux<IndexBatchResponse> sendBatch( List<com.azure.search.documents.implementation.models.IndexAction> actions, int actionsOffset, Context context) { return client.indexDocumentsWithResponse(actions, true, context) .delaySubscription(currentRetryDelay) .flatMapMany(response -> Flux.just( new IndexBatchResponse(response.getStatusCode(), response.getValue().getResults(), actionsOffset, actions.size(), false))) .onErrorResume(IndexBatchException.class, exception -> Flux .just(new IndexBatchResponse(207, exception.getIndexingResults(), actionsOffset, actions.size(), true))) .onErrorResume(HttpResponseException.class, exception -> { /* * If we received an error response where the payload was too large split it into two smaller payloads * and attempt to index again. If the number of index actions was one raise the error as we cannot split * that any further. */ int statusCode = exception.getResponse().getStatusCode(); if (statusCode == HttpURLConnection.HTTP_ENTITY_TOO_LARGE) { int actionCount = actions.size(); if (actionCount == 1) { return Flux.just(new IndexBatchResponse(statusCode, null, actionsOffset, actionCount, true)); } int splitOffset = Math.round(actionCount / 2.0f); return Flux.concat( sendBatch(actions.subList(0, splitOffset), 0, context), sendBatch(actions.subList(splitOffset, actionCount), splitOffset, context) ); } return Flux.just(new IndexBatchResponse(statusCode, null, actionsOffset, actions.size(), true)); }); } private boolean batchAvailableForProcessing() { return actions.size() >= batchActionCount; } private static boolean isSuccess(int statusCode) { return statusCode == 200 || statusCode == 201; } private static boolean isRetryable(int statusCode) { return statusCode == 409 || statusCode == 422 || statusCode == 503; } /* * Helper class which contains the IndexAction and the number of times it has tried to be indexed. */ private static final class TryTrackingIndexAction<T> { private final IndexAction<T> action; private final String key; private int tryCount = 0; private TryTrackingIndexAction(IndexAction<T> action, String key) { this.action = action; this.key = key; } public IndexAction<T> getAction() { return action; } public String getKey() { return key; } public int getTryCount() { return tryCount; } public void incrementTryCount() { tryCount++; } } /* * Helper class which keeps track of the service results, the offset from the initial request set if it was split, * and whether the response is an error status. */ private static final class IndexBatchResponse { private final int statusCode; private final List<IndexingResult> results; private final int offset; private final int count; private final boolean isError; private IndexBatchResponse(int statusCode, List<IndexingResult> results, int offset, int count, boolean isError) { this.statusCode = statusCode; this.results = results; this.offset = offset; this.count = count; this.isError = isError; } public int getStatusCode() { return statusCode; } public List<IndexingResult> getResults() { return results; } public int getOffset() { return offset; } public int getCount() { return count; } public boolean isError() { return isError; } } private Duration calculateRetryDelay(int backoffCount) { long delayWithJitterInNanos = ThreadLocalRandom.current() .nextLong((long) (retryDelay.toNanos() * (1 - JITTER_FACTOR)), (long) (retryDelay.toNanos() * (1 + JITTER_FACTOR))); return Duration.ofNanos(Math.min((1 << backoffCount) * delayWithJitterInNanos, maxRetryDelay.toNanos())); } }
Ordering of the actions may matter, so the order they were submitted is retained here.
private void handleResponse(List<TryTrackingIndexAction<T>> actions, IndexBatchResponse batchResponse) { /* * Batch has been split until it had one document in it and it returned a 413 response. */ if (batchResponse.getStatusCode() == HttpURLConnection.HTTP_ENTITY_TOO_LARGE && batchResponse.getCount() == 1) { IndexAction<T> action = actions.get(batchResponse.getOffset()).getAction(); onActionErrorBiConsumer.accept(action, new RuntimeException("Document is too large to be indexed and won't be tried again.")); return; } List<TryTrackingIndexAction<T>> actionsToRetry = new ArrayList<>(); boolean has503 = batchResponse.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (batchResponse.getResults() == null) { /* * Null results indicates that the entire request failed. Retry all documents. */ int offset = batchResponse.getOffset(); actionsToRetry.addAll(actions.subList(offset, offset + batchResponse.getCount())); } else { /* * We got back a result set, correlate responses to their request document and add retryable actions back * into the queue. */ for (IndexingResult result : batchResponse.getResults()) { String key = result.getKey(); TryTrackingIndexAction<T> action = actions.stream().skip(batchResponse.getOffset()) .filter(a -> key.equals(a.getKey())) .findFirst() .orElse(null); if (action == null) { logger.warning("Unable to correlate result key {} to initial document.", key); continue; } if (isSuccess(result.getStatusCode())) { onActionSucceededConsumer.accept(action.getAction()); } else if (isRetryable(result.getStatusCode())) { has503 |= result.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (action.getTryCount() < maxRetries) { action.incrementTryCount(); actionsToRetry.add(action); } else { onActionErrorBiConsumer.accept(action.getAction(), new RuntimeException("Document has reached retry limit and won't be tried again.")); } } else { onActionErrorBiConsumer.accept(action.getAction(), new RuntimeException(result.getErrorMessage())); } } } if (has503) { currentRetryDelay = calculateRetryDelay(backoffCount.getAndIncrement()); } else { backoffCount.set(0); currentRetryDelay = Duration.ZERO; } if (!CoreUtils.isNullOrEmpty(actionsToRetry)) { synchronized (actionsMutex) { for (int i = actionsToRetry.size() - 1; i >= 0; i--) { this.actions.push(actionsToRetry.get(i)); } } } }
actionsToRetry.addAll(actions.subList(offset, offset + batchResponse.getCount()));
private void handleResponse(List<TryTrackingIndexAction<T>> actions, IndexBatchResponse batchResponse) { /* * Batch has been split until it had one document in it and it returned a 413 response. */ if (batchResponse.getStatusCode() == HttpURLConnection.HTTP_ENTITY_TOO_LARGE && batchResponse.getCount() == 1) { IndexAction<T> action = actions.get(batchResponse.getOffset()).getAction(); onActionErrorBiConsumer.accept(action, new RuntimeException("Document is too large to be indexed and won't be tried again.")); return; } List<TryTrackingIndexAction<T>> actionsToRetry = new ArrayList<>(); boolean has503 = batchResponse.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (batchResponse.getResults() == null) { /* * Null results indicates that the entire request failed. Retry all documents. */ int offset = batchResponse.getOffset(); actionsToRetry.addAll(actions.subList(offset, offset + batchResponse.getCount())); } else { /* * We got back a result set, correlate responses to their request document and add retryable actions back * into the queue. */ for (IndexingResult result : batchResponse.getResults()) { String key = result.getKey(); TryTrackingIndexAction<T> action = actions.stream().skip(batchResponse.getOffset()) .filter(a -> key.equals(a.getKey())) .findFirst() .orElse(null); if (action == null) { logger.warning("Unable to correlate result key {} to initial document.", key); continue; } if (isSuccess(result.getStatusCode())) { onActionSucceededConsumer.accept(action.getAction()); } else if (isRetryable(result.getStatusCode())) { has503 |= result.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (action.getTryCount() < maxRetries) { action.incrementTryCount(); actionsToRetry.add(action); } else { onActionErrorBiConsumer.accept(action.getAction(), new RuntimeException("Document has reached retry limit and won't be tried again.")); } } else { onActionErrorBiConsumer.accept(action.getAction(), new RuntimeException(result.getErrorMessage())); } } } if (has503) { currentRetryDelay = calculateRetryDelay(backoffCount.getAndIncrement()); } else { backoffCount.set(0); currentRetryDelay = Duration.ZERO; } if (!CoreUtils.isNullOrEmpty(actionsToRetry)) { synchronized (actionsMutex) { for (int i = actionsToRetry.size() - 1; i >= 0; i--) { this.actions.push(actionsToRetry.get(i)); } } } }
class SearchIndexingPublisher<T> { private static final double JITTER_FACTOR = 0.05; private final ClientLogger logger = new ClientLogger(SearchIndexingPublisher.class); private final SearchAsyncClient client; private final boolean autoFlush; private final int batchActionCount; private final int maxRetries; private final Duration retryDelay; private final Duration maxRetryDelay; private final Consumer<IndexAction<T>> onActionAddedConsumer; private final Consumer<IndexAction<T>> onActionSentConsumer; private final Consumer<IndexAction<T>> onActionSucceededConsumer; private final BiConsumer<IndexAction<T>, Throwable> onActionErrorBiConsumer; private final Function<T, String> documentKeyRetriever; private final Object actionsMutex = new Object(); private final Deque<TryTrackingIndexAction<T>> actions = new LinkedList<>(); private final Semaphore processingSemaphore = new Semaphore(1); volatile AtomicInteger backoffCount = new AtomicInteger(); volatile Duration currentRetryDelay = Duration.ZERO; SearchIndexingPublisher(SearchAsyncClient client, SearchIndexingBufferedSenderOptions<T> options) { Objects.requireNonNull(options, "'options' cannot be null."); this.documentKeyRetriever = Objects.requireNonNull(options.getDocumentKeyRetriever(), "'options.documentKeyRetriever' cannot be null"); this.client = client; this.autoFlush = options.getAutoFlush(); this.batchActionCount = options.getInitialBatchActionCount(); this.maxRetries = options.getMaxRetries(); this.retryDelay = options.getRetryDelay(); this.maxRetryDelay = (options.getMaxRetryDelay().compareTo(retryDelay) < 0) ? retryDelay : options.getMaxRetryDelay(); this.onActionAddedConsumer = (action) -> { if (options.getOnActionAdded() != null) { options.getOnActionAdded().accept(action); } }; this.onActionSentConsumer = (action) -> { if (options.getOnActionSent() != null) { options.getOnActionSent().accept(action); } }; this.onActionSucceededConsumer = (action) -> { if (options.getOnActionSucceeded() != null) { options.getOnActionSucceeded().accept(action); } }; this.onActionErrorBiConsumer = (action, throwable) -> { if (options.getOnActionError() != null) { options.getOnActionError().accept(action, throwable); } }; } synchronized Collection<IndexAction<?>> getActions() { return actions.stream().map(TryTrackingIndexAction::getAction).collect(Collectors.toList()); } int getBatchActionCount() { return batchActionCount; } synchronized Mono<Void> addActions(Collection<IndexAction<T>> actions, Context context, Runnable rescheduleFlush) { actions.stream() .map(action -> new TryTrackingIndexAction<>(action, documentKeyRetriever.apply(action.getDocument()))) .forEach(action -> { onActionAddedConsumer.accept(action.getAction()); this.actions.add(action); }); if (autoFlush && batchAvailableForProcessing()) { rescheduleFlush.run(); return flush(context, false); } return Mono.empty(); } Mono<Void> flush(Context context, boolean awaitLock) { if (awaitLock) { processingSemaphore.acquireUninterruptibly(); return createAndProcessBatch(context) .doFinally(ignored -> processingSemaphore.release()); } else if (processingSemaphore.tryAcquire()) { return createAndProcessBatch(context) .doFinally(ignored -> processingSemaphore.release()); } else { return Mono.empty(); } } private Mono<Void> createAndProcessBatch(Context context) { final List<TryTrackingIndexAction<T>> batchActions = new ArrayList<>(batchActionCount); synchronized (actionsMutex) { int size = Math.min(batchActionCount, this.actions.size()); for (int i = 0; i < size; i++) { TryTrackingIndexAction<T> action = actions.pop(); onActionSentConsumer.accept(action.getAction()); batchActions.add(action); } } if (CoreUtils.isNullOrEmpty(batchActions)) { return Mono.empty(); } List<com.azure.search.documents.implementation.models.IndexAction> convertedActions = batchActions.stream() .map(action -> IndexActionConverter.map(action.getAction(), client.serializer)) .collect(Collectors.toList()); return sendBatch(convertedActions, 0, context) .map(response -> { handleResponse(batchActions, response); return response; }).then(Mono.defer(() -> batchAvailableForProcessing() ? createAndProcessBatch(context) : Mono.empty())); } /* * This may result in more than one service call in the case where the index batch is too large and we attempt to * split it. */ private Flux<IndexBatchResponse> sendBatch( List<com.azure.search.documents.implementation.models.IndexAction> actions, int actionsOffset, Context context) { return client.indexDocumentsWithResponse(actions, true, context) .delaySubscription(currentRetryDelay) .flatMapMany(response -> Flux.just( new IndexBatchResponse(response.getStatusCode(), response.getValue().getResults(), actionsOffset, actions.size(), false))) .onErrorResume(IndexBatchException.class, exception -> Flux .just(new IndexBatchResponse(207, exception.getIndexingResults(), actionsOffset, actions.size(), true))) .onErrorResume(HttpResponseException.class, exception -> { /* * If we received an error response where the payload was too large split it into two smaller payloads * and attempt to index again. If the number of index actions was one raise the error as we cannot split * that any further. */ int statusCode = exception.getResponse().getStatusCode(); if (exception.getResponse().getStatusCode() == HttpURLConnection.HTTP_ENTITY_TOO_LARGE) { int actionCount = actions.size(); if (actionCount == 1) { return Flux.just(new IndexBatchResponse(statusCode, null, actionsOffset, actionCount, true)); } int splitOffset = Math.round(actionCount / 2.0f); return Flux.concat( sendBatch(actions.subList(0, splitOffset), 0, context), sendBatch(actions.subList(splitOffset, actionCount), splitOffset, context) ); } return Flux.just(new IndexBatchResponse(statusCode, null, actionsOffset, actions.size(), true)); }); } private boolean batchAvailableForProcessing() { return actions.size() >= batchActionCount; } private static boolean isSuccess(int statusCode) { return statusCode == 200 || statusCode == 201; } private static boolean isRetryable(int statusCode) { return statusCode == 409 || statusCode == 422 || statusCode == 503; } /* * Helper class which contains the IndexAction and the number of times it has tried to be indexed. */ private static final class TryTrackingIndexAction<T> { private final IndexAction<T> action; private final String key; private int tryCount = 0; private TryTrackingIndexAction(IndexAction<T> action, String key) { this.action = action; this.key = key; } public IndexAction<T> getAction() { return action; } public String getKey() { return key; } public int getTryCount() { return tryCount; } public void incrementTryCount() { tryCount++; } } /* * Helper class which keeps track of the service results, the offset from the initial request set if it was split, * and whether the response is an error status. */ private static final class IndexBatchResponse { private final int statusCode; private final List<IndexingResult> results; private final int offset; private final int count; private final boolean isError; private IndexBatchResponse(int statusCode, List<IndexingResult> results, int offset, int count, boolean isError) { this.statusCode = statusCode; this.results = results; this.offset = offset; this.count = count; this.isError = isError; } public int getStatusCode() { return statusCode; } public List<IndexingResult> getResults() { return results; } public int getOffset() { return offset; } public int getCount() { return count; } public boolean isError() { return isError; } } private Duration calculateRetryDelay(int backoffCount) { long delayWithJitterInNanos = ThreadLocalRandom.current() .nextLong((long) (retryDelay.toNanos() * (1 - JITTER_FACTOR)), (long) (retryDelay.toNanos() * (1 + JITTER_FACTOR))); return Duration.ofNanos(Math.min((1 << backoffCount) * delayWithJitterInNanos, maxRetryDelay.toNanos())); } }
class SearchIndexingPublisher<T> { private static final double JITTER_FACTOR = 0.05; private final ClientLogger logger = new ClientLogger(SearchIndexingPublisher.class); private final SearchAsyncClient client; private final boolean autoFlush; private final int batchActionCount; private final int maxRetries; private final Duration retryDelay; private final Duration maxRetryDelay; private final Consumer<IndexAction<T>> onActionAddedConsumer; private final Consumer<IndexAction<T>> onActionSentConsumer; private final Consumer<IndexAction<T>> onActionSucceededConsumer; private final BiConsumer<IndexAction<T>, Throwable> onActionErrorBiConsumer; private final Function<T, String> documentKeyRetriever; private final Object actionsMutex = new Object(); private final Deque<TryTrackingIndexAction<T>> actions = new LinkedList<>(); private final Semaphore processingSemaphore = new Semaphore(1); volatile AtomicInteger backoffCount = new AtomicInteger(); volatile Duration currentRetryDelay = Duration.ZERO; SearchIndexingPublisher(SearchAsyncClient client, SearchIndexingBufferedSenderOptions<T> options) { Objects.requireNonNull(options, "'options' cannot be null."); this.documentKeyRetriever = Objects.requireNonNull(options.getDocumentKeyRetriever(), "'options.documentKeyRetriever' cannot be null"); this.client = client; this.autoFlush = options.getAutoFlush(); this.batchActionCount = options.getInitialBatchActionCount(); this.maxRetries = options.getMaxRetries(); this.retryDelay = options.getRetryDelay(); this.maxRetryDelay = (options.getMaxRetryDelay().compareTo(retryDelay) < 0) ? retryDelay : options.getMaxRetryDelay(); this.onActionAddedConsumer = (action) -> { if (options.getOnActionAdded() != null) { options.getOnActionAdded().accept(action); } }; this.onActionSentConsumer = (action) -> { if (options.getOnActionSent() != null) { options.getOnActionSent().accept(action); } }; this.onActionSucceededConsumer = (action) -> { if (options.getOnActionSucceeded() != null) { options.getOnActionSucceeded().accept(action); } }; this.onActionErrorBiConsumer = (action, throwable) -> { if (options.getOnActionError() != null) { options.getOnActionError().accept(action, throwable); } }; } synchronized Collection<IndexAction<?>> getActions() { return actions.stream().map(TryTrackingIndexAction::getAction).collect(Collectors.toList()); } int getBatchActionCount() { return batchActionCount; } synchronized Mono<Void> addActions(Collection<IndexAction<T>> actions, Context context, Runnable rescheduleFlush) { actions.stream() .map(action -> new TryTrackingIndexAction<>(action, documentKeyRetriever.apply(action.getDocument()))) .forEach(action -> { onActionAddedConsumer.accept(action.getAction()); this.actions.add(action); }); if (autoFlush && batchAvailableForProcessing()) { rescheduleFlush.run(); return flush(context, false); } return Mono.empty(); } Mono<Void> flush(Context context, boolean awaitLock) { if (awaitLock) { processingSemaphore.acquireUninterruptibly(); return createAndProcessBatch(context) .doFinally(ignored -> processingSemaphore.release()); } else if (processingSemaphore.tryAcquire()) { return createAndProcessBatch(context) .doFinally(ignored -> processingSemaphore.release()); } else { return Mono.empty(); } } private Mono<Void> createAndProcessBatch(Context context) { final List<TryTrackingIndexAction<T>> batchActions = new ArrayList<>(batchActionCount); synchronized (actionsMutex) { int size = Math.min(batchActionCount, this.actions.size()); for (int i = 0; i < size; i++) { TryTrackingIndexAction<T> action = actions.pop(); onActionSentConsumer.accept(action.getAction()); batchActions.add(action); } } if (CoreUtils.isNullOrEmpty(batchActions)) { return Mono.empty(); } List<com.azure.search.documents.implementation.models.IndexAction> convertedActions = batchActions.stream() .map(action -> IndexActionConverter.map(action.getAction(), client.serializer)) .collect(Collectors.toList()); return sendBatch(convertedActions, 0, context) .map(response -> { handleResponse(batchActions, response); return response; }).then(Mono.defer(() -> batchAvailableForProcessing() ? createAndProcessBatch(context) : Mono.empty())); } /* * This may result in more than one service call in the case where the index batch is too large and we attempt to * split it. */ private Flux<IndexBatchResponse> sendBatch( List<com.azure.search.documents.implementation.models.IndexAction> actions, int actionsOffset, Context context) { return client.indexDocumentsWithResponse(actions, true, context) .delaySubscription(currentRetryDelay) .flatMapMany(response -> Flux.just( new IndexBatchResponse(response.getStatusCode(), response.getValue().getResults(), actionsOffset, actions.size(), false))) .onErrorResume(IndexBatchException.class, exception -> Flux .just(new IndexBatchResponse(207, exception.getIndexingResults(), actionsOffset, actions.size(), true))) .onErrorResume(HttpResponseException.class, exception -> { /* * If we received an error response where the payload was too large split it into two smaller payloads * and attempt to index again. If the number of index actions was one raise the error as we cannot split * that any further. */ int statusCode = exception.getResponse().getStatusCode(); if (statusCode == HttpURLConnection.HTTP_ENTITY_TOO_LARGE) { int actionCount = actions.size(); if (actionCount == 1) { return Flux.just(new IndexBatchResponse(statusCode, null, actionsOffset, actionCount, true)); } int splitOffset = Math.round(actionCount / 2.0f); return Flux.concat( sendBatch(actions.subList(0, splitOffset), 0, context), sendBatch(actions.subList(splitOffset, actionCount), splitOffset, context) ); } return Flux.just(new IndexBatchResponse(statusCode, null, actionsOffset, actions.size(), true)); }); } private boolean batchAvailableForProcessing() { return actions.size() >= batchActionCount; } private static boolean isSuccess(int statusCode) { return statusCode == 200 || statusCode == 201; } private static boolean isRetryable(int statusCode) { return statusCode == 409 || statusCode == 422 || statusCode == 503; } /* * Helper class which contains the IndexAction and the number of times it has tried to be indexed. */ private static final class TryTrackingIndexAction<T> { private final IndexAction<T> action; private final String key; private int tryCount = 0; private TryTrackingIndexAction(IndexAction<T> action, String key) { this.action = action; this.key = key; } public IndexAction<T> getAction() { return action; } public String getKey() { return key; } public int getTryCount() { return tryCount; } public void incrementTryCount() { tryCount++; } } /* * Helper class which keeps track of the service results, the offset from the initial request set if it was split, * and whether the response is an error status. */ private static final class IndexBatchResponse { private final int statusCode; private final List<IndexingResult> results; private final int offset; private final int count; private final boolean isError; private IndexBatchResponse(int statusCode, List<IndexingResult> results, int offset, int count, boolean isError) { this.statusCode = statusCode; this.results = results; this.offset = offset; this.count = count; this.isError = isError; } public int getStatusCode() { return statusCode; } public List<IndexingResult> getResults() { return results; } public int getOffset() { return offset; } public int getCount() { return count; } public boolean isError() { return isError; } } private Duration calculateRetryDelay(int backoffCount) { long delayWithJitterInNanos = ThreadLocalRandom.current() .nextLong((long) (retryDelay.toNanos() * (1 - JITTER_FACTOR)), (long) (retryDelay.toNanos() * (1 + JITTER_FACTOR))); return Duration.ofNanos(Math.min((1 << backoffCount) * delayWithJitterInNanos, maxRetryDelay.toNanos())); } }
Is this still a service bug?
static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", null, null, new PiiEntityCollection(new IterableStream<>(new ArrayList<>()), "I had a wonderful trip to Seattle last week.", null)), new RecognizePiiEntitiesResult("1", null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); }
static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", null, null, new PiiEntityCollection(new IterableStream<>(new ArrayList<>()), "I had a wonderful trip to Seattle last week.", null)), new RecognizePiiEntitiesResult("1", null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was dark and unclean."; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> ANALYZE_TASK_INPUTS = asList(CATEGORIZED_ENTITY_INPUTS.get(0), PII_ENTITY_INPUTS.get(0)); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList1().get(1))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0); PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28); return asList(piiEntity0, piiEntity1); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18); PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18); PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18); PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18); return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 32 ) )), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 36 ) )), null); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( 2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2())))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<HealthcareTaskResult> result = new ArrayList<>(); result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( firstPage, healthcareEntitiesResults1))); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( secondPage, healthcareEntitiesResults2))); } return result; } /** * Helper method that get the expected RecognizeHealthcareEntitiesResultCollection result in page. */ static RecognizeHealthcareEntitiesResultCollection getExpectedBatchHealthcareEntitiesWithPageSize(int sizePerPage, List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults = new RecognizeHealthcareEntitiesResultCollection(healthcareEntitiesResults); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(recognizeHealthcareEntitiesResults, "2020-09-03"); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(recognizeHealthcareEntitiesResults, textDocumentBatchStatistics); return recognizeHealthcareEntitiesResults; } /** * Helper method that get the expected HealthcareTaskResult result. */ static HealthcareTaskResult getExpectedHealthcareTaskResult( RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults) { final HealthcareTaskResult healthcareTaskResult = new HealthcareTaskResult(null, null, null, null, null, null); HealthcareTaskResultPropertiesHelper.setResult(healthcareTaskResult, recognizeHealthcareEntitiesResults); return healthcareTaskResult; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Age")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("Gender")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity2, new ArrayList<>()); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection1 = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection1, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult1 = new RecognizeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, healthcareEntityCollection1); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 25); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions in the anterior lateral leads"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 108); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "wrist pain"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 120); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity5, new ArrayList<>()); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity6, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 137); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity6, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity6, new ArrayList<>()); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult = new RecognizeHealthcareEntitiesResult("1", textDocumentStatistics, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, healthcareEntityCollection); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", null); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle", "week")), null)), new ExtractKeyPhraseResult("1", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the expected AnalyzeTasksResult result. */ static AnalyzeTasksResult getExpectedAnalyzeTasksResult( List<RecognizeEntitiesResultCollection> recognizeEntitiesResults, List<RecognizePiiEntitiesResultCollection> recognizePiiEntitiesResults, List<ExtractKeyPhrasesResultCollection> extractKeyPhraseResults) { final AnalyzeTasksResult analyzeTasksResult = new AnalyzeTasksResult( null, null, null, null, "Test1", null); AnalyzeTasksResultPropertiesHelper.setStatistics(analyzeTasksResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeTasksResultPropertiesHelper.setCompleted(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setFailed(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setInProgress(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setTotal(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionTasks(analyzeTasksResult, recognizeEntitiesResults); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionPiiTasks(analyzeTasksResult, recognizePiiEntitiesResults); AnalyzeTasksResultPropertiesHelper.setKeyPhraseExtractionTasks(analyzeTasksResult, extractKeyPhraseResults); return analyzeTasksResult; } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * Helper method that get a multiple-pages (AnalyzeTasksResult) list. */ static List<AnalyzeTasksResult> getExpectedAnalyzeTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeTasksResult> analyzeTasksResults = new ArrayList<>(); analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage)) )); startIndex += firstPage; analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage)) )); return analyzeTasksResults; } /** * 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(TextAnalyticsServiceVersion.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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.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())); } private TestUtils() { } }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was dark and unclean."; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> ANALYZE_TASK_INPUTS = asList(CATEGORIZED_ENTITY_INPUTS.get(0), PII_ENTITY_INPUTS.get(0)); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList1().get(1))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0); PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28); return asList(piiEntity0, piiEntity1); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18); PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18); PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18); PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18); return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 32 ) )), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 36 ) )), null); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( 2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2())))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<HealthcareTaskResult> result = new ArrayList<>(); result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( firstPage, healthcareEntitiesResults1))); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( secondPage, healthcareEntitiesResults2))); } return result; } /** * Helper method that get the expected RecognizeHealthcareEntitiesResultCollection result in page. */ static RecognizeHealthcareEntitiesResultCollection getExpectedBatchHealthcareEntitiesWithPageSize(int sizePerPage, List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults = new RecognizeHealthcareEntitiesResultCollection(healthcareEntitiesResults); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(recognizeHealthcareEntitiesResults, "2020-09-03"); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(recognizeHealthcareEntitiesResults, textDocumentBatchStatistics); return recognizeHealthcareEntitiesResults; } /** * Helper method that get the expected HealthcareTaskResult result. */ static HealthcareTaskResult getExpectedHealthcareTaskResult( RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults) { final HealthcareTaskResult healthcareTaskResult = new HealthcareTaskResult(null, null, null, null, null, null); HealthcareTaskResultPropertiesHelper.setResult(healthcareTaskResult, recognizeHealthcareEntitiesResults); return healthcareTaskResult; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Age")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("Gender")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity2, new ArrayList<>()); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection1 = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection1, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult1 = new RecognizeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, healthcareEntityCollection1); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 25); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions in the anterior lateral leads"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 108); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "wrist pain"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 120); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity5, new ArrayList<>()); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity6, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 137); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity6, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity6, new ArrayList<>()); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult = new RecognizeHealthcareEntitiesResult("1", textDocumentStatistics, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, healthcareEntityCollection); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", null); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle", "week")), null)), new ExtractKeyPhraseResult("1", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the expected AnalyzeTasksResult result. */ static AnalyzeTasksResult getExpectedAnalyzeTasksResult( List<RecognizeEntitiesResultCollection> recognizeEntitiesResults, List<RecognizePiiEntitiesResultCollection> recognizePiiEntitiesResults, List<ExtractKeyPhrasesResultCollection> extractKeyPhraseResults) { final AnalyzeTasksResult analyzeTasksResult = new AnalyzeTasksResult( null, null, null, null, "Test1", null); AnalyzeTasksResultPropertiesHelper.setStatistics(analyzeTasksResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeTasksResultPropertiesHelper.setCompleted(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setFailed(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setInProgress(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setTotal(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionTasks(analyzeTasksResult, recognizeEntitiesResults); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionPiiTasks(analyzeTasksResult, recognizePiiEntitiesResults); AnalyzeTasksResultPropertiesHelper.setKeyPhraseExtractionTasks(analyzeTasksResult, extractKeyPhraseResults); return analyzeTasksResult; } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * Helper method that get a multiple-pages (AnalyzeTasksResult) list. */ static List<AnalyzeTasksResult> getExpectedAnalyzeTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeTasksResult> analyzeTasksResults = new ArrayList<>(); analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage)) )); startIndex += firstPage; analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage)) )); return analyzeTasksResults; } /** * 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(TextAnalyticsServiceVersion.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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.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())); } private TestUtils() { } }
Consider adding service bugs to issues for better follow up.
static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", null, null, new PiiEntityCollection(new IterableStream<>(new ArrayList<>()), "I had a wonderful trip to Seattle last week.", null)), new RecognizePiiEntitiesResult("1", null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); }
static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", null, null, new PiiEntityCollection(new IterableStream<>(new ArrayList<>()), "I had a wonderful trip to Seattle last week.", null)), new RecognizePiiEntitiesResult("1", null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was dark and unclean."; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> ANALYZE_TASK_INPUTS = asList(CATEGORIZED_ENTITY_INPUTS.get(0), PII_ENTITY_INPUTS.get(0)); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList1().get(1))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0); PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28); return asList(piiEntity0, piiEntity1); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18); PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18); PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18); PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18); return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 32 ) )), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 36 ) )), null); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( 2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2())))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<HealthcareTaskResult> result = new ArrayList<>(); result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( firstPage, healthcareEntitiesResults1))); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( secondPage, healthcareEntitiesResults2))); } return result; } /** * Helper method that get the expected RecognizeHealthcareEntitiesResultCollection result in page. */ static RecognizeHealthcareEntitiesResultCollection getExpectedBatchHealthcareEntitiesWithPageSize(int sizePerPage, List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults = new RecognizeHealthcareEntitiesResultCollection(healthcareEntitiesResults); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(recognizeHealthcareEntitiesResults, "2020-09-03"); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(recognizeHealthcareEntitiesResults, textDocumentBatchStatistics); return recognizeHealthcareEntitiesResults; } /** * Helper method that get the expected HealthcareTaskResult result. */ static HealthcareTaskResult getExpectedHealthcareTaskResult( RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults) { final HealthcareTaskResult healthcareTaskResult = new HealthcareTaskResult(null, null, null, null, null, null); HealthcareTaskResultPropertiesHelper.setResult(healthcareTaskResult, recognizeHealthcareEntitiesResults); return healthcareTaskResult; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Age")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("Gender")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity2, new ArrayList<>()); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection1 = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection1, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult1 = new RecognizeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, healthcareEntityCollection1); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 25); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions in the anterior lateral leads"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 108); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "wrist pain"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 120); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity5, new ArrayList<>()); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity6, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 137); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity6, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity6, new ArrayList<>()); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult = new RecognizeHealthcareEntitiesResult("1", textDocumentStatistics, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, healthcareEntityCollection); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", null); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle", "week")), null)), new ExtractKeyPhraseResult("1", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the expected AnalyzeTasksResult result. */ static AnalyzeTasksResult getExpectedAnalyzeTasksResult( List<RecognizeEntitiesResultCollection> recognizeEntitiesResults, List<RecognizePiiEntitiesResultCollection> recognizePiiEntitiesResults, List<ExtractKeyPhrasesResultCollection> extractKeyPhraseResults) { final AnalyzeTasksResult analyzeTasksResult = new AnalyzeTasksResult( null, null, null, null, "Test1", null); AnalyzeTasksResultPropertiesHelper.setStatistics(analyzeTasksResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeTasksResultPropertiesHelper.setCompleted(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setFailed(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setInProgress(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setTotal(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionTasks(analyzeTasksResult, recognizeEntitiesResults); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionPiiTasks(analyzeTasksResult, recognizePiiEntitiesResults); AnalyzeTasksResultPropertiesHelper.setKeyPhraseExtractionTasks(analyzeTasksResult, extractKeyPhraseResults); return analyzeTasksResult; } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * Helper method that get a multiple-pages (AnalyzeTasksResult) list. */ static List<AnalyzeTasksResult> getExpectedAnalyzeTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeTasksResult> analyzeTasksResults = new ArrayList<>(); analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage)) )); startIndex += firstPage; analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage)) )); return analyzeTasksResults; } /** * 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(TextAnalyticsServiceVersion.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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.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())); } private TestUtils() { } }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was dark and unclean."; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> ANALYZE_TASK_INPUTS = asList(CATEGORIZED_ENTITY_INPUTS.get(0), PII_ENTITY_INPUTS.get(0)); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList1().get(1))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0); PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28); return asList(piiEntity0, piiEntity1); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18); PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18); PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18); PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18); return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 32 ) )), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 36 ) )), null); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( 2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2())))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<HealthcareTaskResult> result = new ArrayList<>(); result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( firstPage, healthcareEntitiesResults1))); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( secondPage, healthcareEntitiesResults2))); } return result; } /** * Helper method that get the expected RecognizeHealthcareEntitiesResultCollection result in page. */ static RecognizeHealthcareEntitiesResultCollection getExpectedBatchHealthcareEntitiesWithPageSize(int sizePerPage, List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults = new RecognizeHealthcareEntitiesResultCollection(healthcareEntitiesResults); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(recognizeHealthcareEntitiesResults, "2020-09-03"); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(recognizeHealthcareEntitiesResults, textDocumentBatchStatistics); return recognizeHealthcareEntitiesResults; } /** * Helper method that get the expected HealthcareTaskResult result. */ static HealthcareTaskResult getExpectedHealthcareTaskResult( RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults) { final HealthcareTaskResult healthcareTaskResult = new HealthcareTaskResult(null, null, null, null, null, null); HealthcareTaskResultPropertiesHelper.setResult(healthcareTaskResult, recognizeHealthcareEntitiesResults); return healthcareTaskResult; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Age")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("Gender")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity2, new ArrayList<>()); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection1 = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection1, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult1 = new RecognizeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, healthcareEntityCollection1); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 25); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions in the anterior lateral leads"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 108); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "wrist pain"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 120); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity5, new ArrayList<>()); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity6, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 137); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity6, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity6, new ArrayList<>()); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult = new RecognizeHealthcareEntitiesResult("1", textDocumentStatistics, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, healthcareEntityCollection); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", null); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle", "week")), null)), new ExtractKeyPhraseResult("1", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the expected AnalyzeTasksResult result. */ static AnalyzeTasksResult getExpectedAnalyzeTasksResult( List<RecognizeEntitiesResultCollection> recognizeEntitiesResults, List<RecognizePiiEntitiesResultCollection> recognizePiiEntitiesResults, List<ExtractKeyPhrasesResultCollection> extractKeyPhraseResults) { final AnalyzeTasksResult analyzeTasksResult = new AnalyzeTasksResult( null, null, null, null, "Test1", null); AnalyzeTasksResultPropertiesHelper.setStatistics(analyzeTasksResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeTasksResultPropertiesHelper.setCompleted(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setFailed(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setInProgress(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setTotal(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionTasks(analyzeTasksResult, recognizeEntitiesResults); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionPiiTasks(analyzeTasksResult, recognizePiiEntitiesResults); AnalyzeTasksResultPropertiesHelper.setKeyPhraseExtractionTasks(analyzeTasksResult, extractKeyPhraseResults); return analyzeTasksResult; } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * Helper method that get a multiple-pages (AnalyzeTasksResult) list. */ static List<AnalyzeTasksResult> getExpectedAnalyzeTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeTasksResult> analyzeTasksResults = new ArrayList<>(); analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage)) )); startIndex += firstPage; analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage)) )); return analyzeTasksResults; } /** * 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(TextAnalyticsServiceVersion.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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.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())); } private TestUtils() { } }
Yes, it is still a bugs. https://github.com/Azure/azure-sdk-for-java/issues/17564
static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", null, null, new PiiEntityCollection(new IterableStream<>(new ArrayList<>()), "I had a wonderful trip to Seattle last week.", null)), new RecognizePiiEntitiesResult("1", null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); }
static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", null, null, new PiiEntityCollection(new IterableStream<>(new ArrayList<>()), "I had a wonderful trip to Seattle last week.", null)), new RecognizePiiEntitiesResult("1", null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was dark and unclean."; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> ANALYZE_TASK_INPUTS = asList(CATEGORIZED_ENTITY_INPUTS.get(0), PII_ENTITY_INPUTS.get(0)); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList1().get(1))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0); PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28); return asList(piiEntity0, piiEntity1); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18); PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18); PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18); PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18); return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 32 ) )), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 36 ) )), null); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( 2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2())))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<HealthcareTaskResult> result = new ArrayList<>(); result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( firstPage, healthcareEntitiesResults1))); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( secondPage, healthcareEntitiesResults2))); } return result; } /** * Helper method that get the expected RecognizeHealthcareEntitiesResultCollection result in page. */ static RecognizeHealthcareEntitiesResultCollection getExpectedBatchHealthcareEntitiesWithPageSize(int sizePerPage, List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults = new RecognizeHealthcareEntitiesResultCollection(healthcareEntitiesResults); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(recognizeHealthcareEntitiesResults, "2020-09-03"); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(recognizeHealthcareEntitiesResults, textDocumentBatchStatistics); return recognizeHealthcareEntitiesResults; } /** * Helper method that get the expected HealthcareTaskResult result. */ static HealthcareTaskResult getExpectedHealthcareTaskResult( RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults) { final HealthcareTaskResult healthcareTaskResult = new HealthcareTaskResult(null, null, null, null, null, null); HealthcareTaskResultPropertiesHelper.setResult(healthcareTaskResult, recognizeHealthcareEntitiesResults); return healthcareTaskResult; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Age")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("Gender")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity2, new ArrayList<>()); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection1 = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection1, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult1 = new RecognizeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, healthcareEntityCollection1); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 25); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions in the anterior lateral leads"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 108); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "wrist pain"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 120); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity5, new ArrayList<>()); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity6, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 137); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity6, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity6, new ArrayList<>()); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult = new RecognizeHealthcareEntitiesResult("1", textDocumentStatistics, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, healthcareEntityCollection); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", null); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle", "week")), null)), new ExtractKeyPhraseResult("1", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the expected AnalyzeTasksResult result. */ static AnalyzeTasksResult getExpectedAnalyzeTasksResult( List<RecognizeEntitiesResultCollection> recognizeEntitiesResults, List<RecognizePiiEntitiesResultCollection> recognizePiiEntitiesResults, List<ExtractKeyPhrasesResultCollection> extractKeyPhraseResults) { final AnalyzeTasksResult analyzeTasksResult = new AnalyzeTasksResult( null, null, null, null, "Test1", null); AnalyzeTasksResultPropertiesHelper.setStatistics(analyzeTasksResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeTasksResultPropertiesHelper.setCompleted(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setFailed(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setInProgress(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setTotal(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionTasks(analyzeTasksResult, recognizeEntitiesResults); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionPiiTasks(analyzeTasksResult, recognizePiiEntitiesResults); AnalyzeTasksResultPropertiesHelper.setKeyPhraseExtractionTasks(analyzeTasksResult, extractKeyPhraseResults); return analyzeTasksResult; } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * Helper method that get a multiple-pages (AnalyzeTasksResult) list. */ static List<AnalyzeTasksResult> getExpectedAnalyzeTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeTasksResult> analyzeTasksResults = new ArrayList<>(); analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage)) )); startIndex += firstPage; analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage)) )); return analyzeTasksResults; } /** * 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(TextAnalyticsServiceVersion.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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.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())); } private TestUtils() { } }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was dark and unclean."; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> ANALYZE_TASK_INPUTS = asList(CATEGORIZED_ENTITY_INPUTS.get(0), PII_ENTITY_INPUTS.get(0)); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList1().get(1))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0); PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28); return asList(piiEntity0, piiEntity1); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18); PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18); PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18); PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18); return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 32 ) )), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList( new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 0 ), new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion( new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new IterableStream<>(asList( new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)), new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)) ))))), 36 ) )), null); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( 2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2())))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<HealthcareTaskResult> getExpectedHealthcareTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<HealthcareTaskResult> result = new ArrayList<>(); result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( firstPage, healthcareEntitiesResults1))); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(getExpectedBatchHealthcareEntitiesWithPageSize( secondPage, healthcareEntitiesResults2))); } return result; } /** * Helper method that get the expected RecognizeHealthcareEntitiesResultCollection result in page. */ static RecognizeHealthcareEntitiesResultCollection getExpectedBatchHealthcareEntitiesWithPageSize(int sizePerPage, List<RecognizeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults = new RecognizeHealthcareEntitiesResultCollection(healthcareEntitiesResults); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(recognizeHealthcareEntitiesResults, "2020-09-03"); RecognizeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(recognizeHealthcareEntitiesResults, textDocumentBatchStatistics); return recognizeHealthcareEntitiesResults; } /** * Helper method that get the expected HealthcareTaskResult result. */ static HealthcareTaskResult getExpectedHealthcareTaskResult( RecognizeHealthcareEntitiesResultCollection recognizeHealthcareEntitiesResults) { final HealthcareTaskResult healthcareTaskResult = new HealthcareTaskResult(null, null, null, null, null, null); HealthcareTaskResultPropertiesHelper.setResult(healthcareTaskResult, recognizeHealthcareEntitiesResults); return healthcareTaskResult; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Age")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("Gender")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity2, new ArrayList<>()); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection1 = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection1, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult1 = new RecognizeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, healthcareEntityCollection1); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static RecognizeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, EntityCategory.fromString("Time")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity1, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 25); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity1, false); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, EntityCategory.fromString("ConditionQualifier")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity2, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity2, false); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions in the anterior lateral leads"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity3, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity3, false); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity4, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 108); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity4, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity4, new ArrayList<>()); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "wrist pain"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity5, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 120); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity5, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity5, new ArrayList<>()); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, EntityCategory.fromString("SymptomOrSign")); HealthcareEntityPropertiesHelper.setSubcategory(healthcareEntity6, null); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 137); HealthcareEntityPropertiesHelper.setNegated(healthcareEntity6, false); HealthcareEntityPropertiesHelper.setHealthcareEntityLinks(healthcareEntity6, new ArrayList<>()); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, "TimeOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation1, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation1, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation1, " final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, "QualifierOfCondition"); HealthcareEntityRelationPropertiesHelper.setBidirectional(healthcareEntityRelation2, false); HealthcareEntityRelationPropertiesHelper.setSourceLink(healthcareEntityRelation2, " HealthcareEntityRelationPropertiesHelper.setTargetLink(healthcareEntityRelation2, " final HealthcareEntityCollection healthcareEntityCollection = new HealthcareEntityCollection( new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6))); HealthcareEntityCollectionPropertiesHelper.setEntityRelations(healthcareEntityCollection, new IterableStream<>(asList(healthcareEntityRelation1, healthcareEntityRelation2))); final RecognizeHealthcareEntitiesResult healthcareEntitiesResult = new RecognizeHealthcareEntitiesResult("1", textDocumentStatistics, null); RecognizeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, healthcareEntityCollection); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", null); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle", "week")), null)), new ExtractKeyPhraseResult("1", null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the expected AnalyzeTasksResult result. */ static AnalyzeTasksResult getExpectedAnalyzeTasksResult( List<RecognizeEntitiesResultCollection> recognizeEntitiesResults, List<RecognizePiiEntitiesResultCollection> recognizePiiEntitiesResults, List<ExtractKeyPhrasesResultCollection> extractKeyPhraseResults) { final AnalyzeTasksResult analyzeTasksResult = new AnalyzeTasksResult( null, null, null, null, "Test1", null); AnalyzeTasksResultPropertiesHelper.setStatistics(analyzeTasksResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeTasksResultPropertiesHelper.setCompleted(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setFailed(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setInProgress(analyzeTasksResult, 0); AnalyzeTasksResultPropertiesHelper.setTotal(analyzeTasksResult, 3); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionTasks(analyzeTasksResult, recognizeEntitiesResults); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionPiiTasks(analyzeTasksResult, recognizePiiEntitiesResults); AnalyzeTasksResultPropertiesHelper.setKeyPhraseExtractionTasks(analyzeTasksResult, extractKeyPhraseResults); return analyzeTasksResult; } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* employee with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome API's")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * Helper method that get a multiple-pages (AnalyzeTasksResult) list. */ static List<AnalyzeTasksResult> getExpectedAnalyzeTaskResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeTasksResult> analyzeTasksResults = new ArrayList<>(); analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage)) )); startIndex += firstPage; analyzeTasksResults.add(getExpectedAnalyzeTasksResult( asList(getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage)), asList(getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage)) )); return analyzeTasksResults; } /** * 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(TextAnalyticsServiceVersion.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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.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())); } private TestUtils() { } }
Can this check happen before the function call, one less code jump?
private JobManifestTasks getJobManifestTasks(AnalyzeTasksOptions options) { if (options == null) { return null; } return new JobManifestTasks() .setEntityRecognitionTasks(options.getEntitiesRecognitionTasks() == null ? null : options.getEntitiesRecognitionTasks().stream().map( entitiesTask -> { if (entitiesTask == null) { return null; } final EntitiesTask entitiesTaskImpl = new EntitiesTask(); final com.azure.ai.textanalytics.models.EntitiesTaskParameters entitiesTaskParameters = entitiesTask.getParameters(); if (entitiesTaskParameters == null) { return entitiesTaskImpl; } entitiesTaskImpl.setParameters( new EntitiesTaskParameters().setModelVersion(entitiesTaskParameters.getModelVersion())); return entitiesTaskImpl; }).collect(Collectors.toList())) .setEntityRecognitionPiiTasks(options.getPiiEntitiesRecognitionTasks() == null ? null : options.getPiiEntitiesRecognitionTasks().stream().map( piiEntitiesTask -> { if (piiEntitiesTask == null) { return null; } final PiiTask piiTaskImpl = new PiiTask(); final com.azure.ai.textanalytics.models.PiiTaskParameters piiTaskParameters = piiEntitiesTask.getParameters(); if (piiTaskParameters == null) { return piiTaskImpl; } piiTaskImpl.setParameters( new PiiTaskParameters() .setModelVersion(piiTaskParameters.getModelVersion()) .setDomain(PiiTaskParametersDomain.fromString( piiTaskParameters.getDomain() == null ? null : piiTaskParameters.getDomain().toString()))); return piiTaskImpl; }).collect(Collectors.toList())) .setKeyPhraseExtractionTasks(options.getKeyPhrasesExtractionTasks() == null ? null : options.getKeyPhrasesExtractionTasks().stream().map( keyPhrasesTask -> { if (keyPhrasesTask == null) { return null; } final com.azure.ai.textanalytics.models.KeyPhrasesTaskParameters keyPhrasesTaskParameters = keyPhrasesTask.getParameters(); final KeyPhrasesTask keyPhrasesTaskImpl = new KeyPhrasesTask(); if (keyPhrasesTaskParameters == null) { return keyPhrasesTaskImpl; } keyPhrasesTaskImpl.setParameters( new KeyPhrasesTaskParameters().setModelVersion(keyPhrasesTaskParameters.getModelVersion())); return keyPhrasesTaskImpl; }).collect(Collectors.toList())); }
}
private JobManifestTasks getJobManifestTasks(AnalyzeTasksOptions options) { return new JobManifestTasks() .setEntityRecognitionTasks(options.getEntitiesRecognitionTasks() == null ? null : options.getEntitiesRecognitionTasks().stream().map( entitiesTask -> { if (entitiesTask == null) { return null; } final EntitiesTask entitiesTaskImpl = new EntitiesTask(); final com.azure.ai.textanalytics.models.EntitiesTaskParameters entitiesTaskParameters = entitiesTask.getParameters(); if (entitiesTaskParameters == null) { return entitiesTaskImpl; } entitiesTaskImpl.setParameters( new EntitiesTaskParameters().setModelVersion(entitiesTaskParameters.getModelVersion())); return entitiesTaskImpl; }).collect(Collectors.toList())) .setEntityRecognitionPiiTasks(options.getPiiEntitiesRecognitionTasks() == null ? null : options.getPiiEntitiesRecognitionTasks().stream().map( piiEntitiesTask -> { if (piiEntitiesTask == null) { return null; } final PiiTask piiTaskImpl = new PiiTask(); final com.azure.ai.textanalytics.models.PiiTaskParameters piiTaskParameters = piiEntitiesTask.getParameters(); if (piiTaskParameters == null) { return piiTaskImpl; } piiTaskImpl.setParameters( new PiiTaskParameters() .setModelVersion(piiTaskParameters.getModelVersion()) .setDomain(PiiTaskParametersDomain.fromString( piiTaskParameters.getDomain() == null ? null : piiTaskParameters.getDomain().toString()))); return piiTaskImpl; }).collect(Collectors.toList())) .setKeyPhraseExtractionTasks(options.getKeyPhrasesExtractionTasks() == null ? null : options.getKeyPhrasesExtractionTasks().stream().map( keyPhrasesTask -> { if (keyPhrasesTask == null) { return null; } final com.azure.ai.textanalytics.models.KeyPhrasesTaskParameters keyPhrasesTaskParameters = keyPhrasesTask.getParameters(); final KeyPhrasesTask keyPhrasesTaskImpl = new KeyPhrasesTask(); if (keyPhrasesTaskParameters == null) { return keyPhrasesTaskImpl; } keyPhrasesTaskImpl.setParameters( new KeyPhrasesTaskParameters().setModelVersion(keyPhrasesTaskParameters.getModelVersion())); return keyPhrasesTaskImpl; }).collect(Collectors.toList())); }
class AnalyzeTasksAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeTasksAsyncClient.class); private final TextAnalyticsClientImpl service; AnalyzeTasksAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<TextAnalyticsOperationResult, PagedFlux<AnalyzeTasksResult>> beginAnalyze( Iterable<TextDocumentInput> documents, AnalyzeTasksOptions options, Context context) { try { inputDocumentsValidation(documents); AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(options)); Duration pollingInterval = DEFAULT_POLL_INTERVAL; if (options != null) { analyzeBatchInput.setDisplayName(options.getDisplayName()); pollingInterval = options.getPollInterval(); } final Boolean finalIncludeStatistics = options == null ? null : options.isIncludeStatistics(); final Integer finalTop = options == null ? null : options.getTop(); final Integer finalSkip = options == null ? null : options.getSkip(); return new PollerFlux<>( pollingInterval, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE)) .map(analyzeResponse -> { final TextAnalyticsOperationResult textAnalyticsOperationResult = new TextAnalyticsOperationResult(); TextAnalyticsOperationResultPropertiesHelper.setResultId(textAnalyticsOperationResult, parseModelId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(resultID -> service.analyzeStatusWithResponseAsync(resultID, finalIncludeStatistics, finalTop, finalSkip, context)), (activationResponse, pollingContext) -> null, fetchingOperation(resultId -> Mono.just(getAnalyzeOperationFluxPage( resultId, finalTop, finalSkip, finalIncludeStatistics, context))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<TextAnalyticsOperationResult, PagedIterable<AnalyzeTasksResult>> beginAnalyzeIterable( Iterable<TextDocumentInput> documents, AnalyzeTasksOptions options, Context context) { try { inputDocumentsValidation(documents); AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(options)); Duration pollingInterval = DEFAULT_POLL_INTERVAL; if (options != null) { analyzeBatchInput.setDisplayName(options.getDisplayName()); pollingInterval = options.getPollInterval(); } final Boolean finalIncludeStatistics = options == null ? null : options.isIncludeStatistics(); final Integer finalTop = options == null ? null : options.getTop(); final Integer finalSkip = options == null ? null : options.getSkip(); return new PollerFlux<>( pollingInterval, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE)) .map(analyzeResponse -> { final TextAnalyticsOperationResult textAnalyticsOperationResult = new TextAnalyticsOperationResult(); TextAnalyticsOperationResultPropertiesHelper.setResultId(textAnalyticsOperationResult, parseModelId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(resultID -> service.analyzeStatusWithResponseAsync(resultID, options == null ? null : options.isIncludeStatistics(), null, null, context)), (activationResponse, pollingContext) -> null, fetchingOperationIterable(resultId -> Mono.just(new PagedIterable<>(getAnalyzeOperationFluxPage( resultId, finalTop, finalSkip, finalIncludeStatistics, context)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private Function<PollingContext<TextAnalyticsOperationResult>, Mono<TextAnalyticsOperationResult>> activationOperation(Mono<TextAnalyticsOperationResult> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<TextAnalyticsOperationResult>, Mono<PollResponse<TextAnalyticsOperationResult>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<TextAnalyticsOperationResult> operationResultPollResponse = pollingContext.getLatestResponse(); final String resultID = operationResultPollResponse.getValue().getResultId(); return pollingFunction.apply(resultID) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<TextAnalyticsOperationResult>, Mono<PagedFlux<AnalyzeTasksResult>>> fetchingOperation(Function<String, Mono<PagedFlux<AnalyzeTasksResult>>> fetchingFunction) { return pollingContext -> { try { final String resultUUID = pollingContext.getLatestResponse().getValue().getResultId(); return fetchingFunction.apply(resultUUID); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<TextAnalyticsOperationResult>, Mono<PagedIterable<AnalyzeTasksResult>>> fetchingOperationIterable(Function<String, Mono<PagedIterable<AnalyzeTasksResult>>> fetchingFunction) { return pollingContext -> { try { final String resultUUID = pollingContext.getLatestResponse().getValue().getResultId(); return fetchingFunction.apply(resultUUID); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } PagedFlux<AnalyzeTasksResult> getAnalyzeOperationFluxPage(String analyzeTasksId, Integer top, Integer skip, Boolean showStats, Context context) { return new PagedFlux<>( () -> getPage(null, analyzeTasksId, top, skip, showStats, context), continuationToken -> getPage(continuationToken, analyzeTasksId, top, skip, showStats, context)); } Mono<PagedResponse<AnalyzeTasksResult>> getPage(String continuationToken, String analyzeTasksId, Integer top, Integer skip, Boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Integer> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = continuationTokenMap.getOrDefault("$skip", null); return service.analyzeStatusWithResponseAsync(analyzeTasksId, showStats, topValue, skipValue, context) .map(this::toAnalyzeTasksPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } else { return service.analyzeStatusWithResponseAsync(analyzeTasksId, showStats, top, skip, context) .map(this::toAnalyzeTasksPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } } private PagedResponse<AnalyzeTasksResult> toAnalyzeTasksPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeTasksResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeTasks(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeTasksResult toAnalyzeTasks(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); List<RecognizeEntitiesResultCollection> entitiesResultCollections = null; List<RecognizePiiEntitiesResultCollection> piiEntitiesResultCollections = null; List<ExtractKeyPhrasesResultCollection> keyPhrasesResultCollections = null; if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { entitiesResultCollections = entityRecognitionTasksItems.stream() .map(taskItem -> toRecognizeEntitiesResultCollectionResponse(taskItem.getResults())) .collect(Collectors.toList()); } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { piiEntitiesResultCollections = piiTasksItems.stream() .map(taskItem -> toRecognizePiiEntitiesResultCollection(taskItem.getResults())) .collect(Collectors.toList()); } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { keyPhrasesResultCollections = keyPhraseExtractionTasks.stream() .map(taskItem -> toExtractKeyPhrasesResultCollection(taskItem.getResults())) .collect(Collectors.toList()); } final AnalyzeTasksResult analyzeTasksResult = new AnalyzeTasksResult( analyzeJobState.getJobId(), analyzeJobState.getCreatedDateTime(), analyzeJobState.getLastUpdateDateTime(), toJobState(analyzeJobState.getStatus()), analyzeJobState.getDisplayName(), analyzeJobState.getExpirationDateTime()); AnalyzeTasksResultPropertiesHelper.setErrors(analyzeTasksResult, analyzeJobState.getErrors().stream().map(Utility::toTextAnalyticsError).collect(Collectors.toList())); AnalyzeTasksResultPropertiesHelper.setStatistics(analyzeTasksResult, analyzeJobState.getStatistics() == null ? null : toBatchStatistics(analyzeJobState.getStatistics())); AnalyzeTasksResultPropertiesHelper.setCompleted(analyzeTasksResult, tasksStateTasks.getCompleted()); AnalyzeTasksResultPropertiesHelper.setFailed(analyzeTasksResult, tasksStateTasks.getFailed()); AnalyzeTasksResultPropertiesHelper.setInProgress(analyzeTasksResult, tasksStateTasks.getInProgress()); AnalyzeTasksResultPropertiesHelper.setTotal(analyzeTasksResult, tasksStateTasks.getTotal()); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionTasks(analyzeTasksResult, entitiesResultCollections); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionPiiTasks(analyzeTasksResult, piiEntitiesResultCollections); AnalyzeTasksResultPropertiesHelper.setKeyPhraseExtractionTasks(analyzeTasksResult, keyPhrasesResultCollections); return analyzeTasksResult; } private Mono<PollResponse<TextAnalyticsOperationResult>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<TextAnalyticsOperationResult> operationResultPollResponse) { LongRunningOperationStatus status; switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case CANCELLING: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case FAILED: final TextAnalyticsException exception = new TextAnalyticsException("Analyze operation failed", null, null); TextAnalyticsExceptionPropertiesHelper.setErrorInformationList(exception, analyzeJobStateResponse.getValue().getErrors().stream() .map(error -> { final TextAnalyticsErrorInformation textAnalyticsErrorInformation = new TextAnalyticsErrorInformation(); TextAnalyticsErrorInformationPropertiesHelper.setErrorCode(textAnalyticsErrorInformation, TextAnalyticsErrorCode.fromString(error.getCode().toString())); TextAnalyticsErrorInformationPropertiesHelper.setMessage(textAnalyticsErrorInformation, error.getMessage()); return textAnalyticsErrorInformation; }).collect(Collectors.toList())); throw logger.logExceptionAsError(exception); default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } }
class AnalyzeTasksAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeTasksAsyncClient.class); private final TextAnalyticsClientImpl service; AnalyzeTasksAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<TextAnalyticsOperationResult, PagedFlux<AnalyzeTasksResult>> beginAnalyzeTasks( Iterable<TextDocumentInput> documents, AnalyzeTasksOptions options, Context context) { try { inputDocumentsValidation(documents); if (options == null) { options = new AnalyzeTasksOptions(); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(options)); analyzeBatchInput.setDisplayName(options.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); final Integer finalTop = options.getTop(); final Integer finalSkip = options.getSkip(); return new PollerFlux<>( options.getPollInterval(), activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE)) .map(analyzeResponse -> { final TextAnalyticsOperationResult textAnalyticsOperationResult = new TextAnalyticsOperationResult(); TextAnalyticsOperationResultPropertiesHelper.setResultId(textAnalyticsOperationResult, parseModelId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(resultID -> service.analyzeStatusWithResponseAsync(resultID, finalIncludeStatistics, finalTop, finalSkip, context)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(resultId -> Mono.just(getAnalyzeOperationFluxPage( resultId, finalTop, finalSkip, finalIncludeStatistics, context))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<TextAnalyticsOperationResult, PagedIterable<AnalyzeTasksResult>> beginAnalyzeTasksIterable( Iterable<TextDocumentInput> documents, AnalyzeTasksOptions options, Context context) { try { inputDocumentsValidation(documents); if (options == null) { options = new AnalyzeTasksOptions(); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(options)); analyzeBatchInput.setDisplayName(options.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); final Integer finalTop = options.getTop(); final Integer finalSkip = options.getSkip(); return new PollerFlux<>( options.getPollInterval(), activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE)) .map(analyzeResponse -> { final TextAnalyticsOperationResult textAnalyticsOperationResult = new TextAnalyticsOperationResult(); TextAnalyticsOperationResultPropertiesHelper.setResultId(textAnalyticsOperationResult, parseModelId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(resultID -> service.analyzeStatusWithResponseAsync(resultID, finalIncludeStatistics, finalTop, finalSkip, context)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable(resultId -> Mono.just(new PagedIterable<>(getAnalyzeOperationFluxPage( resultId, finalTop, finalSkip, finalIncludeStatistics, context)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private Function<PollingContext<TextAnalyticsOperationResult>, Mono<TextAnalyticsOperationResult>> activationOperation(Mono<TextAnalyticsOperationResult> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<TextAnalyticsOperationResult>, Mono<PollResponse<TextAnalyticsOperationResult>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<TextAnalyticsOperationResult> operationResultPollResponse = pollingContext.getLatestResponse(); final String resultID = operationResultPollResponse.getValue().getResultId(); return pollingFunction.apply(resultID) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<TextAnalyticsOperationResult>, Mono<PagedFlux<AnalyzeTasksResult>>> fetchingOperation(Function<String, Mono<PagedFlux<AnalyzeTasksResult>>> fetchingFunction) { return pollingContext -> { try { final String resultUUID = pollingContext.getLatestResponse().getValue().getResultId(); return fetchingFunction.apply(resultUUID); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<TextAnalyticsOperationResult>, Mono<PagedIterable<AnalyzeTasksResult>>> fetchingOperationIterable(Function<String, Mono<PagedIterable<AnalyzeTasksResult>>> fetchingFunction) { return pollingContext -> { try { final String resultUUID = pollingContext.getLatestResponse().getValue().getResultId(); return fetchingFunction.apply(resultUUID); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } PagedFlux<AnalyzeTasksResult> getAnalyzeOperationFluxPage(String analyzeTasksId, Integer top, Integer skip, boolean showStats, Context context) { return new PagedFlux<>( () -> getPage(null, analyzeTasksId, top, skip, showStats, context), continuationToken -> getPage(continuationToken, analyzeTasksId, top, skip, showStats, context)); } Mono<PagedResponse<AnalyzeTasksResult>> getPage(String continuationToken, String analyzeTasksId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Integer> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = continuationTokenMap.getOrDefault("$skip", null); return service.analyzeStatusWithResponseAsync(analyzeTasksId, showStats, topValue, skipValue, context) .map(this::toAnalyzeTasksPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } else { return service.analyzeStatusWithResponseAsync(analyzeTasksId, showStats, top, skip, context) .map(this::toAnalyzeTasksPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist); } } private PagedResponse<AnalyzeTasksResult> toAnalyzeTasksPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeTasksResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeTasks(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeTasksResult toAnalyzeTasks(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); List<RecognizeEntitiesResultCollection> entitiesResultCollections = null; List<RecognizePiiEntitiesResultCollection> piiEntitiesResultCollections = null; List<ExtractKeyPhrasesResultCollection> keyPhrasesResultCollections = null; if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { entitiesResultCollections = entityRecognitionTasksItems.stream() .map(taskItem -> toRecognizeEntitiesResultCollectionResponse(taskItem.getResults())) .collect(Collectors.toList()); } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { piiEntitiesResultCollections = piiTasksItems.stream() .map(taskItem -> toRecognizePiiEntitiesResultCollection(taskItem.getResults())) .collect(Collectors.toList()); } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { keyPhrasesResultCollections = keyPhraseExtractionTasks.stream() .map(taskItem -> toExtractKeyPhrasesResultCollection(taskItem.getResults())) .collect(Collectors.toList()); } final AnalyzeTasksResult analyzeTasksResult = new AnalyzeTasksResult( analyzeJobState.getJobId(), analyzeJobState.getCreatedDateTime(), analyzeJobState.getLastUpdateDateTime(), toJobState(analyzeJobState.getStatus()), analyzeJobState.getDisplayName(), analyzeJobState.getExpirationDateTime()); AnalyzeTasksResultPropertiesHelper.setErrors(analyzeTasksResult, analyzeJobState.getErrors().stream().map(Utility::toTextAnalyticsError).collect(Collectors.toList())); AnalyzeTasksResultPropertiesHelper.setStatistics(analyzeTasksResult, analyzeJobState.getStatistics() == null ? null : toBatchStatistics(analyzeJobState.getStatistics())); AnalyzeTasksResultPropertiesHelper.setCompleted(analyzeTasksResult, tasksStateTasks.getCompleted()); AnalyzeTasksResultPropertiesHelper.setFailed(analyzeTasksResult, tasksStateTasks.getFailed()); AnalyzeTasksResultPropertiesHelper.setInProgress(analyzeTasksResult, tasksStateTasks.getInProgress()); AnalyzeTasksResultPropertiesHelper.setTotal(analyzeTasksResult, tasksStateTasks.getTotal()); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionTasks(analyzeTasksResult, entitiesResultCollections); AnalyzeTasksResultPropertiesHelper.setEntityRecognitionPiiTasks(analyzeTasksResult, piiEntitiesResultCollections); AnalyzeTasksResultPropertiesHelper.setKeyPhraseExtractionTasks(analyzeTasksResult, keyPhrasesResultCollections); return analyzeTasksResult; } private Mono<PollResponse<TextAnalyticsOperationResult>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<TextAnalyticsOperationResult> operationResultPollResponse) { LongRunningOperationStatus status; switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case CANCELLING: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case FAILED: final TextAnalyticsException exception = new TextAnalyticsException("Analyze operation failed", null, null); TextAnalyticsExceptionPropertiesHelper.setErrorInformationList(exception, analyzeJobStateResponse.getValue().getErrors().stream() .map(error -> { final TextAnalyticsErrorInformation textAnalyticsErrorInformation = new TextAnalyticsErrorInformation(); TextAnalyticsErrorInformationPropertiesHelper.setErrorCode(textAnalyticsErrorInformation, TextAnalyticsErrorCode.fromString(error.getCode().toString())); TextAnalyticsErrorInformationPropertiesHelper.setMessage(textAnalyticsErrorInformation, error.getMessage()); return textAnalyticsErrorInformation; }).collect(Collectors.toList())); throw logger.logExceptionAsError(exception); default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } }
why we remove requestUri? And I think currently we are mixing using resourceAddress and requestUri: for example in RxGatewayStoreModel, we are passing resourceId to resourceAddress of CosmosException But in RntbdRequestManager, we are passing physical address to resourceAddress of CosmosException
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
Removed requestUri from CosmosException string representation, as it is never set. In RxGatewayStoreModel, we are passing `request.getResourceAddress()`
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
This is how it looks for gateway -> resourceAddress='dbs/RxJava.SDKTest.SharedDatabase_20201109T182237_GSh/colls/3d2be199-e23b-4af2-a755-510d7068ff97/docs/18b9d280-e899-4300-ae0c-5fe56411aa18, And for direct -> resourceAddress='rntbd://cdb-ms-prod-westus2-fd26.documents.azure.com:14376/apps/db2a149b-bdb4-4755-b26e-56d1a86cdd4e/services/8ce44d24-fe68-49ae-9784-94b322fa46a3/partitions/003a20cb-a187-4b3a-9bc9-306be0217c36/replicas/132494067072942319s/, which both are resource addresses.
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
Thanks Kushagra~ I just wonder should we also capture the server info for gateway mode: (like following) https://127.0.0.1:8081/dbs/RxJava.SDKTest.SharedDatabase_20201109T193921_erZ/colls/7d5337a3-30f7-46bb-b318-104a5dcfb721 Currently, the resourceAddress for gateway mode only contains the resourceId or full name, but not a complete uri. I think that probably why there is requestResource and requestUri there previously? (not sure though)
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
Good point, not sure how we can capture that, any ideas ?
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
Currently we calculate the uri at RxGatewayStoreModel.performRequest, maybe we can add it in the requestContext?
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
Yes, I will try to do that, so we can re-use it, will update this thread once I have reached a conclusion :)
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
what about the direct mode? isn't that set in the direct mode? @kushagraThapar could you please check.
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
@moderakh - It is not used anywhere, other than at this code piece - https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreReader.java#L808 Which I am not even sure, if that is correct or not, but don't plan to touch it :)
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
@xinlian12 @FabianMeiswinkel - I have added the full resource address in gateway mode too, please check. Also updated the PR with sample.
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
Thanks Kushagra, looks good to me~
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders="
public String toString() { return getClass().getSimpleName() + "{" + "userAgent=" + USER_AGENT + ", error=" + cosmosError + ", resourceAddress='" + resourceAddress + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
class CosmosException extends AzureException { private static final long serialVersionUID = 1L; private final static String USER_AGENT = Utils.getUserAgent(); private final int statusCode; private final Map<String, String> responseHeaders; private CosmosDiagnostics cosmosDiagnostics; private RequestTimeline requestTimeline; private CosmosError cosmosError; private int rntbdChannelTaskQueueSize; private RntbdEndpointStatistics rntbdEndpointStatistics; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; private int requestPayloadLength; private int rntbdPendingRequestQueueSize; private int rntbdRequestLength; private int rntbdResponseLength; private boolean sendingRequestHasStarted; protected CosmosException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. * @param cause the inner exception */ protected CosmosException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders, Throwable cause) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, cause); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } void setSubStatusCode(int subStatusCode) { this.responseHeaders.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(subStatusCode)); } /** * Gets the error code associated with the exception. * * @return the error. */ CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Diagnostic Statistics associated with this exception. * * @return Cosmos Diagnostic Statistics associated with this exception. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } CosmosException setDiagnostics(CosmosDiagnostics cosmosDiagnostics) { this.cosmosDiagnostics = cosmosDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf( ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } RequestTimeline getRequestTimeline() { return this.requestTimeline; } void setRequestTimeline(RequestTimeline requestTimeline) { this.requestTimeline = requestTimeline; } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } void setRntbdServiceEndpointStatistics(RntbdEndpointStatistics rntbdEndpointStatistics) { this.rntbdEndpointStatistics = rntbdEndpointStatistics; } RntbdEndpointStatistics getRntbdServiceEndpointStatistics() { return this.rntbdEndpointStatistics; } void setRntbdRequestLength(int rntbdRequestLength) { this.rntbdRequestLength = rntbdRequestLength; } int getRntbdRequestLength() { return this.rntbdRequestLength; } void setRntbdResponseLength(int rntbdResponseLength) { this.rntbdResponseLength = rntbdResponseLength; } int getRntbdResponseLength() { return this.rntbdResponseLength; } void setRequestPayloadLength(int requestBodyLength) { this.requestPayloadLength = requestBodyLength; } int getRequestPayloadLength() { return this.requestPayloadLength; } boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted(boolean hasSendingRequestStarted) { this.sendingRequestHasStarted = hasSendingRequestStarted; } int getRntbdChannelTaskQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdChannelTaskQueueSize(int rntbdChannelTaskQueueSize) { this.rntbdChannelTaskQueueSize = rntbdChannelTaskQueueSize; } int getRntbdPendingRequestQueueSize() { return this.rntbdChannelTaskQueueSize; } void setRntbdPendingRequestQueueSize(int rntbdPendingRequestQueueSize) { this.rntbdPendingRequestQueueSize = rntbdPendingRequestQueueSize; } }
Shouldn't this be expecting `ClientAuthenticationException` exception?
public void testArcUserAssigned() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration(); String token1 = "token1"; String endpoint = "http: TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); configuration.put("IDENTITY_ENDPOINT", endpoint); configuration.put("IMDS_ENDPOINT", endpoint); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) .expectError(CredentialUnavailableException.class); }
.expectError(CredentialUnavailableException.class);
public void testArcUserAssigned() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration().clone(); String token1 = "token1"; String endpoint = "http: TokenRequestContext request = new TokenRequestContext().addScopes("https: configuration.put("IDENTITY_ENDPOINT", endpoint); configuration.put("IMDS_ENDPOINT", endpoint); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(t -> t instanceof ClientAuthenticationException) .verify(); }
class ManagedIdentityCredentialTest { private static final String CLIENT_ID = UUID.randomUUID().toString(); @Test public void testVirtualMachineMSICredentialConfigurations() { ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId("foo").build(); Assert.assertEquals("foo", credential.getClientId()); } @Test public void testMSIEndpoint() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration(); try { String endpoint = "http: String secret = "secret"; String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); configuration.put("MSI_ENDPOINT", endpoint); configuration.put("MSI_SECRET", secret); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateToManagedIdentityEndpoint(null, null, endpoint, secret, request1)).thenReturn(TestUtils.getMockAccessToken(token1, expiresAt)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(token -> token1.equals(token.getToken()) && expiresAt.getSecond() == token.getExpiresAt().getSecond()) .verifyComplete(); } finally { configuration.remove("MSI_ENDPOINT"); configuration.remove("MSI_SECRET"); } } @Test public void testIMDS() throws Exception { String token1 = "token1"; TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateToIMDSEndpoint(request)).thenReturn(TestUtils.getMockAccessToken(token1, expiresOn)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) .expectNextMatches(token -> token1.equals(token.getToken()) && expiresOn.getSecond() == token.getExpiresAt().getSecond()) .verifyComplete(); } @Test }
class ManagedIdentityCredentialTest { private static final String CLIENT_ID = UUID.randomUUID().toString(); @Test public void testVirtualMachineMSICredentialConfigurations() { ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId("foo").build(); Assert.assertEquals("foo", credential.getClientId()); } @Test public void testMSIEndpoint() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration(); try { String endpoint = "http: String secret = "secret"; String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); configuration.put("MSI_ENDPOINT", endpoint); configuration.put("MSI_SECRET", secret); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateToManagedIdentityEndpoint(null, null, endpoint, secret, request1)).thenReturn(TestUtils.getMockAccessToken(token1, expiresAt)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(token -> token1.equals(token.getToken()) && expiresAt.getSecond() == token.getExpiresAt().getSecond()) .verifyComplete(); } finally { configuration.remove("MSI_ENDPOINT"); configuration.remove("MSI_SECRET"); } } @Test public void testIMDS() throws Exception { String token1 = "token1"; TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateToIMDSEndpoint(request)).thenReturn(TestUtils.getMockAccessToken(token1, expiresOn)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) .expectNextMatches(token -> token1.equals(token.getToken()) && expiresOn.getSecond() == token.getExpiresAt().getSecond()) .verifyComplete(); } @Test }
True, updated. Saved time before CI complained
public void testArcUserAssigned() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration(); String token1 = "token1"; String endpoint = "http: TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); configuration.put("IDENTITY_ENDPOINT", endpoint); configuration.put("IMDS_ENDPOINT", endpoint); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) .expectError(CredentialUnavailableException.class); }
.expectError(CredentialUnavailableException.class);
public void testArcUserAssigned() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration().clone(); String token1 = "token1"; String endpoint = "http: TokenRequestContext request = new TokenRequestContext().addScopes("https: configuration.put("IDENTITY_ENDPOINT", endpoint); configuration.put("IMDS_ENDPOINT", endpoint); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(t -> t instanceof ClientAuthenticationException) .verify(); }
class ManagedIdentityCredentialTest { private static final String CLIENT_ID = UUID.randomUUID().toString(); @Test public void testVirtualMachineMSICredentialConfigurations() { ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId("foo").build(); Assert.assertEquals("foo", credential.getClientId()); } @Test public void testMSIEndpoint() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration(); try { String endpoint = "http: String secret = "secret"; String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); configuration.put("MSI_ENDPOINT", endpoint); configuration.put("MSI_SECRET", secret); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateToManagedIdentityEndpoint(null, null, endpoint, secret, request1)).thenReturn(TestUtils.getMockAccessToken(token1, expiresAt)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(token -> token1.equals(token.getToken()) && expiresAt.getSecond() == token.getExpiresAt().getSecond()) .verifyComplete(); } finally { configuration.remove("MSI_ENDPOINT"); configuration.remove("MSI_SECRET"); } } @Test public void testIMDS() throws Exception { String token1 = "token1"; TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateToIMDSEndpoint(request)).thenReturn(TestUtils.getMockAccessToken(token1, expiresOn)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) .expectNextMatches(token -> token1.equals(token.getToken()) && expiresOn.getSecond() == token.getExpiresAt().getSecond()) .verifyComplete(); } @Test }
class ManagedIdentityCredentialTest { private static final String CLIENT_ID = UUID.randomUUID().toString(); @Test public void testVirtualMachineMSICredentialConfigurations() { ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId("foo").build(); Assert.assertEquals("foo", credential.getClientId()); } @Test public void testMSIEndpoint() throws Exception { Configuration configuration = Configuration.getGlobalConfiguration(); try { String endpoint = "http: String secret = "secret"; String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); configuration.put("MSI_ENDPOINT", endpoint); configuration.put("MSI_SECRET", secret); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateToManagedIdentityEndpoint(null, null, endpoint, secret, request1)).thenReturn(TestUtils.getMockAccessToken(token1, expiresAt)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(token -> token1.equals(token.getToken()) && expiresAt.getSecond() == token.getExpiresAt().getSecond()) .verifyComplete(); } finally { configuration.remove("MSI_ENDPOINT"); configuration.remove("MSI_SECRET"); } } @Test public void testIMDS() throws Exception { String token1 = "token1"; TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateToIMDSEndpoint(request)).thenReturn(TestUtils.getMockAccessToken(token1, expiresOn)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(CLIENT_ID).build(); StepVerifier.create(credential.getToken(request)) .expectNextMatches(token -> token1.equals(token.getToken()) && expiresOn.getSecond() == token.getExpiresAt().getSecond()) .verifyComplete(); } @Test }
Looks like you should also remove the ChatUserCredentialPolicy file as it is not used anymore
public ChatAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint); HttpPipeline pipeline; if (httpPipeline != null) { pipeline = httpPipeline; } else { Objects.requireNonNull(communicationUserCredential); Objects.requireNonNull(httpClient); CommunicationTokenCredential tokenCredential = new CommunicationTokenCredential(communicationUserCredential); pipeline = createHttpPipeline(httpClient, new BearerTokenAuthenticationPolicy(tokenCredential, ""), customPolicies); } AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(pipeline); return new ChatAsyncClient(clientBuilder.buildClient()); }
CommunicationTokenCredential tokenCredential = new CommunicationTokenCredential(communicationUserCredential);
public ChatAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint); HttpPipeline pipeline; if (httpPipeline != null) { pipeline = httpPipeline; } else { Objects.requireNonNull(communicationUserCredential); Objects.requireNonNull(httpClient); CommunicationTokenCredential tokenCredential = new CommunicationTokenCredential(communicationUserCredential); pipeline = createHttpPipeline(httpClient, new BearerTokenAuthenticationPolicy(tokenCredential, ""), customPolicies); } AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(pipeline); return new ChatAsyncClient(clientBuilder.buildClient()); }
class ChatClientBuilder { private String endpoint; private HttpClient httpClient; private CommunicationUserCredential communicationUserCredential; private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); private HttpLogOptions logOptions = new HttpLogOptions(); private HttpPipeline httpPipeline; private Configuration configuration; private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; /** * Set endpoint of the service * * @param endpoint url of the service * @return the updated ChatClientBuilder object */ public ChatClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set HttpClient to use * * @param httpClient HttpClient to use * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Set a token credential for authorization * * @param communicationUserCredential valid token credential as a string * @return the updated ChatClientBuilder object */ public ChatClientBuilder credential(CommunicationUserCredential communicationUserCredential) { this.communicationUserCredential = Objects.requireNonNull( communicationUserCredential, "'communicationUserCredential' cannot be null."); return this; } /** * Apply additional {@link HttpPipelinePolicy} * * @param customPolicy HttpPipelinePolicy objects to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return the updated ChatClientBuilder object */ public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link ChatServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link ChatServiceVersion} of the service to be used when making requests. * @return the updated ChatClientBuilder object */ public ChatClientBuilder serviceVersion(ChatServiceVersion version) { return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * * @param httpPipeline HttpPipeline to use for sending service requests and receiving responses. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatClient instance */ public ChatClient buildClient() { ChatAsyncClient asyncClient = buildAsyncClient(); return new ChatClient(asyncClient); } /** * Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatAsyncClient instance */ private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> additionalPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); policies.add(authorizationPolicy); applyRequiredPolicies(policies); if (additionalPolicies != null && additionalPolicies.size() > 0) { policies.addAll(additionalPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) { policies.add(getUserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); policies.add(new HttpLoggingPolicy(logOptions)); } /* * Creates a {@link UserAgentPolicy} using the default chat service module name and version. * * @return The default {@link UserAgentPolicy} for the module. */ private UserAgentPolicy getUserAgentPolicy() { Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); return new UserAgentPolicy( logOptions.getApplicationId(), clientName, clientVersion, configuration); } }
class ChatClientBuilder { private String endpoint; private HttpClient httpClient; private CommunicationUserCredential communicationUserCredential; private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); private HttpLogOptions logOptions = new HttpLogOptions(); private HttpPipeline httpPipeline; private Configuration configuration; private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; /** * Set endpoint of the service * * @param endpoint url of the service * @return the updated ChatClientBuilder object */ public ChatClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set HttpClient to use * * @param httpClient HttpClient to use * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Set a token credential for authorization * * @param communicationUserCredential valid token credential as a string * @return the updated ChatClientBuilder object */ public ChatClientBuilder credential(CommunicationUserCredential communicationUserCredential) { this.communicationUserCredential = Objects.requireNonNull( communicationUserCredential, "'communicationUserCredential' cannot be null."); return this; } /** * Apply additional {@link HttpPipelinePolicy} * * @param customPolicy HttpPipelinePolicy objects to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return the updated ChatClientBuilder object */ public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link ChatServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link ChatServiceVersion} of the service to be used when making requests. * @return the updated ChatClientBuilder object */ public ChatClientBuilder serviceVersion(ChatServiceVersion version) { return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * * @param httpPipeline HttpPipeline to use for sending service requests and receiving responses. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatClient instance */ public ChatClient buildClient() { ChatAsyncClient asyncClient = buildAsyncClient(); return new ChatClient(asyncClient); } /** * Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatAsyncClient instance */ private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> additionalPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); policies.add(authorizationPolicy); applyRequiredPolicies(policies); if (additionalPolicies != null && additionalPolicies.size() > 0) { policies.addAll(additionalPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) { policies.add(getUserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); policies.add(new HttpLoggingPolicy(logOptions)); } /* * Creates a {@link UserAgentPolicy} using the default chat service module name and version. * * @return The default {@link UserAgentPolicy} for the module. */ private UserAgentPolicy getUserAgentPolicy() { Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); return new UserAgentPolicy( logOptions.getApplicationId(), clientName, clientVersion, configuration); } }
Just removed it!
public ChatAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint); HttpPipeline pipeline; if (httpPipeline != null) { pipeline = httpPipeline; } else { Objects.requireNonNull(communicationUserCredential); Objects.requireNonNull(httpClient); CommunicationTokenCredential tokenCredential = new CommunicationTokenCredential(communicationUserCredential); pipeline = createHttpPipeline(httpClient, new BearerTokenAuthenticationPolicy(tokenCredential, ""), customPolicies); } AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(pipeline); return new ChatAsyncClient(clientBuilder.buildClient()); }
CommunicationTokenCredential tokenCredential = new CommunicationTokenCredential(communicationUserCredential);
public ChatAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint); HttpPipeline pipeline; if (httpPipeline != null) { pipeline = httpPipeline; } else { Objects.requireNonNull(communicationUserCredential); Objects.requireNonNull(httpClient); CommunicationTokenCredential tokenCredential = new CommunicationTokenCredential(communicationUserCredential); pipeline = createHttpPipeline(httpClient, new BearerTokenAuthenticationPolicy(tokenCredential, ""), customPolicies); } AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(pipeline); return new ChatAsyncClient(clientBuilder.buildClient()); }
class ChatClientBuilder { private String endpoint; private HttpClient httpClient; private CommunicationUserCredential communicationUserCredential; private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); private HttpLogOptions logOptions = new HttpLogOptions(); private HttpPipeline httpPipeline; private Configuration configuration; private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; /** * Set endpoint of the service * * @param endpoint url of the service * @return the updated ChatClientBuilder object */ public ChatClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set HttpClient to use * * @param httpClient HttpClient to use * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Set a token credential for authorization * * @param communicationUserCredential valid token credential as a string * @return the updated ChatClientBuilder object */ public ChatClientBuilder credential(CommunicationUserCredential communicationUserCredential) { this.communicationUserCredential = Objects.requireNonNull( communicationUserCredential, "'communicationUserCredential' cannot be null."); return this; } /** * Apply additional {@link HttpPipelinePolicy} * * @param customPolicy HttpPipelinePolicy objects to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return the updated ChatClientBuilder object */ public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link ChatServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link ChatServiceVersion} of the service to be used when making requests. * @return the updated ChatClientBuilder object */ public ChatClientBuilder serviceVersion(ChatServiceVersion version) { return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * * @param httpPipeline HttpPipeline to use for sending service requests and receiving responses. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatClient instance */ public ChatClient buildClient() { ChatAsyncClient asyncClient = buildAsyncClient(); return new ChatClient(asyncClient); } /** * Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatAsyncClient instance */ private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> additionalPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); policies.add(authorizationPolicy); applyRequiredPolicies(policies); if (additionalPolicies != null && additionalPolicies.size() > 0) { policies.addAll(additionalPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) { policies.add(getUserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); policies.add(new HttpLoggingPolicy(logOptions)); } /* * Creates a {@link UserAgentPolicy} using the default chat service module name and version. * * @return The default {@link UserAgentPolicy} for the module. */ private UserAgentPolicy getUserAgentPolicy() { Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); return new UserAgentPolicy( logOptions.getApplicationId(), clientName, clientVersion, configuration); } }
class ChatClientBuilder { private String endpoint; private HttpClient httpClient; private CommunicationUserCredential communicationUserCredential; private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); private HttpLogOptions logOptions = new HttpLogOptions(); private HttpPipeline httpPipeline; private Configuration configuration; private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; /** * Set endpoint of the service * * @param endpoint url of the service * @return the updated ChatClientBuilder object */ public ChatClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set HttpClient to use * * @param httpClient HttpClient to use * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Set a token credential for authorization * * @param communicationUserCredential valid token credential as a string * @return the updated ChatClientBuilder object */ public ChatClientBuilder credential(CommunicationUserCredential communicationUserCredential) { this.communicationUserCredential = Objects.requireNonNull( communicationUserCredential, "'communicationUserCredential' cannot be null."); return this; } /** * Apply additional {@link HttpPipelinePolicy} * * @param customPolicy HttpPipelinePolicy objects to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return the updated ChatClientBuilder object */ public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link ChatServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link ChatServiceVersion} of the service to be used when making requests. * @return the updated ChatClientBuilder object */ public ChatClientBuilder serviceVersion(ChatServiceVersion version) { return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * * @param httpPipeline HttpPipeline to use for sending service requests and receiving responses. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatClient instance */ public ChatClient buildClient() { ChatAsyncClient asyncClient = buildAsyncClient(); return new ChatClient(asyncClient); } /** * Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatAsyncClient instance */ private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> additionalPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); policies.add(authorizationPolicy); applyRequiredPolicies(policies); if (additionalPolicies != null && additionalPolicies.size() > 0) { policies.addAll(additionalPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) { policies.add(getUserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); policies.add(new HttpLoggingPolicy(logOptions)); } /* * Creates a {@link UserAgentPolicy} using the default chat service module name and version. * * @return The default {@link UserAgentPolicy} for the module. */ private UserAgentPolicy getUserAgentPolicy() { Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); return new UserAgentPolicy( logOptions.getApplicationId(), clientName, clientVersion, configuration); } }
```suggestion throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("Cannot return data for a " ```
public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("Can not return data for a " + "message which is of type %s.", getBodyType().toString()))); } return Arrays.copyOf(data, data.length); }
throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("Can not return data for a "
public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; }
class AmqpMessageBody { private static final ClientLogger LOGGER = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an immutable list containing only first byte array set on this {@link AmqpMessageBody}. This library only * support one byte array, so the returned list will have only one element. Look for future releases where we will * support multiple byte array. * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("Can not return data for a " + "message which is of type %s.", getBodyType().toString()))); } return new IterableStream<>(Collections.singletonList(data)); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ }
I see you already took care of it
public ChatAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint); HttpPipeline pipeline; if (httpPipeline != null) { pipeline = httpPipeline; } else { Objects.requireNonNull(communicationUserCredential); Objects.requireNonNull(httpClient); CommunicationTokenCredential tokenCredential = new CommunicationTokenCredential(communicationUserCredential); pipeline = createHttpPipeline(httpClient, new BearerTokenAuthenticationPolicy(tokenCredential, ""), customPolicies); } AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(pipeline); return new ChatAsyncClient(clientBuilder.buildClient()); }
CommunicationTokenCredential tokenCredential = new CommunicationTokenCredential(communicationUserCredential);
public ChatAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint); HttpPipeline pipeline; if (httpPipeline != null) { pipeline = httpPipeline; } else { Objects.requireNonNull(communicationUserCredential); Objects.requireNonNull(httpClient); CommunicationTokenCredential tokenCredential = new CommunicationTokenCredential(communicationUserCredential); pipeline = createHttpPipeline(httpClient, new BearerTokenAuthenticationPolicy(tokenCredential, ""), customPolicies); } AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(pipeline); return new ChatAsyncClient(clientBuilder.buildClient()); }
class ChatClientBuilder { private String endpoint; private HttpClient httpClient; private CommunicationUserCredential communicationUserCredential; private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); private HttpLogOptions logOptions = new HttpLogOptions(); private HttpPipeline httpPipeline; private Configuration configuration; private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; /** * Set endpoint of the service * * @param endpoint url of the service * @return the updated ChatClientBuilder object */ public ChatClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set HttpClient to use * * @param httpClient HttpClient to use * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Set a token credential for authorization * * @param communicationUserCredential valid token credential as a string * @return the updated ChatClientBuilder object */ public ChatClientBuilder credential(CommunicationUserCredential communicationUserCredential) { this.communicationUserCredential = Objects.requireNonNull( communicationUserCredential, "'communicationUserCredential' cannot be null."); return this; } /** * Apply additional {@link HttpPipelinePolicy} * * @param customPolicy HttpPipelinePolicy objects to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return the updated ChatClientBuilder object */ public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link ChatServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link ChatServiceVersion} of the service to be used when making requests. * @return the updated ChatClientBuilder object */ public ChatClientBuilder serviceVersion(ChatServiceVersion version) { return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * * @param httpPipeline HttpPipeline to use for sending service requests and receiving responses. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatClient instance */ public ChatClient buildClient() { ChatAsyncClient asyncClient = buildAsyncClient(); return new ChatClient(asyncClient); } /** * Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatAsyncClient instance */ private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> additionalPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); policies.add(authorizationPolicy); applyRequiredPolicies(policies); if (additionalPolicies != null && additionalPolicies.size() > 0) { policies.addAll(additionalPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) { policies.add(getUserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); policies.add(new HttpLoggingPolicy(logOptions)); } /* * Creates a {@link UserAgentPolicy} using the default chat service module name and version. * * @return The default {@link UserAgentPolicy} for the module. */ private UserAgentPolicy getUserAgentPolicy() { Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); return new UserAgentPolicy( logOptions.getApplicationId(), clientName, clientVersion, configuration); } }
class ChatClientBuilder { private String endpoint; private HttpClient httpClient; private CommunicationUserCredential communicationUserCredential; private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); private HttpLogOptions logOptions = new HttpLogOptions(); private HttpPipeline httpPipeline; private Configuration configuration; private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; /** * Set endpoint of the service * * @param endpoint url of the service * @return the updated ChatClientBuilder object */ public ChatClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set HttpClient to use * * @param httpClient HttpClient to use * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Set a token credential for authorization * * @param communicationUserCredential valid token credential as a string * @return the updated ChatClientBuilder object */ public ChatClientBuilder credential(CommunicationUserCredential communicationUserCredential) { this.communicationUserCredential = Objects.requireNonNull( communicationUserCredential, "'communicationUserCredential' cannot be null."); return this; } /** * Apply additional {@link HttpPipelinePolicy} * * @param customPolicy HttpPipelinePolicy objects to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return the updated ChatClientBuilder object */ public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated ChatClientBuilder object */ public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link ChatServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link ChatServiceVersion} of the service to be used when making requests. * @return the updated ChatClientBuilder object */ public ChatClientBuilder serviceVersion(ChatServiceVersion version) { return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * * @param httpPipeline HttpPipeline to use for sending service requests and receiving responses. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder pipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated BlobServiceClientBuilder object */ public ChatClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatClient instance */ public ChatClient buildClient() { ChatAsyncClient asyncClient = buildAsyncClient(); return new ChatClient(asyncClient); } /** * Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return ChatAsyncClient instance */ private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> additionalPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); policies.add(authorizationPolicy); applyRequiredPolicies(policies); if (additionalPolicies != null && additionalPolicies.size() > 0) { policies.addAll(additionalPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) { policies.add(getUserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); policies.add(new HttpLoggingPolicy(logOptions)); } /* * Creates a {@link UserAgentPolicy} using the default chat service module name and version. * * @return The default {@link UserAgentPolicy} for the module. */ private UserAgentPolicy getUserAgentPolicy() { Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); return new UserAgentPolicy( logOptions.getApplicationId(), clientName, clientVersion, configuration); } }
Why do we create a new singletonList each time `getData()` is called? We can create the singletonList just once when `fromData()` is called.
public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("Can not return data for a " + "message which is of type %s.", getBodyType().toString()))); } return new IterableStream<>(Collections.singletonList(data)); }
return new IterableStream<>(Collections.singletonList(data));
public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); }
class AmqpMessageBody { private static final ClientLogger LOGGER = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an immutable list containing only first byte array set on this {@link AmqpMessageBody}. This library only * support one byte array, so the returned list will have only one element. Look for future releases where we will * support multiple byte array. * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("Can not return data for a " + "message which is of type %s.", getBodyType().toString()))); } return Arrays.copyOf(data, data.length); } }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; } }
Why does `getData()` not make a copy of the array but this method does?
public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("Can not return data for a " + "message which is of type %s.", getBodyType().toString()))); } return Arrays.copyOf(data, data.length); }
return Arrays.copyOf(data, data.length);
public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; }
class AmqpMessageBody { private static final ClientLogger LOGGER = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an immutable list containing only first byte array set on this {@link AmqpMessageBody}. This library only * support one byte array, so the returned list will have only one element. Look for future releases where we will * support multiple byte array. * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("Can not return data for a " + "message which is of type %s.", getBodyType().toString()))); } return new IterableStream<>(Collections.singletonList(data)); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ }
This kind of error message only serves to confuse users. It is better to say that the type is not supported at present and that it will be available in future releases. Perhaps even going so far as to point to a pre-filed github issue so that users may find more or subscribe.
public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format("Cannot return data for a " + "message which is of type %s.", getBodyType().toString()))); } return new IterableStream<>(data); }
+ "message which is of type %s.", getBodyType().toString())));
public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private List<byte[]> data; AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = Collections.singletonList(Arrays.copyOf(data, data.length)); return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array, so the returned list will have only one * element. Look for future releases where we will support multiple byte array. * * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format("Cannot return data for a " + "message which is of type %s.", getBodyType().toString()))); } return data.get(0); } }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; } }
I don't think copy is required here. Even if we did this for immutability, we'll have to do this again in getter methods which we are currently not doing. So, just copying here isn't useful.
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = Collections.singletonList(Arrays.copyOf(data, data.length)); return body; }
body.data = Collections.singletonList(Arrays.copyOf(data, data.length));
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private List<byte[]> data; AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array, so the returned list will have only one * element. Look for future releases where we will support multiple byte array. * * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format("Cannot return data for a " + "message which is of type %s.", getBodyType().toString()))); } return new IterableStream<>(data); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method.Get methods not * corresponding to the type of the body throws exception.</b> * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format("Cannot return data for a " + "message which is of type %s.", getBodyType().toString()))); } return data.get(0); } }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; } }
Why do we not copy here, but do in the AmqpMessage ctor?
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = Collections.singletonList(data); return body; }
body.data = Collections.singletonList(data);
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private List<byte[]> data; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can only be called for body type [%s]. Track this issue, " + "https: + "future.", AmqpMessageBodyType.DATA.toString()))); } return new IterableStream<>(data); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can only be called for body type [%s]. Track this issue, " + "https: + "future.", AmqpMessageBodyType.DATA.toString()))); } return data.get(0); } }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; } }
Why did you stop copying here?
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = Collections.singletonList(data); return body; }
body.data = Collections.singletonList(data);
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private List<byte[]> data; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can only be called for body type [%s]. Track this issue, " + "https: + "future.", AmqpMessageBodyType.DATA.toString()))); } return new IterableStream<>(data); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can only be called for body type [%s]. Track this issue, " + "https: + "future.", AmqpMessageBodyType.DATA.toString()))); } return data.get(0); } }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; } }
nit: these new lines under the if statement in various places look out of place.
public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data.get(0); }
throw logger.logExceptionAsError(new IllegalArgumentException(
public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private List<byte[]> data; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = Collections.singletonList(data); return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return new IterableStream<>(data); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ }
Based on discussion above https://github.com/Azure/azure-sdk-for-java/pull/17464#discussion_r525535333, I have removed Arrays.copyOf from AmqpMessageBody and ServiceBusMessage
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = Collections.singletonList(data); return body; }
body.data = Collections.singletonList(data);
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private List<byte[]> data; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can only be called for body type [%s]. Track this issue, " + "https: + "future.", AmqpMessageBodyType.DATA.toString()))); } return new IterableStream<>(data); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can only be called for body type [%s]. Track this issue, " + "https: + "future.", AmqpMessageBodyType.DATA.toString()))); } return data.get(0); } }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; } }
If the common case is to have users call this getFirstData API, we shouldn't wrap into a collection and call get(0) on it, as it is just extra work. We should only wrap the first time the getData call is made, and keep it as a byte[] otherwise.
public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data.get(0); }
return data.get(0);
public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private List<byte[]> data; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = Collections.singletonList(data); return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return new IterableStream<>(data); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; private AmqpMessageBody() { } /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ }
nit: Update comment as this is not a package-private constructor anymore or remove the comment
private AmqpMessageBody() { }
private AmqpMessageBody() { }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message. Look for future releases where we will support multiple byte array and you can use * {@link AmqpMessageBody * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; } }
class AmqpMessageBody { private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; private byte[] data; private List<byte[]> dataList; /** * Creates instance of {@link AmqpMessageBody} with given byte array. * * @param data used to create another instance of {@link AmqpMessageBody}. * * @return AmqpMessageBody Newly created instance. * * @throws NullPointerException if {@code data} is null. */ public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; } /** * Gets the {@link AmqpMessageBodyType} of the message. * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return AmqpBodyType type of the message. */ public AmqpMessageBodyType getBodyType() { return bodyType; } /** * Gets an {@link IterableStream} of byte array containing only first byte array set on this * {@link AmqpMessageBody}. This library only support one byte array at present, so the returned list will have only * one element. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType */ public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); } /** * Gets first byte array set on this {@link AmqpMessageBody}. This library only support one byte array on Amqp * Message at present. * <p><b>Client should test for {@link AmqpMessageBodyType} before calling corresponding get method. Get methods not * corresponding to the type of the body throws exception.</b></p> * * <p><strong>How to check for {@link AmqpMessageBodyType}</strong></p> * {@codesnippet com.azure.core.amqp.models.AmqpBodyType.checkBodyType} * @return data set on {@link AmqpMessageBody}. * * @throws IllegalArgumentException If {@link AmqpMessageBodyType} is not {@link AmqpMessageBodyType * @see <a href="http: * Amqp Message Format.</a> */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "https: + "future.")); } return data; } }
does user supply IV ?
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty.")); } EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; ICryptoTransform transform; byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations."); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); try { transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag); } catch (Exception e) { return Mono.error(e); } byte[] decrypted; try { decrypted = transform.doFinal(decryptOptions.getCipherText()); } catch (Exception e) { return Mono.error(e); } return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId())); }
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty.")); } EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; ICryptoTransform transform; byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations."); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); try { transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag); } catch (Exception e) { return Mono.error(e); } byte[] decrypted; try { decrypted = transform.doFinal(decryptOptions.getCipherText()); } catch (Exception e) { return Mono.error(e); } return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId())); }
class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient { private static final int CBC_BLOCK_SIZE = 16; private static final int GCM_NONCE_SIZE = 12; private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class); private byte[] key; /** * Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations. * * @param serviceClient The client to route the requests through. */ SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) { super(serviceClient); } SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) { super(serviceClient); this.key = key.toAes().getEncoded(); } private byte[] getKey(JsonWebKey key) { if (this.key == null) { this.key = key.toAes().getEncoded(); } return this.key; } @Override Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty.")); } EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; ICryptoTransform transform; byte[] iv = encryptOptions.getIv(); byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = generateRandomByteArray(GCM_NONCE_SIZE); if (iv == null) { if (algorithm == EncryptionAlgorithm.A128GCM || algorithm == EncryptionAlgorithm.A192GCM || algorithm == EncryptionAlgorithm.A256GCM) { iv = generateRandomByteArray(GCM_NONCE_SIZE); } else if (algorithm == EncryptionAlgorithm.A128CBC || algorithm == EncryptionAlgorithm.A192CBC || algorithm == EncryptionAlgorithm.A256CBC || algorithm == EncryptionAlgorithm.A128CBCPAD || algorithm == EncryptionAlgorithm.A192CBCPAD || algorithm == EncryptionAlgorithm.A256CBCPAD) { iv = generateRandomByteArray(CBC_BLOCK_SIZE); } } try { transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData, authenticationTag); } catch (Exception e) { return Mono.error(e); } byte[] encrypted; try { encrypted = transform.doFinal(encryptOptions.getPlainText()); } catch (Exception e) { return Mono.error(e); } return Mono.just(new EncryptResult(encrypted, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData, authenticationTag)); } @Override @Override Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) { return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key")); } @Override Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context, JsonWebKey key) { return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key")); } @Override Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("key")); } Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; ICryptoTransform transform; try { transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null); } catch (Exception e) { return Mono.error(e); } byte[] encrypted; try { encrypted = transform.doFinal(key); } catch (Exception e) { return Mono.error(e); } return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId())); } @Override Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; ICryptoTransform transform; try { transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null); } catch (Exception e) { return Mono.error(e); } byte[] decrypted; try { decrypted = transform.doFinal(encryptedKey); } catch (Exception e) { return Mono.error(e); } return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId())); } @Override Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) { return signAsync(algorithm, data, context, key); } @Override Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context, JsonWebKey key) { return verifyAsync(algorithm, data, signature, context, key); } private byte[] generateRandomByteArray(int sizeInBytes) { byte[] iv = new byte[0]; SecureRandom randomSecureRandom; try { randomSecureRandom = SecureRandom.getInstance("SHA1PRNG"); iv = new byte[sizeInBytes]; randomSecureRandom.nextBytes(iv); } catch (NoSuchAlgorithmException e) { logger.logThrowableAsError(e); } return iv; } }
class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient { private static final int CBC_BLOCK_SIZE = 16; private static final int GCM_NONCE_SIZE = 12; private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class); private byte[] key; /** * Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations. * * @param serviceClient The client to route the requests through. */ SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) { super(serviceClient); } SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) { super(serviceClient); this.key = key.toAes().getEncoded(); } private byte[] getKey(JsonWebKey key) { if (this.key == null) { this.key = key.toAes().getEncoded(); } return this.key; } @Override Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty.")); } EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; ICryptoTransform transform; byte[] iv = encryptOptions.getIv(); byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = generateRandomByteArray(GCM_NONCE_SIZE); if (iv == null) { if (algorithm == EncryptionAlgorithm.A128GCM || algorithm == EncryptionAlgorithm.A192GCM || algorithm == EncryptionAlgorithm.A256GCM) { iv = generateRandomByteArray(GCM_NONCE_SIZE); } else if (algorithm == EncryptionAlgorithm.A128CBC || algorithm == EncryptionAlgorithm.A192CBC || algorithm == EncryptionAlgorithm.A256CBC || algorithm == EncryptionAlgorithm.A128CBCPAD || algorithm == EncryptionAlgorithm.A192CBCPAD || algorithm == EncryptionAlgorithm.A256CBCPAD) { iv = generateRandomByteArray(CBC_BLOCK_SIZE); } } try { transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData, authenticationTag); } catch (Exception e) { return Mono.error(e); } byte[] encrypted; try { encrypted = transform.doFinal(encryptOptions.getPlainText()); } catch (Exception e) { return Mono.error(e); } return Mono.just(new EncryptResult(encrypted, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData, authenticationTag)); } @Override @Override Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) { return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key")); } @Override Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context, JsonWebKey key) { return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key")); } @Override Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("key")); } Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; ICryptoTransform transform; try { transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null); } catch (Exception e) { return Mono.error(e); } byte[] encrypted; try { encrypted = transform.doFinal(key); } catch (Exception e) { return Mono.error(e); } return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId())); } @Override Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; ICryptoTransform transform; try { transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null); } catch (Exception e) { return Mono.error(e); } byte[] decrypted; try { decrypted = transform.doFinal(encryptedKey); } catch (Exception e) { return Mono.error(e); } return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId())); } @Override Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) { return signAsync(algorithm, data, context, key); } @Override Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context, JsonWebKey key) { return verifyAsync(algorithm, data, signature, context, key); } private byte[] generateRandomByteArray(int sizeInBytes) { byte[] iv = new byte[0]; SecureRandom randomSecureRandom; try { randomSecureRandom = SecureRandom.getInstance("SHA1PRNG"); iv = new byte[sizeInBytes]; randomSecureRandom.nextBytes(iv); } catch (NoSuchAlgorithmException e) { logger.logThrowableAsError(e); } return iv; } }
Yes
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty.")); } EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; ICryptoTransform transform; byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations."); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); try { transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag); } catch (Exception e) { return Mono.error(e); } byte[] decrypted; try { decrypted = transform.doFinal(decryptOptions.getCipherText()); } catch (Exception e) { return Mono.error(e); } return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId())); }
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty.")); } EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm(); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; ICryptoTransform transform; byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations."); byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = decryptOptions.getAuthenticationTag(); try { transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag); } catch (Exception e) { return Mono.error(e); } byte[] decrypted; try { decrypted = transform.doFinal(decryptOptions.getCipherText()); } catch (Exception e) { return Mono.error(e); } return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId())); }
class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient { private static final int CBC_BLOCK_SIZE = 16; private static final int GCM_NONCE_SIZE = 12; private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class); private byte[] key; /** * Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations. * * @param serviceClient The client to route the requests through. */ SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) { super(serviceClient); } SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) { super(serviceClient); this.key = key.toAes().getEncoded(); } private byte[] getKey(JsonWebKey key) { if (this.key == null) { this.key = key.toAes().getEncoded(); } return this.key; } @Override Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty.")); } EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; ICryptoTransform transform; byte[] iv = encryptOptions.getIv(); byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = generateRandomByteArray(GCM_NONCE_SIZE); if (iv == null) { if (algorithm == EncryptionAlgorithm.A128GCM || algorithm == EncryptionAlgorithm.A192GCM || algorithm == EncryptionAlgorithm.A256GCM) { iv = generateRandomByteArray(GCM_NONCE_SIZE); } else if (algorithm == EncryptionAlgorithm.A128CBC || algorithm == EncryptionAlgorithm.A192CBC || algorithm == EncryptionAlgorithm.A256CBC || algorithm == EncryptionAlgorithm.A128CBCPAD || algorithm == EncryptionAlgorithm.A192CBCPAD || algorithm == EncryptionAlgorithm.A256CBCPAD) { iv = generateRandomByteArray(CBC_BLOCK_SIZE); } } try { transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData, authenticationTag); } catch (Exception e) { return Mono.error(e); } byte[] encrypted; try { encrypted = transform.doFinal(encryptOptions.getPlainText()); } catch (Exception e) { return Mono.error(e); } return Mono.just(new EncryptResult(encrypted, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData, authenticationTag)); } @Override @Override Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) { return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key")); } @Override Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context, JsonWebKey key) { return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key")); } @Override Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("key")); } Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; ICryptoTransform transform; try { transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null); } catch (Exception e) { return Mono.error(e); } byte[] encrypted; try { encrypted = transform.doFinal(key); } catch (Exception e) { return Mono.error(e); } return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId())); } @Override Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; ICryptoTransform transform; try { transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null); } catch (Exception e) { return Mono.error(e); } byte[] decrypted; try { decrypted = transform.doFinal(encryptedKey); } catch (Exception e) { return Mono.error(e); } return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId())); } @Override Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) { return signAsync(algorithm, data, context, key); } @Override Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context, JsonWebKey key) { return verifyAsync(algorithm, data, signature, context, key); } private byte[] generateRandomByteArray(int sizeInBytes) { byte[] iv = new byte[0]; SecureRandom randomSecureRandom; try { randomSecureRandom = SecureRandom.getInstance("SHA1PRNG"); iv = new byte[sizeInBytes]; randomSecureRandom.nextBytes(iv); } catch (NoSuchAlgorithmException e) { logger.logThrowableAsError(e); } return iv; } }
class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient { private static final int CBC_BLOCK_SIZE = 16; private static final int GCM_NONCE_SIZE = 12; private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class); private byte[] key; /** * Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations. * * @param serviceClient The client to route the requests through. */ SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) { super(serviceClient); } SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) { super(serviceClient); this.key = key.toAes().getEncoded(); } private byte[] getKey(JsonWebKey key) { if (this.key == null) { this.key = key.toAes().getEncoded(); } return this.key; } @Override Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty.")); } EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm(); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm; ICryptoTransform transform; byte[] iv = encryptOptions.getIv(); byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData(); byte[] authenticationTag = generateRandomByteArray(GCM_NONCE_SIZE); if (iv == null) { if (algorithm == EncryptionAlgorithm.A128GCM || algorithm == EncryptionAlgorithm.A192GCM || algorithm == EncryptionAlgorithm.A256GCM) { iv = generateRandomByteArray(GCM_NONCE_SIZE); } else if (algorithm == EncryptionAlgorithm.A128CBC || algorithm == EncryptionAlgorithm.A192CBC || algorithm == EncryptionAlgorithm.A256CBC || algorithm == EncryptionAlgorithm.A128CBCPAD || algorithm == EncryptionAlgorithm.A192CBCPAD || algorithm == EncryptionAlgorithm.A256CBCPAD) { iv = generateRandomByteArray(CBC_BLOCK_SIZE); } } try { transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData, authenticationTag); } catch (Exception e) { return Mono.error(e); } byte[] encrypted; try { encrypted = transform.doFinal(encryptOptions.getPlainText()); } catch (Exception e) { return Mono.error(e); } return Mono.just(new EncryptResult(encrypted, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData, authenticationTag)); } @Override @Override Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) { return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key")); } @Override Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context, JsonWebKey key) { return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key")); } @Override Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); if (key == null || key.length == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("key")); } Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; ICryptoTransform transform; try { transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null); } catch (Exception e) { return Mono.error(e); } byte[] encrypted; try { encrypted = transform.doFinal(key); } catch (Exception e) { return Mono.error(e); } return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId())); } @Override Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) { this.key = getKey(jsonWebKey); Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm.toString()); if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) { return Mono.error(new NoSuchAlgorithmException(algorithm.toString())); } LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm; ICryptoTransform transform; try { transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null); } catch (Exception e) { return Mono.error(e); } byte[] decrypted; try { decrypted = transform.doFinal(encryptedKey); } catch (Exception e) { return Mono.error(e); } return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId())); } @Override Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) { return signAsync(algorithm, data, context, key); } @Override Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context, JsonWebKey key) { return verifyAsync(algorithm, data, signature, context, key); } private byte[] generateRandomByteArray(int sizeInBytes) { byte[] iv = new byte[0]; SecureRandom randomSecureRandom; try { randomSecureRandom = SecureRandom.getInstance("SHA1PRNG"); iv = new byte[sizeInBytes]; randomSecureRandom.nextBytes(iv); } catch (NoSuchAlgorithmException e) { logger.logThrowableAsError(e); } return iv; } }
I would use `checkNotNull` pattern that you used elsewhere to be consistent and more succinct
public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new NullPointerException("partitionKeyRangeId"); } this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); }
throw new NullPointerException("partitionKeyRangeId");
public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { checkNotNull(partitionKeyRangeId, "Argument 'partitionKeyRangeId' must not be null"); this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); }
class FeedRangePartitionKeyRangeImpl extends FeedRangeInternal { private final String partitionKeyRangeId; private final PartitionKeyRangeIdentity partitionKeyRangeIdentity; public String getPartitionKeyRangeId() { return this.partitionKeyRangeId; } public PartitionKeyRangeIdentity getPartitionKeyRangeIdentity() { return this.partitionKeyRangeIdentity; } @Override public void accept(final FeedRangeVisitor visitor) { if (visitor == null) { throw new NullPointerException("visitor"); } visitor.visit(this); } @Override public <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input) { if (visitor == null) { throw new NullPointerException("visitor"); } visitor.visit(this, input); } @Override public <T> Mono<T> acceptAsync(final FeedRangeAsyncVisitor<T> visitor) { if (visitor == null) { throw new NullPointerException("visitor"); } return visitor.visitAsync(this); } @Override public Mono<UnmodifiableList<Range<String>>> getEffectiveRangesAsync( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final Mono<ValueHolder<PartitionKeyRange>> getPkRangeTask = routingMapProvider .tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, false, null) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return routingMapProvider.tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, true, null); } else { return Mono.just(pkRangeHolder); } }) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return Mono.error( new PartitionKeyRangeGoneException( String.format( "The PartitionKeyRangeId: \"%s\" is not valid for the current " + "container %s .", partitionKeyRangeId, containerRid) )); } else { return Mono.just(pkRangeHolder); } }); return getPkRangeTask.flatMap((pkRangeHolder) -> { final ArrayList<Range<String>> temp = new ArrayList<>(); if (pkRangeHolder != null) { temp.add(pkRangeHolder.v.toRange()); } return Mono.just((UnmodifiableList<Range<String>>)UnmodifiableList.unmodifiableList(temp)); }); } @Override public Mono<UnmodifiableList<String>> getPartitionKeyRangesAsync( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final ArrayList<String> temp = new ArrayList<>(); temp.add(this.partitionKeyRangeId); return Mono.just( (UnmodifiableList<String>)UnmodifiableList.unmodifiableList(temp)); } public void populatePropertyBag() { super.populatePropertyBag(); if (this.partitionKeyRangeId != null) { setProperty( this, Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID, this.partitionKeyRangeId); } } @Override public String toString() { return this.partitionKeyRangeId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FeedRangePartitionKeyRangeImpl that = (FeedRangePartitionKeyRangeImpl) o; return Objects.equals(this.partitionKeyRangeId, that.partitionKeyRangeId); } @Override public int hashCode() { return Objects.hash(partitionKeyRangeId); } }
class FeedRangePartitionKeyRangeImpl extends FeedRangeInternal { private final String partitionKeyRangeId; private final PartitionKeyRangeIdentity partitionKeyRangeIdentity; public String getPartitionKeyRangeId() { return this.partitionKeyRangeId; } public PartitionKeyRangeIdentity getPartitionKeyRangeIdentity() { return this.partitionKeyRangeIdentity; } @Override public void accept(final FeedRangeVisitor visitor) { checkNotNull(visitor, "Argument 'visitor' must not be null"); visitor.visit(this); } @Override public <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input) { checkNotNull(visitor, "Argument 'visitor' must not be null"); visitor.visit(this, input); } @Override public <T> Mono<T> accept(final FeedRangeAsyncVisitor<T> visitor) { checkNotNull(visitor, "Argument 'visitor' must not be null"); return visitor.visit(this); } @Override public Mono<UnmodifiableList<Range<String>>> getEffectiveRanges( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final Mono<ValueHolder<PartitionKeyRange>> getPkRangeTask = routingMapProvider .tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, false, null) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return routingMapProvider.tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, true, null); } else { return Mono.just(pkRangeHolder); } }) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return Mono.error( new PartitionKeyRangeGoneException( String.format( "The PartitionKeyRangeId: \"%s\" is not valid for the current " + "container %s .", partitionKeyRangeId, containerRid) )); } else { return Mono.just(pkRangeHolder); } }); return getPkRangeTask.flatMap((pkRangeHolder) -> { final ArrayList<Range<String>> temp = new ArrayList<>(); if (pkRangeHolder != null) { temp.add(pkRangeHolder.v.toRange()); } return Mono.just((UnmodifiableList<Range<String>>)UnmodifiableList.unmodifiableList(temp)); }); } @Override public Mono<UnmodifiableList<String>> getPartitionKeyRanges( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final ArrayList<String> temp = new ArrayList<>(); temp.add(this.partitionKeyRangeId); return Mono.just( (UnmodifiableList<String>)UnmodifiableList.unmodifiableList(temp)); } public void populatePropertyBag() { super.populatePropertyBag(); if (this.partitionKeyRangeId != null) { setProperty( this, Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID, this.partitionKeyRangeId); } } @Override public String toString() { return this.partitionKeyRangeId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FeedRangePartitionKeyRangeImpl that = (FeedRangePartitionKeyRangeImpl) o; return Objects.equals(this.partitionKeyRangeId, that.partitionKeyRangeId); } @Override public int hashCode() { return Objects.hash(partitionKeyRangeId); } }
I would use `checkNotNull` pattern that you used elsewhere to be consistent and more succinct. here and everywhere else in the new code.
public void accept(final FeedRangeVisitor visitor) { if (visitor == null) { throw new NullPointerException("visitor"); } visitor.visit(this); }
throw new NullPointerException("visitor");
public void accept(final FeedRangeVisitor visitor) { checkNotNull(visitor, "Argument 'visitor' must not be null"); visitor.visit(this); }
class FeedRangePartitionKeyRangeImpl extends FeedRangeInternal { private final String partitionKeyRangeId; private final PartitionKeyRangeIdentity partitionKeyRangeIdentity; public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new NullPointerException("partitionKeyRangeId"); } this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); } public String getPartitionKeyRangeId() { return this.partitionKeyRangeId; } public PartitionKeyRangeIdentity getPartitionKeyRangeIdentity() { return this.partitionKeyRangeIdentity; } @Override @Override public <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input) { if (visitor == null) { throw new NullPointerException("visitor"); } visitor.visit(this, input); } @Override public <T> Mono<T> acceptAsync(final FeedRangeAsyncVisitor<T> visitor) { if (visitor == null) { throw new NullPointerException("visitor"); } return visitor.visitAsync(this); } @Override public Mono<UnmodifiableList<Range<String>>> getEffectiveRangesAsync( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final Mono<ValueHolder<PartitionKeyRange>> getPkRangeTask = routingMapProvider .tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, false, null) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return routingMapProvider.tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, true, null); } else { return Mono.just(pkRangeHolder); } }) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return Mono.error( new PartitionKeyRangeGoneException( String.format( "The PartitionKeyRangeId: \"%s\" is not valid for the current " + "container %s .", partitionKeyRangeId, containerRid) )); } else { return Mono.just(pkRangeHolder); } }); return getPkRangeTask.flatMap((pkRangeHolder) -> { final ArrayList<Range<String>> temp = new ArrayList<>(); if (pkRangeHolder != null) { temp.add(pkRangeHolder.v.toRange()); } return Mono.just((UnmodifiableList<Range<String>>)UnmodifiableList.unmodifiableList(temp)); }); } @Override public Mono<UnmodifiableList<String>> getPartitionKeyRangesAsync( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final ArrayList<String> temp = new ArrayList<>(); temp.add(this.partitionKeyRangeId); return Mono.just( (UnmodifiableList<String>)UnmodifiableList.unmodifiableList(temp)); } public void populatePropertyBag() { super.populatePropertyBag(); if (this.partitionKeyRangeId != null) { setProperty( this, Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID, this.partitionKeyRangeId); } } @Override public String toString() { return this.partitionKeyRangeId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FeedRangePartitionKeyRangeImpl that = (FeedRangePartitionKeyRangeImpl) o; return Objects.equals(this.partitionKeyRangeId, that.partitionKeyRangeId); } @Override public int hashCode() { return Objects.hash(partitionKeyRangeId); } }
class FeedRangePartitionKeyRangeImpl extends FeedRangeInternal { private final String partitionKeyRangeId; private final PartitionKeyRangeIdentity partitionKeyRangeIdentity; public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { checkNotNull(partitionKeyRangeId, "Argument 'partitionKeyRangeId' must not be null"); this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); } public String getPartitionKeyRangeId() { return this.partitionKeyRangeId; } public PartitionKeyRangeIdentity getPartitionKeyRangeIdentity() { return this.partitionKeyRangeIdentity; } @Override @Override public <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input) { checkNotNull(visitor, "Argument 'visitor' must not be null"); visitor.visit(this, input); } @Override public <T> Mono<T> accept(final FeedRangeAsyncVisitor<T> visitor) { checkNotNull(visitor, "Argument 'visitor' must not be null"); return visitor.visit(this); } @Override public Mono<UnmodifiableList<Range<String>>> getEffectiveRanges( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final Mono<ValueHolder<PartitionKeyRange>> getPkRangeTask = routingMapProvider .tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, false, null) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return routingMapProvider.tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, true, null); } else { return Mono.just(pkRangeHolder); } }) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return Mono.error( new PartitionKeyRangeGoneException( String.format( "The PartitionKeyRangeId: \"%s\" is not valid for the current " + "container %s .", partitionKeyRangeId, containerRid) )); } else { return Mono.just(pkRangeHolder); } }); return getPkRangeTask.flatMap((pkRangeHolder) -> { final ArrayList<Range<String>> temp = new ArrayList<>(); if (pkRangeHolder != null) { temp.add(pkRangeHolder.v.toRange()); } return Mono.just((UnmodifiableList<Range<String>>)UnmodifiableList.unmodifiableList(temp)); }); } @Override public Mono<UnmodifiableList<String>> getPartitionKeyRanges( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final ArrayList<String> temp = new ArrayList<>(); temp.add(this.partitionKeyRangeId); return Mono.just( (UnmodifiableList<String>)UnmodifiableList.unmodifiableList(temp)); } public void populatePropertyBag() { super.populatePropertyBag(); if (this.partitionKeyRangeId != null) { setProperty( this, Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID, this.partitionKeyRangeId); } } @Override public String toString() { return this.partitionKeyRangeId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FeedRangePartitionKeyRangeImpl that = (FeedRangePartitionKeyRangeImpl) o; return Objects.equals(this.partitionKeyRangeId, that.partitionKeyRangeId); } @Override public int hashCode() { return Objects.hash(partitionKeyRangeId); } }
Fixed
public void accept(final FeedRangeVisitor visitor) { if (visitor == null) { throw new NullPointerException("visitor"); } visitor.visit(this); }
throw new NullPointerException("visitor");
public void accept(final FeedRangeVisitor visitor) { checkNotNull(visitor, "Argument 'visitor' must not be null"); visitor.visit(this); }
class FeedRangePartitionKeyRangeImpl extends FeedRangeInternal { private final String partitionKeyRangeId; private final PartitionKeyRangeIdentity partitionKeyRangeIdentity; public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new NullPointerException("partitionKeyRangeId"); } this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); } public String getPartitionKeyRangeId() { return this.partitionKeyRangeId; } public PartitionKeyRangeIdentity getPartitionKeyRangeIdentity() { return this.partitionKeyRangeIdentity; } @Override @Override public <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input) { if (visitor == null) { throw new NullPointerException("visitor"); } visitor.visit(this, input); } @Override public <T> Mono<T> acceptAsync(final FeedRangeAsyncVisitor<T> visitor) { if (visitor == null) { throw new NullPointerException("visitor"); } return visitor.visitAsync(this); } @Override public Mono<UnmodifiableList<Range<String>>> getEffectiveRangesAsync( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final Mono<ValueHolder<PartitionKeyRange>> getPkRangeTask = routingMapProvider .tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, false, null) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return routingMapProvider.tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, true, null); } else { return Mono.just(pkRangeHolder); } }) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return Mono.error( new PartitionKeyRangeGoneException( String.format( "The PartitionKeyRangeId: \"%s\" is not valid for the current " + "container %s .", partitionKeyRangeId, containerRid) )); } else { return Mono.just(pkRangeHolder); } }); return getPkRangeTask.flatMap((pkRangeHolder) -> { final ArrayList<Range<String>> temp = new ArrayList<>(); if (pkRangeHolder != null) { temp.add(pkRangeHolder.v.toRange()); } return Mono.just((UnmodifiableList<Range<String>>)UnmodifiableList.unmodifiableList(temp)); }); } @Override public Mono<UnmodifiableList<String>> getPartitionKeyRangesAsync( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final ArrayList<String> temp = new ArrayList<>(); temp.add(this.partitionKeyRangeId); return Mono.just( (UnmodifiableList<String>)UnmodifiableList.unmodifiableList(temp)); } public void populatePropertyBag() { super.populatePropertyBag(); if (this.partitionKeyRangeId != null) { setProperty( this, Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID, this.partitionKeyRangeId); } } @Override public String toString() { return this.partitionKeyRangeId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FeedRangePartitionKeyRangeImpl that = (FeedRangePartitionKeyRangeImpl) o; return Objects.equals(this.partitionKeyRangeId, that.partitionKeyRangeId); } @Override public int hashCode() { return Objects.hash(partitionKeyRangeId); } }
class FeedRangePartitionKeyRangeImpl extends FeedRangeInternal { private final String partitionKeyRangeId; private final PartitionKeyRangeIdentity partitionKeyRangeIdentity; public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { checkNotNull(partitionKeyRangeId, "Argument 'partitionKeyRangeId' must not be null"); this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); } public String getPartitionKeyRangeId() { return this.partitionKeyRangeId; } public PartitionKeyRangeIdentity getPartitionKeyRangeIdentity() { return this.partitionKeyRangeIdentity; } @Override @Override public <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input) { checkNotNull(visitor, "Argument 'visitor' must not be null"); visitor.visit(this, input); } @Override public <T> Mono<T> accept(final FeedRangeAsyncVisitor<T> visitor) { checkNotNull(visitor, "Argument 'visitor' must not be null"); return visitor.visit(this); } @Override public Mono<UnmodifiableList<Range<String>>> getEffectiveRanges( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final Mono<ValueHolder<PartitionKeyRange>> getPkRangeTask = routingMapProvider .tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, false, null) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return routingMapProvider.tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, true, null); } else { return Mono.just(pkRangeHolder); } }) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return Mono.error( new PartitionKeyRangeGoneException( String.format( "The PartitionKeyRangeId: \"%s\" is not valid for the current " + "container %s .", partitionKeyRangeId, containerRid) )); } else { return Mono.just(pkRangeHolder); } }); return getPkRangeTask.flatMap((pkRangeHolder) -> { final ArrayList<Range<String>> temp = new ArrayList<>(); if (pkRangeHolder != null) { temp.add(pkRangeHolder.v.toRange()); } return Mono.just((UnmodifiableList<Range<String>>)UnmodifiableList.unmodifiableList(temp)); }); } @Override public Mono<UnmodifiableList<String>> getPartitionKeyRanges( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final ArrayList<String> temp = new ArrayList<>(); temp.add(this.partitionKeyRangeId); return Mono.just( (UnmodifiableList<String>)UnmodifiableList.unmodifiableList(temp)); } public void populatePropertyBag() { super.populatePropertyBag(); if (this.partitionKeyRangeId != null) { setProperty( this, Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID, this.partitionKeyRangeId); } } @Override public String toString() { return this.partitionKeyRangeId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FeedRangePartitionKeyRangeImpl that = (FeedRangePartitionKeyRangeImpl) o; return Objects.equals(this.partitionKeyRangeId, that.partitionKeyRangeId); } @Override public int hashCode() { return Objects.hash(partitionKeyRangeId); } }
use slf4j logger placeholder instead of `%s` ```suggestion LOGGER.debug("Failed to parse feed range JSON {}", jsonString, ioError); ```
public static FeedRangeInternal tryParse(final String jsonString) { checkNotNull(jsonString, "Argument 'jsonString' must not be null"); final ObjectMapper mapper = Utils.getSimpleObjectMapper(); try { JsonNode rootNode = mapper.readTree(jsonString); JsonNode rangeNode = rootNode.get(Constants.Properties.RANGE); if (rangeNode != null && rangeNode.isObject()) { Range<String> range = new Range<>((ObjectNode)rangeNode); return new FeedRangeEpkImpl(range); } JsonNode pkNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY); if (pkNode != null && pkNode.isArray()) { PartitionKeyInternal pk = mapper.convertValue(pkNode, PartitionKeyInternal.class); return new FeedRangePartitionKeyImpl(pk); } JsonNode pkRangeIdNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID); if (pkRangeIdNode != null && pkRangeIdNode.isTextual()) { return new FeedRangePartitionKeyRangeImpl(pkRangeIdNode.asText()); } return null; } catch (final IOException ioError) { LOGGER.debug("Failed to parse feed range JSON %s", jsonString, ioError); return null; } }
LOGGER.debug("Failed to parse feed range JSON %s", jsonString, ioError);
public static FeedRangeInternal tryParse(final String jsonString) { checkNotNull(jsonString, "Argument 'jsonString' must not be null"); final ObjectMapper mapper = Utils.getSimpleObjectMapper(); try { JsonNode rootNode = mapper.readTree(jsonString); JsonNode rangeNode = rootNode.get(Constants.Properties.RANGE); if (rangeNode != null && rangeNode.isObject()) { Range<String> range = new Range<>((ObjectNode)rangeNode); return new FeedRangeEpkImpl(range); } JsonNode pkNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY); if (pkNode != null && pkNode.isArray()) { PartitionKeyInternal pk = mapper.convertValue(pkNode, PartitionKeyInternal.class); return new FeedRangePartitionKeyImpl(pk); } JsonNode pkRangeIdNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID); if (pkRangeIdNode != null && pkRangeIdNode.isTextual()) { return new FeedRangePartitionKeyRangeImpl(pkRangeIdNode.asText()); } return null; } catch (final IOException ioError) { LOGGER.debug("Failed to parse feed range JSON {}", jsonString, ioError); return null; } }
class FeedRangeInternal extends JsonSerializable implements FeedRange { private final static Logger LOGGER = LoggerFactory.getLogger(FeedRangeInternal.class); public abstract void accept(FeedRangeVisitor visitor); public abstract <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input); public abstract <T> Mono<T> accept(FeedRangeAsyncVisitor<T> visitor); public static FeedRangeInternal convert(final FeedRange feedRange) { checkNotNull(feedRange, "Argument 'feedRange' must not be null"); if (feedRange instanceof FeedRangeInternal) { return (FeedRangeInternal)feedRange; } String json = feedRange.toJsonString(); return fromJsonString(json); } /** * Creates a range from a previously obtained string representation. * * @param json A string representation of a feed range * @return A feed range */ public static FeedRangeInternal fromJsonString(String json) { FeedRangeInternal parsedRange = FeedRangeInternal.tryParse(json); if (parsedRange == null) { throw new IllegalArgumentException( String.format( "The provided string '%s' does not represent any known format.", json)); } return parsedRange; } public abstract Mono<UnmodifiableList<Range<String>>> getEffectiveRanges( IRoutingMapProvider routingMapProvider, String containerRid, PartitionKeyDefinition partitionKeyDefinition); public abstract Mono<UnmodifiableList<String>> getPartitionKeyRanges( IRoutingMapProvider routingMapProvider, String containerRid, PartitionKeyDefinition partitionKeyDefinition); public void populatePropertyBag() { super.populatePropertyBag(); } @Override public abstract String toString(); @Override public String toJsonString() { return this.toJson(); } }
class FeedRangeInternal extends JsonSerializable implements FeedRange { private final static Logger LOGGER = LoggerFactory.getLogger(FeedRangeInternal.class); public abstract void accept(FeedRangeVisitor visitor); public abstract <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input); public abstract <T> Mono<T> accept(FeedRangeAsyncVisitor<T> visitor); public static FeedRangeInternal convert(final FeedRange feedRange) { checkNotNull(feedRange, "Argument 'feedRange' must not be null"); if (feedRange instanceof FeedRangeInternal) { return (FeedRangeInternal)feedRange; } String json = feedRange.toJsonString(); return fromJsonString(json); } /** * Creates a range from a previously obtained string representation. * * @param json A string representation of a feed range * @return A feed range */ public static FeedRangeInternal fromJsonString(String json) { FeedRangeInternal parsedRange = FeedRangeInternal.tryParse(json); if (parsedRange == null) { throw new IllegalArgumentException( String.format( "The provided string '%s' does not represent any known format.", json)); } return parsedRange; } public abstract Mono<UnmodifiableList<Range<String>>> getEffectiveRanges( IRoutingMapProvider routingMapProvider, String containerRid, PartitionKeyDefinition partitionKeyDefinition); public abstract Mono<UnmodifiableList<String>> getPartitionKeyRanges( IRoutingMapProvider routingMapProvider, String containerRid, PartitionKeyDefinition partitionKeyDefinition); public void populatePropertyBag() { super.populatePropertyBag(); } @Override public abstract String toString(); @Override public String toJsonString() { return this.toJson(); } }
Fixed
public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new NullPointerException("partitionKeyRangeId"); } this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); }
throw new NullPointerException("partitionKeyRangeId");
public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { checkNotNull(partitionKeyRangeId, "Argument 'partitionKeyRangeId' must not be null"); this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); }
class FeedRangePartitionKeyRangeImpl extends FeedRangeInternal { private final String partitionKeyRangeId; private final PartitionKeyRangeIdentity partitionKeyRangeIdentity; public String getPartitionKeyRangeId() { return this.partitionKeyRangeId; } public PartitionKeyRangeIdentity getPartitionKeyRangeIdentity() { return this.partitionKeyRangeIdentity; } @Override public void accept(final FeedRangeVisitor visitor) { if (visitor == null) { throw new NullPointerException("visitor"); } visitor.visit(this); } @Override public <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input) { if (visitor == null) { throw new NullPointerException("visitor"); } visitor.visit(this, input); } @Override public <T> Mono<T> acceptAsync(final FeedRangeAsyncVisitor<T> visitor) { if (visitor == null) { throw new NullPointerException("visitor"); } return visitor.visitAsync(this); } @Override public Mono<UnmodifiableList<Range<String>>> getEffectiveRangesAsync( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final Mono<ValueHolder<PartitionKeyRange>> getPkRangeTask = routingMapProvider .tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, false, null) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return routingMapProvider.tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, true, null); } else { return Mono.just(pkRangeHolder); } }) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return Mono.error( new PartitionKeyRangeGoneException( String.format( "The PartitionKeyRangeId: \"%s\" is not valid for the current " + "container %s .", partitionKeyRangeId, containerRid) )); } else { return Mono.just(pkRangeHolder); } }); return getPkRangeTask.flatMap((pkRangeHolder) -> { final ArrayList<Range<String>> temp = new ArrayList<>(); if (pkRangeHolder != null) { temp.add(pkRangeHolder.v.toRange()); } return Mono.just((UnmodifiableList<Range<String>>)UnmodifiableList.unmodifiableList(temp)); }); } @Override public Mono<UnmodifiableList<String>> getPartitionKeyRangesAsync( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final ArrayList<String> temp = new ArrayList<>(); temp.add(this.partitionKeyRangeId); return Mono.just( (UnmodifiableList<String>)UnmodifiableList.unmodifiableList(temp)); } public void populatePropertyBag() { super.populatePropertyBag(); if (this.partitionKeyRangeId != null) { setProperty( this, Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID, this.partitionKeyRangeId); } } @Override public String toString() { return this.partitionKeyRangeId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FeedRangePartitionKeyRangeImpl that = (FeedRangePartitionKeyRangeImpl) o; return Objects.equals(this.partitionKeyRangeId, that.partitionKeyRangeId); } @Override public int hashCode() { return Objects.hash(partitionKeyRangeId); } }
class FeedRangePartitionKeyRangeImpl extends FeedRangeInternal { private final String partitionKeyRangeId; private final PartitionKeyRangeIdentity partitionKeyRangeIdentity; public String getPartitionKeyRangeId() { return this.partitionKeyRangeId; } public PartitionKeyRangeIdentity getPartitionKeyRangeIdentity() { return this.partitionKeyRangeIdentity; } @Override public void accept(final FeedRangeVisitor visitor) { checkNotNull(visitor, "Argument 'visitor' must not be null"); visitor.visit(this); } @Override public <TInput> void accept(GenericFeedRangeVisitor<TInput> visitor, TInput input) { checkNotNull(visitor, "Argument 'visitor' must not be null"); visitor.visit(this, input); } @Override public <T> Mono<T> accept(final FeedRangeAsyncVisitor<T> visitor) { checkNotNull(visitor, "Argument 'visitor' must not be null"); return visitor.visit(this); } @Override public Mono<UnmodifiableList<Range<String>>> getEffectiveRanges( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final Mono<ValueHolder<PartitionKeyRange>> getPkRangeTask = routingMapProvider .tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, false, null) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return routingMapProvider.tryGetPartitionKeyRangeByIdAsync( null, containerRid, partitionKeyRangeId, true, null); } else { return Mono.just(pkRangeHolder); } }) .flatMap((pkRangeHolder) -> { if (pkRangeHolder.v == null) { return Mono.error( new PartitionKeyRangeGoneException( String.format( "The PartitionKeyRangeId: \"%s\" is not valid for the current " + "container %s .", partitionKeyRangeId, containerRid) )); } else { return Mono.just(pkRangeHolder); } }); return getPkRangeTask.flatMap((pkRangeHolder) -> { final ArrayList<Range<String>> temp = new ArrayList<>(); if (pkRangeHolder != null) { temp.add(pkRangeHolder.v.toRange()); } return Mono.just((UnmodifiableList<Range<String>>)UnmodifiableList.unmodifiableList(temp)); }); } @Override public Mono<UnmodifiableList<String>> getPartitionKeyRanges( final IRoutingMapProvider routingMapProvider, final String containerRid, final PartitionKeyDefinition partitionKeyDefinition) { final ArrayList<String> temp = new ArrayList<>(); temp.add(this.partitionKeyRangeId); return Mono.just( (UnmodifiableList<String>)UnmodifiableList.unmodifiableList(temp)); } public void populatePropertyBag() { super.populatePropertyBag(); if (this.partitionKeyRangeId != null) { setProperty( this, Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID, this.partitionKeyRangeId); } } @Override public String toString() { return this.partitionKeyRangeId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FeedRangePartitionKeyRangeImpl that = (FeedRangePartitionKeyRangeImpl) o; return Objects.equals(this.partitionKeyRangeId, that.partitionKeyRangeId); } @Override public int hashCode() { return Objects.hash(partitionKeyRangeId); } }
Talked offline, we're following `BlobClientBuilder`'s example now with a last one wins logic, and additionally info log that the previous credential got overridden.
private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.credential != null) { return new HmacAuthenticationPolicy(this.credential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } }
new IllegalArgumentException("Missing credential information while building a client."));
private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null && this.accessKeyCredential != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); } if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.accessKeyCredential != null) { return new HmacAuthenticationPolicy(this.accessKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } }
class CommunicationIdentityClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_ADMINISTRATION_PROPERTIES = "azure-communication-administration.properties"; private final ClientLogger logger = new ClientLogger(CommunicationIdentityClientBuilder.class); private String endpoint; private CommunicationClientCredential credential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private Configuration configuration; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_ADMINISTRATION_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationIdentityClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CommunicationIdentityClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); return this; } /** * Set credential to use * * @param accessKey access key for initalizing CommunicationClientCredential * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder accessKey(String accessKey) { Objects.requireNonNull(accessKey, "'accessKey' cannot be null."); this.credential = new CommunicationClientCredential(accessKey); return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); ConnectionString connectionStringObject = new ConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .accessKey(accessKey); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationIdentityClientBuilder object */ public CommunicationIdentityClientBuilder configuration(Configuration configuration) { this.configuration = Objects.requireNonNull(configuration, "'configuration' cannot be null."); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationIdentityClientBuilder object */ public CommunicationIdentityClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link CommunicationIdentityServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationIdentityServiceVersion} of the service to be used when making requests. * @return the updated CommunicationIdentityClientBuilder object */ public CommunicationIdentityClientBuilder serviceVersion(CommunicationIdentityServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationIdentityAsyncClient instance */ public CommunicationIdentityAsyncClient buildAsyncClient() { return new CommunicationIdentityAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationIdentityClient instance */ public CommunicationIdentityClient buildClient() { return new CommunicationIdentityClient(buildAsyncClient()); } private CommunicationIdentityClientImpl createServiceImpl() { Objects.requireNonNull(endpoint); HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationIdentityClientImplBuilder clientBuilder = new CommunicationIdentityClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); policies.add(authorizationPolicy); applyRequiredPolicies(policies); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, configuration)); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
class CommunicationIdentityClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_ADMINISTRATION_PROPERTIES = "azure-communication-administration.properties"; private final ClientLogger logger = new ClientLogger(CommunicationIdentityClientBuilder.class); private String endpoint; private CommunicationClientCredential accessKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private Configuration configuration; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_ADMINISTRATION_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationIdentityClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CommunicationIdentityClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); return this; } /** * Set credential to use * * @param accessKey access key for initalizing CommunicationClientCredential * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder accessKey(String accessKey) { Objects.requireNonNull(accessKey, "'accessKey' cannot be null."); this.accessKeyCredential = new CommunicationClientCredential(accessKey); return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); ConnectionString connectionStringObject = new ConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .accessKey(accessKey); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationIdentityClientBuilder */ public CommunicationIdentityClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationIdentityClientBuilder object */ public CommunicationIdentityClientBuilder configuration(Configuration configuration) { this.configuration = Objects.requireNonNull(configuration, "'configuration' cannot be null."); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationIdentityClientBuilder object */ public CommunicationIdentityClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link CommunicationIdentityServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationIdentityServiceVersion} of the service to be used when making requests. * @return the updated CommunicationIdentityClientBuilder object */ public CommunicationIdentityClientBuilder serviceVersion(CommunicationIdentityServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationIdentityAsyncClient instance */ public CommunicationIdentityAsyncClient buildAsyncClient() { return new CommunicationIdentityAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationIdentityClient instance */ public CommunicationIdentityClient buildClient() { return new CommunicationIdentityClient(buildAsyncClient()); } private CommunicationIdentityClientImpl createServiceImpl() { Objects.requireNonNull(endpoint); HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationIdentityClientImplBuilder clientBuilder = new CommunicationIdentityClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); policies.add(authorizationPolicy); applyRequiredPolicies(policies); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, configuration)); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
do you think creating a github issue and putting it here will help to keep track of this?
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(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()); assertNull(receipt2Pages.stream().findFirst().get().getLines()); 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()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); }
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(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().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()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); }
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 INVOICE_PDF = "Invoice_1.pdf"; static final String MULTIPAGE_VENDOR_INVOICE_PDF = "multipage_vendor_invoice.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"); static final List<String> INVOICE_FIELDS = Arrays.asList("CustomerAddressRecipient", "InvoiceId", "VendorName", "VendorAddress", "CustomerAddress", "CustomerName", "InvoiceTotal", "DueDate", "InvoiceDate"); enum PrebuiltType { RECEIPT, BUSINESS_CARD, INVOICE } Duration durationTestMode; public static final String INVOICE_TEST_URL = "https: + "feature/formrecognizer_v2.1-preview2/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/" + "sample_files/Test/Invoice_1.pdf"; /** * 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_POLL_INTERVAL; } } 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 AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_FORM_RECOGNIZER_API_KEY"))); } 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()); validateBoundingBoxData(expectedTable.getBoundingBox(), actualTable.getFieldBoundingBox()); } } 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 validateFormSelectionMarkData(List<SelectionMark> expectedMarks, List<FormSelectionMark> actualMarks, int pageNumber) { for (int i = 0; i < actualMarks.size(); i++) { final SelectionMark expectedMark = expectedMarks.get(i); final FormSelectionMark actualMark = actualMarks.get(i); assertEquals(expectedMark.getState().toString(), actualMark.getState().toString()); validateBoundingBoxData(expectedMark.getBoundingBox(), actualMark.getBoundingBox()); assertNull(actualMark.getText()); assertEquals(pageNumber, actualMark.getPageNumber()); } } 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 recognizeContentWithSelectionMarks(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 recognizeContentWithSelectionMarksFromUrl(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 recognizeCustomFormLabeledDataWithSelectionMark(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 recognizeCustomFormUrlLabeledDataWithSelectionMark(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()); } validateFormSelectionMarkData(readResult.getSelectionMarks(), actualFormPage.getSelectionMarks(), readResult.getPage()); 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, PrebuiltType 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)) { assertEquals("prebuilt:businesscard", actualForm.getFormType()); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else if (RECEIPT.equals(prebuiltType)) { assertEquals("prebuilt:receipt", actualForm.getFormType()); 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); }); } else if (INVOICE.equals(prebuiltType)) { assertEquals("prebuilt:invoice", actualForm.getFormType()); INVOICE_FIELDS.forEach(invoiceField -> { final Map<String, FormField> actualRecognizedInvoiceFields = actualForm.getFields(); Map<String, FieldValue> expectedInvoiceFields = rawDocumentResult.getFields(); validateFieldValueTransforms(expectedInvoiceFields.get(invoiceField), actualRecognizedInvoiceFields.get(invoiceField), rawReadResults, includeFieldElements); }); } else { throw new RuntimeException("prebuilt type not supported"); } } } 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 testingContainerUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } 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 beginSelectionMarkTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getSelectionMarkTrainingSasUri(), 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 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()); FormField contactNameField = businessCard1Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactNameField.getValueData().getPageNumber(), 1); assertEquals(contactNameField.getValueData().getText(), "JOHN SINGER"); 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()); FormField contactName2Field = businessCard2Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactName2Field.getValueData().getPageNumber(), 2); assertEquals(contactName2Field.getValueData().getText(), "Dr. Avery Smith"); } static void validateMultipageInvoiceData(List<RecognizedForm> recognizedInvoices) { assertEquals(1, recognizedInvoices.size()); RecognizedForm recognizedForm = recognizedInvoices.get(0); assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(2, recognizedForm.getPageRange().getLastPageNumber()); Map<String, FormField> recognizedInvoiceFields = recognizedForm.getFields(); final FormField remittanceAddressRecipient = recognizedInvoiceFields.get("RemittanceAddressRecipient"); assertEquals("Contoso Ltd.", remittanceAddressRecipient.getValue().asString()); assertEquals(1, remittanceAddressRecipient.getValueData().getPageNumber()); final FormField remittanceAddress = recognizedInvoiceFields.get("RemittanceAddress"); assertEquals("2345 Dogwood Lane Birch, Kansas 98123", remittanceAddress.getValue().asString()); assertEquals(1, remittanceAddress.getValueData().getPageNumber()); final FormField vendorName = recognizedInvoiceFields.get("VendorName"); assertEquals("Southridge Video", vendorName.getValue().asString()); assertEquals(2, vendorName.getValueData().getPageNumber()); assertEquals(2, recognizedForm.getPages().size()); } 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); } } private String getSelectionMarkTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_SELECTION_MARK_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 RecordedData copyRecordedData = interceptorManager.getRecordedData(); final NetworkCallRecord networkCallRecord = copyRecordedData.findFirstAndRemoveNetworkCall(record -> true); copyRecordedData.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 INVOICE_PDF = "Invoice_1.pdf"; static final String MULTIPAGE_VENDOR_INVOICE_PDF = "multipage_vendor_invoice.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"); static final List<String> INVOICE_FIELDS = Arrays.asList("CustomerAddressRecipient", "InvoiceId", "VendorName", "VendorAddress", "CustomerAddress", "CustomerName", "InvoiceTotal", "DueDate", "InvoiceDate"); enum PrebuiltType { RECEIPT, BUSINESS_CARD, INVOICE } Duration durationTestMode; public static final String INVOICE_TEST_URL = "https: + "feature/formrecognizer_v2.1-preview2/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/" + "sample_files/Test/Invoice_1.pdf"; /** * 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_POLL_INTERVAL; } } 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 AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } 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()); validateBoundingBoxData(expectedTable.getBoundingBox(), actualTable.getFieldBoundingBox()); } } 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 validateFormSelectionMarkData(List<SelectionMark> expectedMarks, List<FormSelectionMark> actualMarks, int pageNumber) { for (int i = 0; i < actualMarks.size(); i++) { final SelectionMark expectedMark = expectedMarks.get(i); final FormSelectionMark actualMark = actualMarks.get(i); assertEquals(expectedMark.getState().toString(), actualMark.getState().toString()); validateBoundingBoxData(expectedMark.getBoundingBox(), actualMark.getBoundingBox()); assertNull(actualMark.getText()); assertEquals(pageNumber, actualMark.getPageNumber()); } } 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 recognizeContentWithSelectionMarks(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 recognizeContentWithSelectionMarksFromUrl(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 recognizeCustomFormLabeledDataWithSelectionMark(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 recognizeCustomFormUrlLabeledDataWithSelectionMark(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()); } validateFormSelectionMarkData(readResult.getSelectionMarks(), actualFormPage.getSelectionMarks(), readResult.getPage()); 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, PrebuiltType 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)) { assertEquals("prebuilt:businesscard", actualForm.getFormType()); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else if (RECEIPT.equals(prebuiltType)) { assertEquals("prebuilt:receipt", actualForm.getFormType()); 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); }); } else if (INVOICE.equals(prebuiltType)) { assertEquals("prebuilt:invoice", actualForm.getFormType()); INVOICE_FIELDS.forEach(invoiceField -> { final Map<String, FormField> actualRecognizedInvoiceFields = actualForm.getFields(); Map<String, FieldValue> expectedInvoiceFields = rawDocumentResult.getFields(); validateFieldValueTransforms(expectedInvoiceFields.get(invoiceField), actualRecognizedInvoiceFields.get(invoiceField), rawReadResults, includeFieldElements); }); } else { throw new RuntimeException("prebuilt type not supported"); } } } 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 testingContainerUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } 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 beginSelectionMarkTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getSelectionMarkTrainingSasUri(), 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 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()); FormField contactNameField = businessCard1Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactNameField.getValueData().getPageNumber(), 1); assertEquals(contactNameField.getValueData().getText(), "JOHN SINGER"); 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()); FormField contactName2Field = businessCard2Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactName2Field.getValueData().getPageNumber(), 2); assertEquals(contactName2Field.getValueData().getText(), "Dr. Avery Smith"); } static void validateMultipageInvoiceData(List<RecognizedForm> recognizedInvoices) { assertEquals(1, recognizedInvoices.size()); RecognizedForm recognizedForm = recognizedInvoices.get(0); assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(2, recognizedForm.getPageRange().getLastPageNumber()); Map<String, FormField> recognizedInvoiceFields = recognizedForm.getFields(); final FormField remittanceAddressRecipient = recognizedInvoiceFields.get("RemittanceAddressRecipient"); assertEquals("Contoso Ltd.", remittanceAddressRecipient.getValue().asString()); assertEquals(1, remittanceAddressRecipient.getValueData().getPageNumber()); final FormField remittanceAddress = recognizedInvoiceFields.get("RemittanceAddress"); assertEquals("2345 Dogwood Lane Birch, Kansas 98123", remittanceAddress.getValue().asString()); assertEquals(1, remittanceAddress.getValueData().getPageNumber()); final FormField vendorName = recognizedInvoiceFields.get("VendorName"); assertEquals("Southridge Video", vendorName.getValue().asString()); assertEquals(2, vendorName.getValueData().getPageNumber()); assertEquals(2, recognizedForm.getPages().size()); } 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); } } private String getSelectionMarkTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_SELECTION_MARK_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 networkCallRecord1 = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(networkCallRecord -> { URL url = null; try { url = new URL(networkCallRecord.getUri()); } catch (MalformedURLException e) { assertFalse(false, e.getMessage()); } if (url.getQuery() != null) { String[] params = url.getQuery().split("&"); for (String param : params) { String name = param.split("=")[0]; String queryValue = param.split("=")[1]; if (name.equals(requestParam) && value.equals(queryValue)) { return true; } } return false; } return false; }); assertNotNull(networkCallRecord1); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord1); } }
ohh interesting. is it not mandatory in the swagger? or what changed? a regression?
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(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()); assertNull(receipt2Pages.stream().findFirst().get().getLines()); 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()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); }
assertEquals(1, receipt2Pages.size());
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(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().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()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); }
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 INVOICE_PDF = "Invoice_1.pdf"; static final String MULTIPAGE_VENDOR_INVOICE_PDF = "multipage_vendor_invoice.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"); static final List<String> INVOICE_FIELDS = Arrays.asList("CustomerAddressRecipient", "InvoiceId", "VendorName", "VendorAddress", "CustomerAddress", "CustomerName", "InvoiceTotal", "DueDate", "InvoiceDate"); enum PrebuiltType { RECEIPT, BUSINESS_CARD, INVOICE } Duration durationTestMode; public static final String INVOICE_TEST_URL = "https: + "feature/formrecognizer_v2.1-preview2/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/" + "sample_files/Test/Invoice_1.pdf"; /** * 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_POLL_INTERVAL; } } 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 AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_FORM_RECOGNIZER_API_KEY"))); } 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()); validateBoundingBoxData(expectedTable.getBoundingBox(), actualTable.getFieldBoundingBox()); } } 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 validateFormSelectionMarkData(List<SelectionMark> expectedMarks, List<FormSelectionMark> actualMarks, int pageNumber) { for (int i = 0; i < actualMarks.size(); i++) { final SelectionMark expectedMark = expectedMarks.get(i); final FormSelectionMark actualMark = actualMarks.get(i); assertEquals(expectedMark.getState().toString(), actualMark.getState().toString()); validateBoundingBoxData(expectedMark.getBoundingBox(), actualMark.getBoundingBox()); assertNull(actualMark.getText()); assertEquals(pageNumber, actualMark.getPageNumber()); } } 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 recognizeContentWithSelectionMarks(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 recognizeContentWithSelectionMarksFromUrl(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 recognizeCustomFormLabeledDataWithSelectionMark(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 recognizeCustomFormUrlLabeledDataWithSelectionMark(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()); } validateFormSelectionMarkData(readResult.getSelectionMarks(), actualFormPage.getSelectionMarks(), readResult.getPage()); 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, PrebuiltType 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)) { assertEquals("prebuilt:businesscard", actualForm.getFormType()); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else if (RECEIPT.equals(prebuiltType)) { assertEquals("prebuilt:receipt", actualForm.getFormType()); 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); }); } else if (INVOICE.equals(prebuiltType)) { assertEquals("prebuilt:invoice", actualForm.getFormType()); INVOICE_FIELDS.forEach(invoiceField -> { final Map<String, FormField> actualRecognizedInvoiceFields = actualForm.getFields(); Map<String, FieldValue> expectedInvoiceFields = rawDocumentResult.getFields(); validateFieldValueTransforms(expectedInvoiceFields.get(invoiceField), actualRecognizedInvoiceFields.get(invoiceField), rawReadResults, includeFieldElements); }); } else { throw new RuntimeException("prebuilt type not supported"); } } } 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 testingContainerUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } 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 beginSelectionMarkTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getSelectionMarkTrainingSasUri(), 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 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()); FormField contactNameField = businessCard1Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactNameField.getValueData().getPageNumber(), 1); assertEquals(contactNameField.getValueData().getText(), "JOHN SINGER"); 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()); FormField contactName2Field = businessCard2Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactName2Field.getValueData().getPageNumber(), 2); assertEquals(contactName2Field.getValueData().getText(), "Dr. Avery Smith"); } static void validateMultipageInvoiceData(List<RecognizedForm> recognizedInvoices) { assertEquals(1, recognizedInvoices.size()); RecognizedForm recognizedForm = recognizedInvoices.get(0); assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(2, recognizedForm.getPageRange().getLastPageNumber()); Map<String, FormField> recognizedInvoiceFields = recognizedForm.getFields(); final FormField remittanceAddressRecipient = recognizedInvoiceFields.get("RemittanceAddressRecipient"); assertEquals("Contoso Ltd.", remittanceAddressRecipient.getValue().asString()); assertEquals(1, remittanceAddressRecipient.getValueData().getPageNumber()); final FormField remittanceAddress = recognizedInvoiceFields.get("RemittanceAddress"); assertEquals("2345 Dogwood Lane Birch, Kansas 98123", remittanceAddress.getValue().asString()); assertEquals(1, remittanceAddress.getValueData().getPageNumber()); final FormField vendorName = recognizedInvoiceFields.get("VendorName"); assertEquals("Southridge Video", vendorName.getValue().asString()); assertEquals(2, vendorName.getValueData().getPageNumber()); assertEquals(2, recognizedForm.getPages().size()); } 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); } } private String getSelectionMarkTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_SELECTION_MARK_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 RecordedData copyRecordedData = interceptorManager.getRecordedData(); final NetworkCallRecord networkCallRecord = copyRecordedData.findFirstAndRemoveNetworkCall(record -> true); copyRecordedData.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 INVOICE_PDF = "Invoice_1.pdf"; static final String MULTIPAGE_VENDOR_INVOICE_PDF = "multipage_vendor_invoice.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"); static final List<String> INVOICE_FIELDS = Arrays.asList("CustomerAddressRecipient", "InvoiceId", "VendorName", "VendorAddress", "CustomerAddress", "CustomerName", "InvoiceTotal", "DueDate", "InvoiceDate"); enum PrebuiltType { RECEIPT, BUSINESS_CARD, INVOICE } Duration durationTestMode; public static final String INVOICE_TEST_URL = "https: + "feature/formrecognizer_v2.1-preview2/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/" + "sample_files/Test/Invoice_1.pdf"; /** * 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_POLL_INTERVAL; } } 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 AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } 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()); validateBoundingBoxData(expectedTable.getBoundingBox(), actualTable.getFieldBoundingBox()); } } 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 validateFormSelectionMarkData(List<SelectionMark> expectedMarks, List<FormSelectionMark> actualMarks, int pageNumber) { for (int i = 0; i < actualMarks.size(); i++) { final SelectionMark expectedMark = expectedMarks.get(i); final FormSelectionMark actualMark = actualMarks.get(i); assertEquals(expectedMark.getState().toString(), actualMark.getState().toString()); validateBoundingBoxData(expectedMark.getBoundingBox(), actualMark.getBoundingBox()); assertNull(actualMark.getText()); assertEquals(pageNumber, actualMark.getPageNumber()); } } 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 recognizeContentWithSelectionMarks(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 recognizeContentWithSelectionMarksFromUrl(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 recognizeCustomFormLabeledDataWithSelectionMark(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 recognizeCustomFormUrlLabeledDataWithSelectionMark(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()); } validateFormSelectionMarkData(readResult.getSelectionMarks(), actualFormPage.getSelectionMarks(), readResult.getPage()); 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, PrebuiltType 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)) { assertEquals("prebuilt:businesscard", actualForm.getFormType()); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else if (RECEIPT.equals(prebuiltType)) { assertEquals("prebuilt:receipt", actualForm.getFormType()); 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); }); } else if (INVOICE.equals(prebuiltType)) { assertEquals("prebuilt:invoice", actualForm.getFormType()); INVOICE_FIELDS.forEach(invoiceField -> { final Map<String, FormField> actualRecognizedInvoiceFields = actualForm.getFields(); Map<String, FieldValue> expectedInvoiceFields = rawDocumentResult.getFields(); validateFieldValueTransforms(expectedInvoiceFields.get(invoiceField), actualRecognizedInvoiceFields.get(invoiceField), rawReadResults, includeFieldElements); }); } else { throw new RuntimeException("prebuilt type not supported"); } } } 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 testingContainerUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } 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 beginSelectionMarkTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getSelectionMarkTrainingSasUri(), 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 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()); FormField contactNameField = businessCard1Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactNameField.getValueData().getPageNumber(), 1); assertEquals(contactNameField.getValueData().getText(), "JOHN SINGER"); 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()); FormField contactName2Field = businessCard2Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactName2Field.getValueData().getPageNumber(), 2); assertEquals(contactName2Field.getValueData().getText(), "Dr. Avery Smith"); } static void validateMultipageInvoiceData(List<RecognizedForm> recognizedInvoices) { assertEquals(1, recognizedInvoices.size()); RecognizedForm recognizedForm = recognizedInvoices.get(0); assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(2, recognizedForm.getPageRange().getLastPageNumber()); Map<String, FormField> recognizedInvoiceFields = recognizedForm.getFields(); final FormField remittanceAddressRecipient = recognizedInvoiceFields.get("RemittanceAddressRecipient"); assertEquals("Contoso Ltd.", remittanceAddressRecipient.getValue().asString()); assertEquals(1, remittanceAddressRecipient.getValueData().getPageNumber()); final FormField remittanceAddress = recognizedInvoiceFields.get("RemittanceAddress"); assertEquals("2345 Dogwood Lane Birch, Kansas 98123", remittanceAddress.getValue().asString()); assertEquals(1, remittanceAddress.getValueData().getPageNumber()); final FormField vendorName = recognizedInvoiceFields.get("VendorName"); assertEquals("Southridge Video", vendorName.getValue().asString()); assertEquals(2, vendorName.getValueData().getPageNumber()); assertEquals(2, recognizedForm.getPages().size()); } 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); } } private String getSelectionMarkTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_SELECTION_MARK_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 networkCallRecord1 = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(networkCallRecord -> { URL url = null; try { url = new URL(networkCallRecord.getUri()); } catch (MalformedURLException e) { assertFalse(false, e.getMessage()); } if (url.getQuery() != null) { String[] params = url.getQuery().split("&"); for (String param : params) { String name = param.split("=")[0]; String queryValue = param.split("=")[1]; if (name.equals(requestParam) && value.equals(queryValue)) { return true; } } return false; } return false; }); assertNotNull(networkCallRecord1); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord1); } }
ohh yeah I saw this too. NM
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(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()); assertNull(receipt2Pages.stream().findFirst().get().getLines()); 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()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); }
assertEquals(1, receipt2Pages.size());
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(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().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()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); }
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 INVOICE_PDF = "Invoice_1.pdf"; static final String MULTIPAGE_VENDOR_INVOICE_PDF = "multipage_vendor_invoice.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"); static final List<String> INVOICE_FIELDS = Arrays.asList("CustomerAddressRecipient", "InvoiceId", "VendorName", "VendorAddress", "CustomerAddress", "CustomerName", "InvoiceTotal", "DueDate", "InvoiceDate"); enum PrebuiltType { RECEIPT, BUSINESS_CARD, INVOICE } Duration durationTestMode; public static final String INVOICE_TEST_URL = "https: + "feature/formrecognizer_v2.1-preview2/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/" + "sample_files/Test/Invoice_1.pdf"; /** * 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_POLL_INTERVAL; } } 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 AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_FORM_RECOGNIZER_API_KEY"))); } 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()); validateBoundingBoxData(expectedTable.getBoundingBox(), actualTable.getFieldBoundingBox()); } } 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 validateFormSelectionMarkData(List<SelectionMark> expectedMarks, List<FormSelectionMark> actualMarks, int pageNumber) { for (int i = 0; i < actualMarks.size(); i++) { final SelectionMark expectedMark = expectedMarks.get(i); final FormSelectionMark actualMark = actualMarks.get(i); assertEquals(expectedMark.getState().toString(), actualMark.getState().toString()); validateBoundingBoxData(expectedMark.getBoundingBox(), actualMark.getBoundingBox()); assertNull(actualMark.getText()); assertEquals(pageNumber, actualMark.getPageNumber()); } } 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 recognizeContentWithSelectionMarks(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 recognizeContentWithSelectionMarksFromUrl(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 recognizeCustomFormLabeledDataWithSelectionMark(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 recognizeCustomFormUrlLabeledDataWithSelectionMark(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()); } validateFormSelectionMarkData(readResult.getSelectionMarks(), actualFormPage.getSelectionMarks(), readResult.getPage()); 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, PrebuiltType 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)) { assertEquals("prebuilt:businesscard", actualForm.getFormType()); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else if (RECEIPT.equals(prebuiltType)) { assertEquals("prebuilt:receipt", actualForm.getFormType()); 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); }); } else if (INVOICE.equals(prebuiltType)) { assertEquals("prebuilt:invoice", actualForm.getFormType()); INVOICE_FIELDS.forEach(invoiceField -> { final Map<String, FormField> actualRecognizedInvoiceFields = actualForm.getFields(); Map<String, FieldValue> expectedInvoiceFields = rawDocumentResult.getFields(); validateFieldValueTransforms(expectedInvoiceFields.get(invoiceField), actualRecognizedInvoiceFields.get(invoiceField), rawReadResults, includeFieldElements); }); } else { throw new RuntimeException("prebuilt type not supported"); } } } 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 testingContainerUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } 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 beginSelectionMarkTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getSelectionMarkTrainingSasUri(), 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 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()); FormField contactNameField = businessCard1Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactNameField.getValueData().getPageNumber(), 1); assertEquals(contactNameField.getValueData().getText(), "JOHN SINGER"); 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()); FormField contactName2Field = businessCard2Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactName2Field.getValueData().getPageNumber(), 2); assertEquals(contactName2Field.getValueData().getText(), "Dr. Avery Smith"); } static void validateMultipageInvoiceData(List<RecognizedForm> recognizedInvoices) { assertEquals(1, recognizedInvoices.size()); RecognizedForm recognizedForm = recognizedInvoices.get(0); assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(2, recognizedForm.getPageRange().getLastPageNumber()); Map<String, FormField> recognizedInvoiceFields = recognizedForm.getFields(); final FormField remittanceAddressRecipient = recognizedInvoiceFields.get("RemittanceAddressRecipient"); assertEquals("Contoso Ltd.", remittanceAddressRecipient.getValue().asString()); assertEquals(1, remittanceAddressRecipient.getValueData().getPageNumber()); final FormField remittanceAddress = recognizedInvoiceFields.get("RemittanceAddress"); assertEquals("2345 Dogwood Lane Birch, Kansas 98123", remittanceAddress.getValue().asString()); assertEquals(1, remittanceAddress.getValueData().getPageNumber()); final FormField vendorName = recognizedInvoiceFields.get("VendorName"); assertEquals("Southridge Video", vendorName.getValue().asString()); assertEquals(2, vendorName.getValueData().getPageNumber()); assertEquals(2, recognizedForm.getPages().size()); } 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); } } private String getSelectionMarkTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_SELECTION_MARK_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 RecordedData copyRecordedData = interceptorManager.getRecordedData(); final NetworkCallRecord networkCallRecord = copyRecordedData.findFirstAndRemoveNetworkCall(record -> true); copyRecordedData.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 INVOICE_PDF = "Invoice_1.pdf"; static final String MULTIPAGE_VENDOR_INVOICE_PDF = "multipage_vendor_invoice.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"); static final List<String> INVOICE_FIELDS = Arrays.asList("CustomerAddressRecipient", "InvoiceId", "VendorName", "VendorAddress", "CustomerAddress", "CustomerName", "InvoiceTotal", "DueDate", "InvoiceDate"); enum PrebuiltType { RECEIPT, BUSINESS_CARD, INVOICE } Duration durationTestMode; public static final String INVOICE_TEST_URL = "https: + "feature/formrecognizer_v2.1-preview2/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/" + "sample_files/Test/Invoice_1.pdf"; /** * 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_POLL_INTERVAL; } } 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 AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } 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()); validateBoundingBoxData(expectedTable.getBoundingBox(), actualTable.getFieldBoundingBox()); } } 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 validateFormSelectionMarkData(List<SelectionMark> expectedMarks, List<FormSelectionMark> actualMarks, int pageNumber) { for (int i = 0; i < actualMarks.size(); i++) { final SelectionMark expectedMark = expectedMarks.get(i); final FormSelectionMark actualMark = actualMarks.get(i); assertEquals(expectedMark.getState().toString(), actualMark.getState().toString()); validateBoundingBoxData(expectedMark.getBoundingBox(), actualMark.getBoundingBox()); assertNull(actualMark.getText()); assertEquals(pageNumber, actualMark.getPageNumber()); } } 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 recognizeContentWithSelectionMarks(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 recognizeContentWithSelectionMarksFromUrl(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 recognizeCustomFormLabeledDataWithSelectionMark(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 recognizeCustomFormUrlLabeledDataWithSelectionMark(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()); } validateFormSelectionMarkData(readResult.getSelectionMarks(), actualFormPage.getSelectionMarks(), readResult.getPage()); 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, PrebuiltType 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)) { assertEquals("prebuilt:businesscard", actualForm.getFormType()); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else if (RECEIPT.equals(prebuiltType)) { assertEquals("prebuilt:receipt", actualForm.getFormType()); 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); }); } else if (INVOICE.equals(prebuiltType)) { assertEquals("prebuilt:invoice", actualForm.getFormType()); INVOICE_FIELDS.forEach(invoiceField -> { final Map<String, FormField> actualRecognizedInvoiceFields = actualForm.getFields(); Map<String, FieldValue> expectedInvoiceFields = rawDocumentResult.getFields(); validateFieldValueTransforms(expectedInvoiceFields.get(invoiceField), actualRecognizedInvoiceFields.get(invoiceField), rawReadResults, includeFieldElements); }); } else { throw new RuntimeException("prebuilt type not supported"); } } } 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 testingContainerUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } 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 beginSelectionMarkTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getSelectionMarkTrainingSasUri(), 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 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()); FormField contactNameField = businessCard1Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactNameField.getValueData().getPageNumber(), 1); assertEquals(contactNameField.getValueData().getText(), "JOHN SINGER"); 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()); FormField contactName2Field = businessCard2Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactName2Field.getValueData().getPageNumber(), 2); assertEquals(contactName2Field.getValueData().getText(), "Dr. Avery Smith"); } static void validateMultipageInvoiceData(List<RecognizedForm> recognizedInvoices) { assertEquals(1, recognizedInvoices.size()); RecognizedForm recognizedForm = recognizedInvoices.get(0); assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(2, recognizedForm.getPageRange().getLastPageNumber()); Map<String, FormField> recognizedInvoiceFields = recognizedForm.getFields(); final FormField remittanceAddressRecipient = recognizedInvoiceFields.get("RemittanceAddressRecipient"); assertEquals("Contoso Ltd.", remittanceAddressRecipient.getValue().asString()); assertEquals(1, remittanceAddressRecipient.getValueData().getPageNumber()); final FormField remittanceAddress = recognizedInvoiceFields.get("RemittanceAddress"); assertEquals("2345 Dogwood Lane Birch, Kansas 98123", remittanceAddress.getValue().asString()); assertEquals(1, remittanceAddress.getValueData().getPageNumber()); final FormField vendorName = recognizedInvoiceFields.get("VendorName"); assertEquals("Southridge Video", vendorName.getValue().asString()); assertEquals(2, vendorName.getValueData().getPageNumber()); assertEquals(2, recognizedForm.getPages().size()); } 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); } } private String getSelectionMarkTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_SELECTION_MARK_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 networkCallRecord1 = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(networkCallRecord -> { URL url = null; try { url = new URL(networkCallRecord.getUri()); } catch (MalformedURLException e) { assertFalse(false, e.getMessage()); } if (url.getQuery() != null) { String[] params = url.getQuery().split("&"); for (String param : params) { String name = param.split("=")[0]; String queryValue = param.split("=")[1]; if (name.equals(requestParam) && value.equals(queryValue)) { return true; } } return false; } return false; }); assertNotNull(networkCallRecord1); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord1); } }
what happens if the field type is not ARRAY only?
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && (fieldValue.getPage() != null && fieldValue.getBoundingBox() != null && fieldValue.getText() != null)) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return setFormField(null, valueData, fieldValue, readResults); }) .collect(Collectors.toList()); }
if (ARRAY != fieldValue.getType()
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && (fieldValue.getPage() != null && fieldValue.getBoundingBox() != null && fieldValue.getText() != null)) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return setFormField(null, valueData, fieldValue, readResults); }) .collect(Collectors.toList()); }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> { FormTable formTable = new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber); FormTableHelper.setBoundingBox(formTable, toBoundingBox(dataTable.getBoundingBox())); return formTable; }) .collect(Collectors.toList()); } } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> { FormLine formLine = new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage())); FormLineHelper.setAppearance(formLine, getAppearance(textLine)); return formLine; }) .collect(Collectors.toList()); } /** * Private method to get the appearance from the service side text line object. * @param textLine The service side text line object. * @return the custom type Appearance model. */ private static Appearance getAppearance(TextLine textLine) { Style style = new Style(); if (textLine.getAppearance() != null) { if (textLine.getAppearance().getStyle() != null) { if (textLine.getAppearance().getStyle().getName() != null) { StyleHelper.setName(style, TextStyle.fromString(textLine.getAppearance().getStyle().getName().toString())); } StyleHelper.setConfidence(style, textLine.getAppearance().getStyle().getConfidence()); } } Appearance appearance = new Appearance(); AppearanceHelper.setStyle(appearance, style); return appearance; } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = new ArrayList<>(); List<FormElement> formValueContentList = new ArrayList<>(); if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); FormLineHelper.setAppearance(lineElement, getAppearance(textLine)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> { FormTable formTable = new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber); FormTableHelper.setBoundingBox(formTable, toBoundingBox(dataTable.getBoundingBox())); return formTable; }) .collect(Collectors.toList()); } } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> { FormLine formLine = new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage())); FormLineHelper.setAppearance(formLine, getAppearance(textLine)); return formLine; }) .collect(Collectors.toList()); } /** * Private method to get the appearance from the service side text line object. * @param textLine The service side text line object. * @return the custom type Appearance model. */ private static Appearance getAppearance(TextLine textLine) { Style style = new Style(); if (textLine.getAppearance() != null) { if (textLine.getAppearance().getStyle() != null) { if (textLine.getAppearance().getStyle().getName() != null) { StyleHelper.setName(style, TextStyle.fromString(textLine.getAppearance().getStyle().getName().toString())); } StyleHelper.setConfidence(style, textLine.getAppearance().getStyle().getConfidence()); } } Appearance appearance = new Appearance(); AppearanceHelper.setStyle(appearance, style); return appearance; } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = new ArrayList<>(); List<FormElement> formValueContentList = new ArrayList<>(); if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); FormLineHelper.setAppearance(lineElement, getAppearance(textLine)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
They will have valueData except for the mentioned two cases.
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && (fieldValue.getPage() != null && fieldValue.getBoundingBox() != null && fieldValue.getText() != null)) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return setFormField(null, valueData, fieldValue, readResults); }) .collect(Collectors.toList()); }
if (ARRAY != fieldValue.getType()
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType() && (fieldValue.getPage() != null && fieldValue.getBoundingBox() != null && fieldValue.getText() != null)) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return setFormField(null, valueData, fieldValue, readResults); }) .collect(Collectors.toList()); }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> { FormTable formTable = new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber); FormTableHelper.setBoundingBox(formTable, toBoundingBox(dataTable.getBoundingBox())); return formTable; }) .collect(Collectors.toList()); } } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> { FormLine formLine = new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage())); FormLineHelper.setAppearance(formLine, getAppearance(textLine)); return formLine; }) .collect(Collectors.toList()); } /** * Private method to get the appearance from the service side text line object. * @param textLine The service side text line object. * @return the custom type Appearance model. */ private static Appearance getAppearance(TextLine textLine) { Style style = new Style(); if (textLine.getAppearance() != null) { if (textLine.getAppearance().getStyle() != null) { if (textLine.getAppearance().getStyle().getName() != null) { StyleHelper.setName(style, TextStyle.fromString(textLine.getAppearance().getStyle().getName().toString())); } StyleHelper.setConfidence(style, textLine.getAppearance().getStyle().getConfidence()); } } Appearance appearance = new Appearance(); AppearanceHelper.setStyle(appearance, style); return appearance; } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = new ArrayList<>(); List<FormElement> formValueContentList = new ArrayList<>(); if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); FormLineHelper.setAppearance(lineElement, getAppearance(textLine)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); RecognizedFormHelper.setFormTypeConfidence(recognizedForm, documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { RecognizedFormHelper.setModelId(recognizedForm, documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); RecognizedFormHelper.setModelId(recognizedForm, modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); if (pageResultItem != null) { perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } List<FormSelectionMark> perPageFormSelectionMarkList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getSelectionMarks())) { PageResult pageResultItem = pageResults.get(index); perPageFormSelectionMarkList = getReadResultFormSelectionMarks(readResultItem, pageResultItem.getPage()); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList, perPageFormSelectionMarkList)); })); return formPages; } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormSelectionMark}. * * @param readResultItem The per page text extraction item result returned by the service. * @param pageNumber The page number. * * @return A list of {@code FormSelectionMark}. */ static List<FormSelectionMark> getReadResultFormSelectionMarks(ReadResult readResultItem, int pageNumber) { return readResultItem.getSelectionMarks().stream() .map(selectionMark -> { final FormSelectionMark formSelectionMark = new FormSelectionMark( null, toBoundingBox(selectionMark.getBoundingBox()), pageNumber); final SelectionMarkState selectionMarkStateImpl = selectionMark.getState(); com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState; if (SelectionMarkState.SELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (SelectionMarkState.UNSELECTED.equals(selectionMarkStateImpl)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { throw LOGGER.logThrowableAsError(new RuntimeException( String.format("%s, unsupported selection mark state.", selectionMarkStateImpl))); } FormSelectionMarkHelper.setConfidence(formSelectionMark, selectionMark.getConfidence()); FormSelectionMarkHelper.setState(formSelectionMark, selectionMarkState); return formSelectionMark; }) .collect(Collectors.toList()); } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { if (pageResultItem.getTables() == null) { return new ArrayList<>(); } else { return pageResultItem.getTables().stream() .map(dataTable -> { FormTable formTable = new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber); FormTableHelper.setBoundingBox(formTable, toBoundingBox(dataTable.getBoundingBox())); return formTable; }) .collect(Collectors.toList()); } } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> { FormLine formLine = new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage())); FormLineHelper.setAppearance(formLine, getAppearance(textLine)); return formLine; }) .collect(Collectors.toList()); } /** * Private method to get the appearance from the service side text line object. * @param textLine The service side text line object. * @return the custom type Appearance model. */ private static Appearance getAppearance(TextLine textLine) { Style style = new Style(); if (textLine.getAppearance() != null) { if (textLine.getAppearance().getStyle() != null) { if (textLine.getAppearance().getStyle().getName() != null) { StyleHelper.setName(style, TextStyle.fromString(textLine.getAppearance().getStyle().getName().toString())); } StyleHelper.setConfidence(style, textLine.getAppearance().getStyle().getConfidence()); } } Appearance appearance = new Appearance(); AppearanceHelper.setStyle(appearance, style); return appearance; } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param valueData The value text of the field. * @param fieldValue The named field values returned by the service. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; case SELECTION_MARK: com.azure.ai.formrecognizer.models.SelectionMarkState selectionMarkState; final FieldValueSelectionMark fieldValueSelectionMarkState = fieldValue.getValueSelectionMark(); if (FieldValueSelectionMark.SELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.SELECTED; } else if (FieldValueSelectionMark.UNSELECTED.equals(fieldValueSelectionMarkState)) { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.UNSELECTED; } else { selectionMarkState = com.azure.ai.formrecognizer.models.SelectionMarkState.fromString( fieldValue.getText()); } value = new com.azure.ai.formrecognizer.models.FieldValue(selectionMarkState, FieldValueType.SELECTION_MARK_STATE); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * @param perPageSelectionMarkList The per page selection marks. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList, List<FormSelectionMark> perPageSelectionMarkList) { FormPage formPage = new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); FormPageHelper.setSelectionMarks(formPage, perPageSelectionMarkList); return formPage; } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = new ArrayList<>(); List<FormElement> formValueContentList = new ArrayList<>(); if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); FormLineHelper.setAppearance(lineElement, getAppearance(textLine)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
https://github.com/Azure/azure-sdk-for-java/issues/17661
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(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()); assertNull(receipt2Pages.stream().findFirst().get().getLines()); 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()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); }
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(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().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()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); }
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 INVOICE_PDF = "Invoice_1.pdf"; static final String MULTIPAGE_VENDOR_INVOICE_PDF = "multipage_vendor_invoice.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"); static final List<String> INVOICE_FIELDS = Arrays.asList("CustomerAddressRecipient", "InvoiceId", "VendorName", "VendorAddress", "CustomerAddress", "CustomerName", "InvoiceTotal", "DueDate", "InvoiceDate"); enum PrebuiltType { RECEIPT, BUSINESS_CARD, INVOICE } Duration durationTestMode; public static final String INVOICE_TEST_URL = "https: + "feature/formrecognizer_v2.1-preview2/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/" + "sample_files/Test/Invoice_1.pdf"; /** * 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_POLL_INTERVAL; } } 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 AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_FORM_RECOGNIZER_API_KEY"))); } 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()); validateBoundingBoxData(expectedTable.getBoundingBox(), actualTable.getFieldBoundingBox()); } } 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 validateFormSelectionMarkData(List<SelectionMark> expectedMarks, List<FormSelectionMark> actualMarks, int pageNumber) { for (int i = 0; i < actualMarks.size(); i++) { final SelectionMark expectedMark = expectedMarks.get(i); final FormSelectionMark actualMark = actualMarks.get(i); assertEquals(expectedMark.getState().toString(), actualMark.getState().toString()); validateBoundingBoxData(expectedMark.getBoundingBox(), actualMark.getBoundingBox()); assertNull(actualMark.getText()); assertEquals(pageNumber, actualMark.getPageNumber()); } } 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 recognizeContentWithSelectionMarks(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 recognizeContentWithSelectionMarksFromUrl(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 recognizeCustomFormLabeledDataWithSelectionMark(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 recognizeCustomFormUrlLabeledDataWithSelectionMark(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()); } validateFormSelectionMarkData(readResult.getSelectionMarks(), actualFormPage.getSelectionMarks(), readResult.getPage()); 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, PrebuiltType 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)) { assertEquals("prebuilt:businesscard", actualForm.getFormType()); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else if (RECEIPT.equals(prebuiltType)) { assertEquals("prebuilt:receipt", actualForm.getFormType()); 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); }); } else if (INVOICE.equals(prebuiltType)) { assertEquals("prebuilt:invoice", actualForm.getFormType()); INVOICE_FIELDS.forEach(invoiceField -> { final Map<String, FormField> actualRecognizedInvoiceFields = actualForm.getFields(); Map<String, FieldValue> expectedInvoiceFields = rawDocumentResult.getFields(); validateFieldValueTransforms(expectedInvoiceFields.get(invoiceField), actualRecognizedInvoiceFields.get(invoiceField), rawReadResults, includeFieldElements); }); } else { throw new RuntimeException("prebuilt type not supported"); } } } 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 testingContainerUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } 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 beginSelectionMarkTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getSelectionMarkTrainingSasUri(), 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 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()); FormField contactNameField = businessCard1Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactNameField.getValueData().getPageNumber(), 1); assertEquals(contactNameField.getValueData().getText(), "JOHN SINGER"); 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()); FormField contactName2Field = businessCard2Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactName2Field.getValueData().getPageNumber(), 2); assertEquals(contactName2Field.getValueData().getText(), "Dr. Avery Smith"); } static void validateMultipageInvoiceData(List<RecognizedForm> recognizedInvoices) { assertEquals(1, recognizedInvoices.size()); RecognizedForm recognizedForm = recognizedInvoices.get(0); assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(2, recognizedForm.getPageRange().getLastPageNumber()); Map<String, FormField> recognizedInvoiceFields = recognizedForm.getFields(); final FormField remittanceAddressRecipient = recognizedInvoiceFields.get("RemittanceAddressRecipient"); assertEquals("Contoso Ltd.", remittanceAddressRecipient.getValue().asString()); assertEquals(1, remittanceAddressRecipient.getValueData().getPageNumber()); final FormField remittanceAddress = recognizedInvoiceFields.get("RemittanceAddress"); assertEquals("2345 Dogwood Lane Birch, Kansas 98123", remittanceAddress.getValue().asString()); assertEquals(1, remittanceAddress.getValueData().getPageNumber()); final FormField vendorName = recognizedInvoiceFields.get("VendorName"); assertEquals("Southridge Video", vendorName.getValue().asString()); assertEquals(2, vendorName.getValueData().getPageNumber()); assertEquals(2, recognizedForm.getPages().size()); } 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); } } private String getSelectionMarkTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_SELECTION_MARK_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 RecordedData copyRecordedData = interceptorManager.getRecordedData(); final NetworkCallRecord networkCallRecord = copyRecordedData.findFirstAndRemoveNetworkCall(record -> true); copyRecordedData.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 INVOICE_PDF = "Invoice_1.pdf"; static final String MULTIPAGE_VENDOR_INVOICE_PDF = "multipage_vendor_invoice.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"); static final List<String> INVOICE_FIELDS = Arrays.asList("CustomerAddressRecipient", "InvoiceId", "VendorName", "VendorAddress", "CustomerAddress", "CustomerName", "InvoiceTotal", "DueDate", "InvoiceDate"); enum PrebuiltType { RECEIPT, BUSINESS_CARD, INVOICE } Duration durationTestMode; public static final String INVOICE_TEST_URL = "https: + "feature/formrecognizer_v2.1-preview2/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources/" + "sample_files/Test/Invoice_1.pdf"; /** * 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_POLL_INTERVAL; } } 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 AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } 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()); validateBoundingBoxData(expectedTable.getBoundingBox(), actualTable.getFieldBoundingBox()); } } 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 validateFormSelectionMarkData(List<SelectionMark> expectedMarks, List<FormSelectionMark> actualMarks, int pageNumber) { for (int i = 0; i < actualMarks.size(); i++) { final SelectionMark expectedMark = expectedMarks.get(i); final FormSelectionMark actualMark = actualMarks.get(i); assertEquals(expectedMark.getState().toString(), actualMark.getState().toString()); validateBoundingBoxData(expectedMark.getBoundingBox(), actualMark.getBoundingBox()); assertNull(actualMark.getText()); assertEquals(pageNumber, actualMark.getPageNumber()); } } 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 recognizeContentWithSelectionMarks(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 recognizeContentWithSelectionMarksFromUrl(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 recognizeCustomFormLabeledDataWithSelectionMark(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 recognizeCustomFormUrlLabeledDataWithSelectionMark(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()); } validateFormSelectionMarkData(readResult.getSelectionMarks(), actualFormPage.getSelectionMarks(), readResult.getPage()); 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, PrebuiltType 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)) { assertEquals("prebuilt:businesscard", actualForm.getFormType()); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(rawDocumentResult.getFields().get(businessCardField), actualForm.getFields().get(businessCardField), rawReadResults, includeFieldElements)); } else if (RECEIPT.equals(prebuiltType)) { assertEquals("prebuilt:receipt", actualForm.getFormType()); 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); }); } else if (INVOICE.equals(prebuiltType)) { assertEquals("prebuilt:invoice", actualForm.getFormType()); INVOICE_FIELDS.forEach(invoiceField -> { final Map<String, FormField> actualRecognizedInvoiceFields = actualForm.getFields(); Map<String, FieldValue> expectedInvoiceFields = rawDocumentResult.getFields(); validateFieldValueTransforms(expectedInvoiceFields.get(invoiceField), actualRecognizedInvoiceFields.get(invoiceField), rawReadResults, includeFieldElements); }); } else { throw new RuntimeException("prebuilt type not supported"); } } } 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 testingContainerUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } 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 beginSelectionMarkTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getSelectionMarkTrainingSasUri(), 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 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()); FormField contactNameField = businessCard1Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactNameField.getValueData().getPageNumber(), 1); assertEquals(contactNameField.getValueData().getText(), "JOHN SINGER"); 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()); FormField contactName2Field = businessCard2Fields.get("ContactNames").getValue().asList().get(0); assertEquals(contactName2Field.getValueData().getPageNumber(), 2); assertEquals(contactName2Field.getValueData().getText(), "Dr. Avery Smith"); } static void validateMultipageInvoiceData(List<RecognizedForm> recognizedInvoices) { assertEquals(1, recognizedInvoices.size()); RecognizedForm recognizedForm = recognizedInvoices.get(0); assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(2, recognizedForm.getPageRange().getLastPageNumber()); Map<String, FormField> recognizedInvoiceFields = recognizedForm.getFields(); final FormField remittanceAddressRecipient = recognizedInvoiceFields.get("RemittanceAddressRecipient"); assertEquals("Contoso Ltd.", remittanceAddressRecipient.getValue().asString()); assertEquals(1, remittanceAddressRecipient.getValueData().getPageNumber()); final FormField remittanceAddress = recognizedInvoiceFields.get("RemittanceAddress"); assertEquals("2345 Dogwood Lane Birch, Kansas 98123", remittanceAddress.getValue().asString()); assertEquals(1, remittanceAddress.getValueData().getPageNumber()); final FormField vendorName = recognizedInvoiceFields.get("VendorName"); assertEquals("Southridge Video", vendorName.getValue().asString()); assertEquals(2, vendorName.getValueData().getPageNumber()); assertEquals(2, recognizedForm.getPages().size()); } 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); } } private String getSelectionMarkTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_SELECTION_MARK_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 networkCallRecord1 = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(networkCallRecord -> { URL url = null; try { url = new URL(networkCallRecord.getUri()); } catch (MalformedURLException e) { assertFalse(false, e.getMessage()); } if (url.getQuery() != null) { String[] params = url.getQuery().split("&"); for (String param : params) { String name = param.split("=")[0]; String queryValue = param.split("=")[1]; if (name.equals(requestParam) && value.equals(queryValue)) { return true; } } return false; } return false; }); assertNotNull(networkCallRecord1); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord1); } }
We should use another method, error(String, Throwable) here.
public AbstractAuthenticationToken convert(Jwt jwt) { OAuth2AccessToken accessToken = new OAuth2AccessToken( OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt()); AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt); Collection<GrantedAuthority> authorities = token.getAuthorities(); JWTClaimsSet.Builder builder = new Builder(); for (Entry<String, Object> entry : jwt.getClaims().entrySet()) { builder.claim(entry.getKey(), entry.getValue()); } JWTClaimsSet jwtClaimsSet = builder.build(); JWSObject jwsObject = null; try { jwsObject = JWSObject.parse(accessToken.getTokenValue()); } catch (ParseException e) { LOGGER.error( e.getMessage() + ". When create an instance of JWSObject, an exception is resolved on the token."); } UserPrincipal userPrincipal = new UserPrincipal(accessToken.getTokenValue(), jwsObject, jwtClaimsSet); return new PreAuthenticatedAuthenticationToken(userPrincipal, null, authorities); }
LOGGER.error(
public AbstractAuthenticationToken convert(Jwt jwt) { OAuth2AccessToken accessToken = new OAuth2AccessToken( OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt()); Collection<GrantedAuthority> authorities = extractAuthorities(jwt); AzureOAuth2AuthenticatedPrincipal principal = new AzureOAuth2AuthenticatedPrincipal( jwt.getHeaders(), jwt.getClaims(), authorities, jwt.getTokenValue()); return new BearerTokenAuthentication(principal, accessToken, authorities); }
class AzureJwtBearerTokenAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> { private static final Logger LOGGER = LoggerFactory.getLogger(AzureJwtBearerTokenAuthenticationConverter.class); private final JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); public AzureJwtBearerTokenAuthenticationConverter() { } @Override }
class AzureJwtBearerTokenAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> { private static final String DEFAULT_AUTHORITY_PREFIX = "SCOPE_"; private Converter<Jwt, Collection<GrantedAuthority>> jwtGrantedConverter = new JwtGrantedAuthoritiesConverter(); public AzureJwtBearerTokenAuthenticationConverter() { } public AzureJwtBearerTokenAuthenticationConverter(String authoritiesClaimName) { this(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX); } public AzureJwtBearerTokenAuthenticationConverter(String authoritiesClaimName, String authorityPrefix) { Assert.notNull(authoritiesClaimName, "authoritiesClaimName cannot be null"); Assert.notNull(authorityPrefix, "authorityPrefix cannot be null"); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName(authoritiesClaimName); jwtGrantedAuthoritiesConverter.setAuthorityPrefix(authorityPrefix); this.jwtGrantedConverter = jwtGrantedAuthoritiesConverter; } protected Collection<GrantedAuthority> extractAuthorities(Jwt jwt) { return this.jwtGrantedConverter.convert(jwt); } @Override public void setJwtGrantedAuthoritiesConverter( Converter<Jwt, Collection<GrantedAuthority>> jwtGrantedAuthoritiesConverter) { this.jwtGrantedConverter = jwtGrantedAuthoritiesConverter; } }
The check is there to ensure that we don't fire the exception multiple times. As for what happens if close is called multiple times I am not certain and can take a look into this.
private void readTimeoutRunnable(ChannelHandlerContext ctx) { if ((timeoutMillis - (System.currentTimeMillis() - lastReadMillis)) > 0) { return; } if (!closed) { ctx.fireExceptionCaught(new TimeoutException(String.format(READ_TIMED_OUT_MESSAGE, timeoutMillis))); ctx.close(); closed = true; } }
if (!closed) {
private void readTimeoutRunnable(ChannelHandlerContext ctx) { if ((timeoutMillis - (System.currentTimeMillis() - lastReadMillis)) > 0) { return; } if (!closed) { ctx.fireExceptionCaught(new TimeoutException(String.format(READ_TIMED_OUT_MESSAGE, timeoutMillis))); ctx.close(); closed = true; } }
class ReadTimeoutHandler extends ChannelInboundHandlerAdapter { /** * Name of the handler when it is added into a ChannelPipeline. */ public static final String HANDLER_NAME = "azureReadTimeoutHandler"; private static final String READ_TIMED_OUT_MESSAGE = "Channel read timed out after %d milliseconds."; private final long timeoutMillis; private boolean closed; private long lastReadMillis; private ScheduledFuture<?> readTimeoutWatcher; /** * Constructs a channel handler that watches channel read operations to ensure they aren't timing out. * * @param timeoutMillis The period of milliseconds when read progress has stopped before a channel is considered * timed out. */ public ReadTimeoutHandler(long timeoutMillis) { this.timeoutMillis = timeoutMillis; } @Override public void channelReadComplete(ChannelHandlerContext ctx) { this.lastReadMillis = System.currentTimeMillis(); ctx.fireChannelReadComplete(); } @Override public void handlerAdded(ChannelHandlerContext ctx) { if (timeoutMillis > 0) { this.readTimeoutWatcher = ctx.executor().scheduleAtFixedRate(() -> readTimeoutRunnable(ctx), timeoutMillis, timeoutMillis, TimeUnit.MILLISECONDS); } } @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (readTimeoutWatcher != null && !readTimeoutWatcher.isDone()) { readTimeoutWatcher.cancel(false); readTimeoutWatcher = null; } } }
class ReadTimeoutHandler extends ChannelInboundHandlerAdapter { /** * Name of the handler when it is added into a ChannelPipeline. */ public static final String HANDLER_NAME = "azureReadTimeoutHandler"; private static final String READ_TIMED_OUT_MESSAGE = "Channel read timed out after %d milliseconds."; private final long timeoutMillis; private boolean closed; private long lastReadMillis; private ScheduledFuture<?> readTimeoutWatcher; /** * Constructs a channel handler that watches channel read operations to ensure they aren't timing out. * * @param timeoutMillis The period of milliseconds when read progress has stopped before a channel is considered * timed out. */ public ReadTimeoutHandler(long timeoutMillis) { this.timeoutMillis = timeoutMillis; } @Override public void channelReadComplete(ChannelHandlerContext ctx) { this.lastReadMillis = System.currentTimeMillis(); ctx.fireChannelReadComplete(); } @Override public void handlerAdded(ChannelHandlerContext ctx) { if (timeoutMillis > 0) { this.readTimeoutWatcher = ctx.executor().scheduleAtFixedRate(() -> readTimeoutRunnable(ctx), timeoutMillis, timeoutMillis, TimeUnit.MILLISECONDS); } } @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (readTimeoutWatcher != null && !readTimeoutWatcher.isDone()) { readTimeoutWatcher.cancel(false); readTimeoutWatcher = null; } } }
```suggestion reason, errorContext.getException().getMessage()); ```
public static void main(String[] args) throws InterruptedException { Consumer<ServiceBusReceivedMessageContext> messageProcessor = context -> { ServiceBusReceivedMessage message = context.getMessage(); System.out.println("Received message " + message.getBody().toString()); }; final CountDownLatch countdownLatch = new CountDownLatch(1); Consumer<ServiceBusErrorContext> errorHandler = errorContext -> { if (errorContext.getException() instanceof ServiceBusException) { final ServiceBusException serviceBusException = (ServiceBusException) errorContext.getException(); final ServiceBusFailureReason reason = serviceBusException.getReason(); if (reason == ServiceBusFailureReason.MESSAGING_ENTITY_DISABLED || reason == ServiceBusFailureReason.MESSAGING_ENTITY_NOT_FOUND || reason == ServiceBusFailureReason.UNAUTHORIZED) { System.out.printf("An unrecoverable error occurred. Stopping processing with reason %s: %s\n", reason, serviceBusException.toString()); countdownLatch.countDown(); } else if (reason == ServiceBusFailureReason.MESSAGE_LOCK_LOST) { System.out.printf("Message lock lost for message: %s", errorContext.getException().toString()); } else if (reason == ServiceBusFailureReason.SERVICE_BUSY) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.printf("Error source %s, reason %s, message: %s\n", serviceBusException.getErrorSource(), reason, errorContext.getException().toString()); } } else { System.out.printf("Exception: %s\n", errorContext.getException().toString()); } }; final ServiceBusProcessorClient processorClient = new ServiceBusClientBuilder() .connectionString("<< connection-string >>") .processor() .queueName("<< queue name >>") .processMessage(messageProcessor) .processError(errorHandler) .buildProcessorClient(); System.out.println("Starting the processor"); processorClient.start(); System.out.println("Listening for 10 seconds..."); if (countdownLatch.await(10, TimeUnit.SECONDS)) { System.out.println("Closing processor due to fatal error"); } else { System.out.println("Closing processor"); } processorClient.close(); }
reason, errorContext.getException().toString());
public static void main(String[] args) throws InterruptedException { Consumer<ServiceBusReceivedMessageContext> messageProcessor = context -> { ServiceBusReceivedMessage message = context.getMessage(); System.out.println("Received message " + message.getBody().toString()); }; final CountDownLatch countdownLatch = new CountDownLatch(1); Consumer<ServiceBusErrorContext> errorHandler = errorContext -> { if (errorContext.getException() instanceof ServiceBusException) { final ServiceBusException serviceBusException = (ServiceBusException) errorContext.getException(); final ServiceBusFailureReason reason = serviceBusException.getReason(); if (reason == ServiceBusFailureReason.MESSAGING_ENTITY_DISABLED || reason == ServiceBusFailureReason.MESSAGING_ENTITY_NOT_FOUND || reason == ServiceBusFailureReason.UNAUTHORIZED) { System.out.printf("An unrecoverable error occurred. Stopping processing with reason %s: %s\n", reason, serviceBusException.getMessage()); countdownLatch.countDown(); } else if (reason == ServiceBusFailureReason.MESSAGE_LOCK_LOST) { System.out.printf("Message lock lost for message: %s", errorContext.getException().toString()); } else if (reason == ServiceBusFailureReason.SERVICE_BUSY) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.printf("Error source %s, reason %s, message: %s\n", serviceBusException.getErrorSource(), reason, errorContext.getException().getMessage()); } } else { System.out.printf("Exception: %s\n", errorContext.getException().toString()); } }; final ServiceBusProcessorClient processorClient = new ServiceBusClientBuilder() .connectionString("<< connection-string >>") .processor() .queueName("<< queue name >>") .processMessage(messageProcessor) .processError(errorHandler) .buildProcessorClient(); System.out.println("Starting the processor"); processorClient.start(); System.out.println("Listening for 10 seconds..."); if (countdownLatch.await(10, TimeUnit.SECONDS)) { System.out.println("Closing processor due to fatal error"); } else { System.out.println("Closing processor"); } processorClient.close(); }
class ServiceBusProcessorSample { /** * Main method to start the sample application. * @param args Ignored args. * @throws InterruptedException If the application is interrupted. */ }
class ServiceBusProcessorSample { /** * Main method to start the sample application. * @param args Ignored args. * @throws InterruptedException If the application is interrupted. */ }