diff --git a/sdk/attestation/azure-resourcemanager-attestation/pom.xml b/sdk/attestation/azure-resourcemanager-attestation/pom.xml index b69a3c03f8789..381f82c1c3b2d 100644 --- a/sdk/attestation/azure-resourcemanager-attestation/pom.xml +++ b/sdk/attestation/azure-resourcemanager-attestation/pom.xml @@ -39,6 +39,9 @@ UTF-8 + false + + diff --git a/sdk/attestation/azure-security-attestation/README.md b/sdk/attestation/azure-security-attestation/README.md index 602a9d9baee88..4c18617905b63 100644 --- a/sdk/attestation/azure-security-attestation/README.md +++ b/sdk/attestation/azure-security-attestation/README.md @@ -31,14 +31,14 @@ Maven dependency for the Azure Attestation library. Add it to your project's PO - [Azure Subscription][azure_subscription] - An existing [Azure Attestation][azure_attestation]. If you need to create an attestation instance, you can use the [Azure Cloud Shell][azure_cloud_shell] to create one with this Azure CLI command. Replace `` and `` with your own, unique names: - ```bash - az attestation create --resource-group --name - ``` +```bash +az attestation create --resource-group --name +``` ### Authenticate the client In order to interact with the Azure Attestation service, your client must present an Azure Active Directory bearer token to the service. -The simplest way of providing a bearer token is to use the `DefaultAzureCredential` authentication method by providing client secret credentials is being used in this getting started section but you can find more ways to authenticate with [azure-identity][azure_identity]. +The simplest way of providing a bearer token is to use the `DefaultAzureCredential` authentication method by providing client secret credentials is being used in this getting started section, but you can find more ways to authenticate with [azure-identity][azure_identity]. ## Key concepts diff --git a/sdk/attestation/azure-security-attestation/pom.xml b/sdk/attestation/azure-security-attestation/pom.xml index 2e4ba6f83349a..d2dd2df34d73b 100644 --- a/sdk/attestation/azure-security-attestation/pom.xml +++ b/sdk/attestation/azure-security-attestation/pom.xml @@ -39,6 +39,9 @@ --add-opens com.azure.security.attestation/com.azure.security.attestation.models=ALL-UNNAMED --add-opens com.azure.security.attestation/com.azure.security.attestation.models=com.fasterxml.jackson.databind + false + + diff --git a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationAsyncClient.java b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationAsyncClient.java index d4869f104b583..861105bc232b0 100644 --- a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationAsyncClient.java +++ b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationAsyncClient.java @@ -294,7 +294,15 @@ Mono> setAttestationPolicyWithResponse(AttestationType at * which the customer specified. * * For an example of how to check the policy token hash: - * {@codesnippet com.azure.security.attestation.AttestationAdministrationAsyncClient.checkPolicyTokenHash} + * + *
+     * BinaryData expectedHash = client.calculatePolicyTokenHash(policyToSet, null);
+     * BinaryData actualHash = result.getPolicyTokenHash();
+     * if (!expectedHash.equals(actualHash)) {
+     *     throw new RuntimeException("Policy was set but not received!!!");
+     * }
+     * 
+ * * * @param policy AttestationPolicy document use in the underlying JWT. * @param signer Optional signing key used to sign the underlying JWT. diff --git a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationClient.java b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationClient.java index 5963835d282e3..a1dc54603e6b6 100644 --- a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationClient.java +++ b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationClient.java @@ -180,7 +180,15 @@ public Response setAttestationPolicyWithResponse(AttestationType a * which the customer specified. * * For an example of how to check the policy token hash: - * {@codesnippet com.azure.security.attestation.AttestationAdministrationAsyncClient.checkPolicyTokenHash} + * + *
+     * BinaryData expectedHash = client.calculatePolicyTokenHash(policyToSet, null);
+     * BinaryData actualHash = result.getPolicyTokenHash();
+     * if (!expectedHash.equals(actualHash)) {
+     *     throw new RuntimeException("Policy was set but not received!!!");
+     * }
+     * 
+ * * * @param policy AttestationPolicy document use in the underlying JWT. * @param signer Optional signing key used to sign the underlying JWT. diff --git a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationClientBuilder.java b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationClientBuilder.java index c949c829583aa..3c39d90dcddae 100644 --- a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationClientBuilder.java +++ b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAdministrationClientBuilder.java @@ -190,7 +190,13 @@ public AttestationAdministrationClientBuilder tokenValidationOptions(Attestation * * Instantiating a synchronous Attestation client: *
- * {@codesnippet com.azure.security.attestation.AttestationAdministrationClientBuilder.buildClient} + * + *
+     * AttestationAdministrationClient client = new AttestationAdministrationClientBuilder()
+     *     .endpoint(endpoint)
+     *     .buildClient();
+     * 
+ * * @return an instance of {@link AttestationClient}. */ public AttestationAdministrationClient buildClient() { @@ -202,7 +208,13 @@ public AttestationAdministrationClient buildClient() { * * Instantiating a synchronous Attestation client: *
- * {@codesnippet com.azure.security.attestation.AttestationAdministrationClientBuilder.buildAsyncClient} + * + *
+     * AttestationAdministrationAsyncClient asyncClient = new AttestationAdministrationClientBuilder()
+     *     .endpoint(endpoint)
+     *     .buildAsyncClient();
+     * 
+ * * @return an instance of {@link AttestationClient}. */ public AttestationAdministrationAsyncClient buildAsyncClient() { diff --git a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAsyncClient.java b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAsyncClient.java index d82f7f318f921..1ea1c518d0244 100644 --- a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAsyncClient.java +++ b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationAsyncClient.java @@ -171,7 +171,11 @@ public final class AttestationAsyncClient { * Retrieves metadata about the attestation signing keys in use by the attestation service. * *

Retrieve the OpenID metadata for this async client.

- * {@codesnippet com.azure.security.attestation.AttestationAsyncClient.getOpenIdMetadataWithResponse} + * + *
+     * Mono<Response<AttestationOpenIdMetadata>> response = client.getOpenIdMetadataWithResponse();
+     * 
+ * * * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -191,7 +195,11 @@ Mono> getOpenIdMetadataWithResponse(Context * Retrieves metadata about the attestation signing keys in use by the attestation service. *

Retrieve the OpenID metadata for this async client.

- * {@codesnippet com.azure.security.attestation.AttestationAsyncClient.getOpenIdMetadata} + * + *
+     * Mono<AttestationOpenIdMetadata> openIdMetadata = client.getOpenIdMetadata();
+     * 
+ * * * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -211,7 +219,23 @@ public Mono getOpenIdMetadata() { * to validate an attestation token returned by the service. *

*

Retrieve Attestation Signers for this async client.

- * {@codesnippet com.azure.security.attestation.AttestationAsyncClient.getAttestationSigners} + * + *
+     * Mono<List<AttestationSigner>> signers = client.listAttestationSigners();
+     * signers.block().forEach(cert -> {
+     *     System.out.println("Found certificate.");
+     *     if (cert.getKeyId() != null) {
+     *         System.out.println("    Certificate Key ID: " + cert.getKeyId());
+     *     } else {
+     *         System.out.println("    Signer does not have a Key ID");
+     *     }
+     *     cert.getCertificates().forEach(chainElement -> {
+     *         System.out.println("        Cert Subject: " + chainElement.getSubjectDN().getName());
+     *         System.out.println("        Cert Issuer: " + chainElement.getIssuerDN().getName());
+     *     });
+     * });
+     * 
+ * * * @return Returns an array of {@link AttestationSigner} objects. */ @@ -228,7 +252,11 @@ public Mono> listAttestationSigners() { * to validate an attestation token returned by the service. *

*

Retrieve Attestation Signers for this async client.

- * {@codesnippet com.azure.security.attestation.AttestationAsyncClient.getAttestationSignersWithResponse} + * + *
+     * Mono<Response<List<AttestationSigner>>> responseOfSigners = client.listAttestationSignersWithResponse();
+     * 
+ * * * @return Returns an array of {@link AttestationSigner} objects. */ diff --git a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationClientBuilder.java b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationClientBuilder.java index 0addb31a70dbb..ee18d4f39d20b 100644 --- a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationClientBuilder.java +++ b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationClientBuilder.java @@ -188,7 +188,13 @@ public AttestationClientBuilder tokenValidationOptions(AttestationTokenValidatio * * Instantiating a synchronous Attestation client: *
- * {@codesnippet com.azure.security.attestation.AttestationClientBuilder.buildClient} + * + *
+     * AttestationClient client = new AttestationClientBuilder()
+     *     .endpoint(endpoint)
+     *     .buildClient();
+     * 
+ * * @return an instance of {@link AttestationClient}. */ public AttestationClient buildClient() { @@ -200,7 +206,13 @@ public AttestationClient buildClient() { * * Instantiating a synchronous Attestation client: *
- * {@codesnippet com.azure.security.attestation.AttestationClientBuilder.buildAsyncClient} + * + *
+     * AttestationAsyncClient asyncClient = new AttestationClientBuilder()
+     *     .endpoint(endpoint)
+     *     .buildAsyncClient();
+     * 
+ * * @return an instance of {@link AttestationClient}. */ public AttestationAsyncClient buildAsyncClient() { diff --git a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationServiceVersion.java b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationServiceVersion.java index 18fb50e731b21..b188b78eabd30 100644 --- a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationServiceVersion.java +++ b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/AttestationServiceVersion.java @@ -9,6 +9,9 @@ * The versions of Azure Metrics Advisor supported by this client library. */ public enum AttestationServiceVersion implements ServiceVersion { + /** + * Service version {@code 2020-10-01}. + */ V2020_10_01("2020-10-01"); private final String version; diff --git a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/models/AttestationOptions.java b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/models/AttestationOptions.java index 9a2a75aaf070e..4b950139c6811 100644 --- a/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/models/AttestationOptions.java +++ b/sdk/attestation/azure-security-attestation/src/main/java/com/azure/security/attestation/models/AttestationOptions.java @@ -81,7 +81,11 @@ public final class AttestationOptions { * The evidence will typically take the form of either an OpenEnclave report or an Intel SGX quote. * *

Create an AttestationOptions from an SGX quote:

- * {@codesnippet com.azure.security.attestation.models..fromEvidence#byte} + * + *
+     * AttestationOptions options = new AttestationOptions(sgxQuote);
+     * 
+ * * @param evidence to be used in the attest request. */ public AttestationOptions(BinaryData evidence) { @@ -110,7 +114,12 @@ public BinaryData getEvidence() { * the {@link AttestationDataInterpretation} specified for the RunTime Data was set to "BINARY", or * *

Setting RunTime Data Property

- * {@codesnippet com.azure.security.attestation.models..setInitTimeData#byte} + * + *
+     * AttestationOptions optionsWithInitTimeData = new AttestationOptions(openEnclaveReport)
+     *     .setInitTimeData(new AttestationData(inittimeData, AttestationDataInterpretation.BINARY));
+     * 
+ * * @param attestationData the runtimeData value to set. * @return this {@link AttestationOptions} object itself. */ @@ -122,7 +131,14 @@ public AttestationOptions setRunTimeData(AttestationData attestationData) { /** * Retrieves the RunTimeData property to be sent to the service. *

Retrieve the RunTimeData value.

- * {@codesnippet com.azure.security.attestation.models.AttestationOptions.getRunTimeData} + * + *
+     * AttestationOptions attestationOptions = new AttestationOptions(openEnclaveReport)
+     *     .setRunTimeData(new AttestationData(runtimeData, AttestationDataInterpretation.JSON));
+     *
+     * AttestationData existingRuntimeData = attestationOptions.getRunTimeData();
+     * 
+ * * @return The RunTimeData value set by {@link AttestationOptions#setRunTimeData} */ public AttestationData getRunTimeData() { @@ -140,7 +156,12 @@ public AttestationData getRunTimeData() { * for the {@link AttestationData} is set to "JSON". * *

Setting InitTime Data Property

- * {@codesnippet com.azure.security.attestation.models..setInitTimeData#byte} + * + *
+     * AttestationOptions optionsWithInitTimeData = new AttestationOptions(openEnclaveReport)
+     *     .setInitTimeData(new AttestationData(inittimeData, AttestationDataInterpretation.BINARY));
+     * 
+ * * @param attestationData the InitTimeData value to set. * @return this {@link AttestationOptions} object itself. */ @@ -152,7 +173,14 @@ public AttestationOptions setInitTimeData(AttestationData attestationData) { /** * Retrieves the InitTimeData property to be sent to the service. *

Retrieve the InitTimeData value.

- * {@codesnippet com.azure.security.attestation.models.AttestationOptions.getInitTimeData} + * + *
+     * AttestationOptions attestationOptions = new AttestationOptions(openEnclaveReport)
+     *     .setInitTimeData(new AttestationData(inittimeData, AttestationDataInterpretation.JSON));
+     *
+     * AttestationData existingRuntimeData = attestationOptions.getInitTimeData();
+     * 
+ * * @return The InitTimeData value set by {@link AttestationOptions#setInitTimeData} */ public AttestationData getInitTimeData() { @@ -165,7 +193,12 @@ public AttestationData getInitTimeData() { * determine how a proposed attestation policy would affect an attestation token.

* Note that the resulting token cannot be validated. *

Example of setting AttestationOptions with a draft policy.

- * {@codesnippet com.azure.security.attestation.models.AttestationOptions.setDraftPolicyForAttestation#String} + * + *
+     * AttestationOptions request = new AttestationOptions(openEnclaveReport)
+     *     .setDraftPolicyForAttestation("version=1.0; authorizationrules{=> permit();}; issuancerules{};");
+     * 
+ * * @param draftPolicyForAttestation the draftPolicyForAttestation value to set. * @return this {@link AttestationOptions} object itself. */ @@ -178,7 +211,14 @@ public AttestationOptions setDraftPolicyForAttestation(String draftPolicyForAtte * Gets the draftPolicyForAttestation property which is used to attest against the draft policy. * *

Gets the previously set draft policy for attestation.

- * {@codesnippet com.azure.security.attestation.models.AttestationOptions.getDraftPolicyForAttestation} + * + *
+     * AttestationOptions getOptions = new AttestationOptions(openEnclaveReport)
+     *     .setDraftPolicyForAttestation("version=1.0; authorizationrules{=> permit();}; issuancerules{};");
+     *
+     * String draftPolicy = getOptions.getDraftPolicyForAttestation();
+     * 
+ * * @return The draft policy if set. */ public String getDraftPolicyForAttestation() { diff --git a/sdk/attestation/azure-security-attestation/src/samples/java/com/azure/security/attestation/ReadMeSamples.java b/sdk/attestation/azure-security-attestation/src/samples/java/com/azure/security/attestation/ReadmeSamples.java similarity index 100% rename from sdk/attestation/azure-security-attestation/src/samples/java/com/azure/security/attestation/ReadMeSamples.java rename to sdk/attestation/azure-security-attestation/src/samples/java/com/azure/security/attestation/ReadmeSamples.java diff --git a/sdk/keyvault/azure-security-keyvault-administration/README.md b/sdk/keyvault/azure-security-keyvault-administration/README.md index 20c6213b13525..5e608b3fadd74 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/README.md +++ b/sdk/keyvault/azure-security-keyvault-administration/README.md @@ -24,9 +24,9 @@ Maven dependency for the Azure Key Vault Administration library. Add it to your - [Azure Subscription][azure_subscription] - An existing [Azure Key Vault Managed HSM][azure_keyvault_mhsm]. If you need to create a Managed HSM, you can use the [Azure Cloud Shell][azure_cloud_shell] to create one with this Azure CLI command. Replace `` and `` with your own, unique names: - ```Bash - az keyvault create --hsm-name --resource-group --administrators --location - ``` +```bash +az keyvault create --hsm-name --resource-group --administrators --location +``` ### Authenticate the client In order to interact with the Azure Key Vault service, you'll need to either create an instance of the [KeyVaultAccessControlClient](#create-an-access-control-client) or an instance of the class [KeyVaultBackupClient](#create-a-backup-client). You would need a **vault url**, which you may see as "DNS Name" in the portal, and **client secret credentials (client id, client secret, tenant id)** to instantiate a client object using the default `DefaultAzureCredential` examples shown in this document. @@ -39,54 +39,54 @@ To create/get client secret credentials you can use the [Azure Portal][azure_cre Here is an [Azure Cloud Shell][azure_cloud_shell] snippet below to * Create a service principal and configure its access to Azure resources: + +```bash +az ad sp create-for-rbac -n --skip-assignment +``` - ```Bash - az ad sp create-for-rbac -n --skip-assignment - ``` - - Output: +Output: - ```json - { - "appId": "generated-app-ID", - "displayName": "some-app-name", - "name": "https://some-app-name", - "password": "random-password", - "tenant": "tenant-ID" - } - ``` +```json +{ + "appId": "generated-app-ID", + "displayName": "some-app-name", + "name": "https://some-app-name", + "password": "random-password", + "tenant": "tenant-ID" +} +``` * Take note of the service principal objectId - ```Bash - az ad sp show --id --query objectId - ``` +```bash +az ad sp show --id --query objectId +``` - Output: - ``` - "" - ``` +Output: +``` +"" +``` * Use the returned credentials above to set the **AZURE_CLIENT_ID** (appId), **AZURE_CLIENT_SECRET** (password), and **AZURE_TENANT_ID** (tenantId) environment variables. The following example shows a way to do this in Bash: - ```Bash - export AZURE_CLIENT_ID="generated-app-ID" - export AZURE_CLIENT_SECRET="random-password" - export AZURE_TENANT_ID="tenant-ID" - ``` +```bash +export AZURE_CLIENT_ID="generated-app-ID" +export AZURE_CLIENT_SECRET="random-password" +export AZURE_TENANT_ID="tenant-ID" +``` * Create the Managed HSM and grant the above mentioned service principal authorization to perform administrative operations on the Managed HSM (replace `` and `` with your own, unique names and `` with the value from above): - ```bash - az keyvault create --hsm-name --resource-group --administrators --location - ``` +```bash +az keyvault create --hsm-name --resource-group --administrators --location +``` This service principal is automatically added to the "Managed HSM Administrators" [built-in role][built_in_roles]. * Use the aforementioned Azure Key Vault name to retrieve details of your Key Vault, which also contain your Azure Key Vault URL: - ```Bash - az keyvault show --name - ``` +```bash +az keyvault show --name +``` #### Activate your managed HSM All data plane commands are disabled until the HSM is activated. You will not be able to create keys or assign roles. Only the designated administrators that were assigned during the create command can activate the HSM. To activate the HSM you must download the security domain. @@ -142,17 +142,16 @@ The Key Vault Backup Client provides both synchronous and asynchronous operation > NOTE: The backing store for key backups is a blob storage container using Shared Access Signature authentication. For more details on creating a SAS token using the BlobServiceClient, see the [Azure Storage Blobs client README][storage_readme_sas_token]. Alternatively, it is possible to [generate a SAS token in Storage Explorer][portal_sas_token]. ### Backup Operation -A backup operation represents a long running operation for a full key backup. +A backup operation represents a long-running operation for a full key backup. ### Restore Operation -A restore operation represents a long running operation for both a full key and selective key restore. +A restore operation represents a long-running operation for both a full key and selective key restore. ## Create an Access Control client Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET**, and **AZURE_TENANT_ID** environment variables and replaced **your-key-vault-url** with the URI returned above, you can create the `KeyVaultAccessControlClient`: - -```java -KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() +```java readme-sample-createAccessControlClient +KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); @@ -174,8 +173,7 @@ The following sections provide several code snippets covering some of the most c ### List role definitions List the role definitions in the key vault by calling `listRoleDefinitions()`. - -```java +```java readme-sample-listRoleDefinitions PagedIterable roleDefinitions = keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL); @@ -186,8 +184,7 @@ roleDefinitions.forEach(roleDefinition -> ### Create or update a role definition Create or update a role definition in the key vault. The following example shows how to create a role definition with a randomly generated name. - -```java +```java readme-sample-setRoleDefinition KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL); System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n", @@ -197,8 +194,7 @@ System.out.printf("Created role definition with randomly generated name '%s' and ### Retrieve a role definition Get an existing role definition. To do this, the scope and 'name' property from an existing role definition are required. - -```java +```java readme-sample-getRoleDefinition String roleDefinitionName = ""; KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); @@ -210,8 +206,7 @@ System.out.printf("Retrieved role definition with name '%s' and role name '%s'.% ### Delete a role definition Delete a role definition. To do this, the scope and 'name' property property from an existing role definition are required. - -```java +```java readme-sample-deleteRoleDefinition String roleDefinitionName = ""; keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); @@ -222,8 +217,7 @@ System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionNam ### List role assignments List the role assignments in the key vault by calling `listRoleAssignments()`. - -```java +```java readme-sample-listRoleAssignments PagedIterable roleAssignments = keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL); @@ -238,12 +232,11 @@ A role definition ID can be obtained from the 'id' property of one of the role d See the [Create/Get Credentials section](#createget-credentials) for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: -```Bash +```bash az ad signed-in-user show --query objectId ``` - -```java +```java readme-sample-createRoleAssignment String roleDefinitionId = ""; String servicePrincipalId = ""; KeyVaultRoleAssignment roleAssignment = @@ -257,8 +250,7 @@ System.out.printf("Created role assignment with randomly generated name '%s' for ### Retrieve a role assignment Get an existing role assignment. To do this, the 'name' property from an existing role assignment is required. - -```java +```java readme-sample-getRoleAssignment String roleAssignmentName = ""; KeyVaultRoleAssignment roleAssignment = keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); @@ -268,8 +260,7 @@ System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment. ### Delete a role assignment To remove a role assignment from a service principal, the role assignment must be deleted. To do this, the 'name' property from an existing role assignment is required. - -```java +```java readme-sample-deleteRoleAssignment String roleAssignmentName = ""; keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); @@ -293,8 +284,7 @@ The following sections provide several code snippets covering some of the most c ### List role definitions asynchronously List the role definitions in the key vault by calling `listRoleDefinitions()`. - -```java +```java readme-sample-listRoleDefinitionsAsync keyVaultAccessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL) .subscribe(roleDefinition -> System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); @@ -303,8 +293,7 @@ keyVaultAccessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL) ### Create or update a role definition asynchronously Create or update a role definition in the key vault. The following example shows how to create a role definition with a randomly generated name. - -```java +```java readme-sample-setRoleDefinitionAsync keyVaultAccessControlAsyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL) .subscribe(roleDefinition -> System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n", @@ -314,8 +303,7 @@ keyVaultAccessControlAsyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL) ### Retrieve a role definition asynchronously Get an existing role definition. To do this, the 'name' property from an existing role definition is required. - -```java +```java readme-sample-getRoleDefinitionAsync String roleDefinitionName = ""; keyVaultAccessControlAsyncClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) @@ -327,8 +315,7 @@ keyVaultAccessControlAsyncClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, rol ### Delete a role definition asynchronously Delete a role definition. To do this, the 'name' property from an existing role definition is required. - -```java +```java readme-sample-deleteRoleDefinitionAsync String roleDefinitionName = ""; keyVaultAccessControlAsyncClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) @@ -338,8 +325,7 @@ keyVaultAccessControlAsyncClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, ### List role assignments asynchronously List the role assignments in the key vault by calling `listRoleAssignments()`. - -```java +```java readme-sample-listRoleAssignmentsAsync keyVaultAccessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL) .subscribe(roleAssignment -> System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); @@ -352,12 +338,11 @@ A role definition ID can be obtained from the 'id' property of one of the role d See the [Create/Get Credentials section](#createget-credentials) for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: -```Bash +```bash az ad signed-in-user show --query objectId ``` - -```java +```java readme-sample-createRoleAssignmentAsync String roleDefinitionId = ""; String servicePrincipalId = ""; @@ -370,8 +355,7 @@ keyVaultAccessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, ### Retrieve a role assignment asynchronously Get an existing role assignment. To do this, the 'name' property from an existing role assignment is required. - -```java +```java readme-sample-getRoleAssignmentAsync String roleAssignmentName = ""; keyVaultAccessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) @@ -382,8 +366,7 @@ keyVaultAccessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, rol ### Delete a role assignment asynchronously To remove a role assignment from a service principal, the role assignment must be deleted. To do this, the 'name' property from an existing role assignment is required. - -```java +```java readme-sample-deleteRoleAssignmentAsync String roleAssignmentName = ""; keyVaultAccessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) @@ -394,8 +377,7 @@ keyVaultAccessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, ### Create a Backup client Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET**, and **AZURE_TENANT_ID** environment variables and replaced **your-key-vault-url** with the URI returned above, you can create the `KeyVaultBackupClient`: - -```java +```java readme-sample-createBackupClient KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder() .vaultUrl("") .credential(new DefaultAzureCredentialBuilder().build()) @@ -414,8 +396,7 @@ The following sections provide several code snippets covering some of the most c ### Backup a collection of keys Back up an entire collection of keys using `beginBackup()`. - -```java +```java readme-sample-beginBackup String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; @@ -442,8 +423,7 @@ if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COM ### Restore a collection of keys Restore an entire collection of keys from a backup using `beginRestore()`. - -```java +```java readme-sample-beginRestore String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; @@ -468,8 +448,7 @@ if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COM ### Selectively restore a key Restore a specific key from a backup using `beginSelectiveRestore()`. - -```java +```java readme-sample-beginSelectiveKeyRestore String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; String keyName = "myKey"; @@ -503,8 +482,7 @@ The following sections provide several code snippets covering some of the most c ### Backup a collection of keys asynchronously Back up an entire collection of keys using `beginBackup()`. - -```java +```java readme-sample-beginBackupAsync String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; @@ -522,8 +500,7 @@ keyVaultBackupAsyncClient.beginBackup(blobStorageUrl, sasToken) ### Restore a collection of keys asynchronously Restore an entire collection of keys from a backup using `beginRestore()`. - -```java +```java readme-sample-beginRestoreAsync String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; @@ -540,8 +517,7 @@ keyVaultBackupAsyncClient.beginRestore(folderUrl, sasToken) ### Selectively restore a key asynchronously Restore an entire collection of keys from a backup using `beginSelectiveRestore()`. - -```java +```java readme-sample-beginSelectiveKeyRestoreAsync String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; String keyName = "myKey"; @@ -560,9 +536,9 @@ keyVaultBackupAsyncClient.beginSelectiveKeyRestore(folderUrl, sasToken, keyName) ### General Azure Key Vault Access Control clients raise exceptions. For example, if you try to retrieve a role assignment after it is deleted a `404` error is returned, indicating the resource was not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error. -```java +```java readme-sample-troubleshooting try { - client.getRoleAssignment(KeyVaultRoleAssignmentScope.GLOBAL, "") + keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, ""); } catch (HttpResponseException e) { System.out.println(e.getMessage()); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/pom.xml b/sdk/keyvault/azure-security-keyvault-administration/pom.xml index 58ffeb02fcfe5..387bdb5381240 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-administration/pom.xml @@ -39,6 +39,9 @@ --add-opens com.azure.security.keyvault.administration/com.azure.security.keyvault.administration=ALL-UNNAMED + false + + diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClient.java index d8f5e8eb2d1f4..86f763ed2ee4a 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClient.java @@ -66,7 +66,14 @@ * method on a {@link KeyVaultAccessControlClientBuilder} object.

* *

Samples to construct an async client

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.instantiation} + * + *
+ * KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder()
+ *     .vaultUrl("https://myaccount.managedhsm.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildAsyncClient();
+ * 
+ * * * @see KeyVaultAccessControlClientBuilder */ @@ -144,7 +151,13 @@ HttpPipeline getHttpPipeline() { *

Code Samples

*

Lists all {@link KeyVaultRoleDefinition role definitions}. Prints out the details of the retrieved * {@link KeyVaultRoleDefinition role definitions}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.listRoleDefinitions#KeyVaultRoleScope} + * + *
+     * keyVaultAccessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)
+     *     .subscribe(roleDefinition ->
+     *         System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definitions}. * @@ -254,7 +267,14 @@ Mono> listRoleDefinitionsNextPage(String c *

Code Samples

*

Creates a {@link KeyVaultRoleDefinition role definition} with a randomly generated name. Prints out the * details of the created {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.setRoleDefinition#KeyVaultRoleScope} + * + *
+     * keyVaultAccessControlAsyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL)
+     *     .subscribe(roleDefinition ->
+     *         System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n",
+     *             roleDefinition.getName(), roleDefinition.getRoleName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * Managed HSM only supports '/'. @@ -276,7 +296,16 @@ public Mono setRoleDefinition(KeyVaultRoleScope roleScop *

Code Samples

*

Creates or updates a {@link KeyVaultRoleDefinition role definition} with a given generated name. Prints out * the details of the created {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.setRoleDefinition#KeyVaultRoleScope-String} + * + *
+     * String myRoleDefinitionName = "504a3d11-5a63-41a9-b603-41bdf88df03e";
+     *
+     * keyVaultAccessControlAsyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL, myRoleDefinitionName)
+     *     .subscribe(roleDefinition ->
+     *         System.out.printf("Set role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(),
+     *             roleDefinition.getRoleName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * Managed HSM only supports '/'. @@ -301,7 +330,39 @@ public Mono setRoleDefinition(KeyVaultRoleScope roleScop *

Code Samples

*

Creates or updates a {@link KeyVaultRoleDefinition role definition}. Prints out the details of the * {@link Response HTTP response} and the created {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.setRoleDefinitionWithResponse#SetRoleDefinitionOptions} + * + *
+     * String roleDefinitionName = "9de303d3-6ea8-4b8f-a20b-18e67f77e42a";
+     *
+     * List<KeyVaultRoleScope> assignableScopes = new ArrayList<>();
+     * assignableScopes.add(KeyVaultRoleScope.GLOBAL);
+     * assignableScopes.add(KeyVaultRoleScope.KEYS);
+     *
+     * List<KeyVaultDataAction> dataActions = new ArrayList<>();
+     * dataActions.add(KeyVaultDataAction.START_HSM_RESTORE);
+     * dataActions.add(KeyVaultDataAction.START_HSM_BACKUP);
+     * dataActions.add(KeyVaultDataAction.READ_HSM_BACKUP_STATUS);
+     * dataActions.add(KeyVaultDataAction.READ_HSM_RESTORE_STATUS);
+     * dataActions.add(KeyVaultDataAction.BACKUP_HSM_KEYS);
+     * dataActions.add(KeyVaultDataAction.RESTORE_HSM_KEYS);
+     *
+     * List<KeyVaultPermission> permissions = new ArrayList<>();
+     * permissions.add(new KeyVaultPermission(null, null, dataActions, null));
+     *
+     * SetRoleDefinitionOptions setRoleDefinitionOptions =
+     *     new SetRoleDefinitionOptions(KeyVaultRoleScope.GLOBAL, roleDefinitionName)
+     *         .setRoleName("Backup and Restore Role Definition")
+     *         .setDescription("Can backup and restore a whole Managed HSM, as well as individual keys.%n")
+     *         .setAssignableScopes(assignableScopes)
+     *         .setPermissions(permissions);
+     *
+     * keyVaultAccessControlAsyncClient.setRoleDefinitionWithResponse(setRoleDefinitionOptions)
+     *     .subscribe(response ->
+     *         System.out.printf("Response successful with status code: %d. Role definition with name '%s' and role"
+     *             + " name '%s' was set.%n", response.getStatusCode(), response.getValue().getName(),
+     *             response.getValue().getRoleName()));
+     * 
+ * * * @param options Object representing the configurable options to create or update a * {@link KeyVaultRoleDefinition role definition}. @@ -401,7 +462,16 @@ Mono> setRoleDefinitionWithResponse(SetRoleDefi *

Code Samples

*

Gets a {@link KeyVaultRoleDefinition role definition}. Prints out the details of the retrieved * {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.getRoleDefinition#KeyVaultRoleScope-String} + * + *
+     * String roleDefinitionName = "8f90b099-7361-4db6-8321-719adaf6e4ca";
+     *
+     * keyVaultAccessControlAsyncClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName)
+     *     .subscribe(roleDefinition ->
+     *         System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n",
+     *             roleDefinition.getName(), roleDefinition.getRoleName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * @param roleDefinitionName The name used of the {@link KeyVaultRoleDefinition role definition}. @@ -424,7 +494,17 @@ public Mono getRoleDefinition(KeyVaultRoleScope roleScop *

Code Samples

*

Gets a {@link KeyVaultRoleDefinition role definition}. Prints out the details of the * {@link Response HTTP response} and the retrieved {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.getRoleDefinitionWithResponse#KeyVaultRoleScope-String} + * + *
+     * String myRoleDefinitionName = "0877b4ee-6275-4559-89f1-c289060ef398";
+     *
+     * keyVaultAccessControlAsyncClient.getRoleDefinitionWithResponse(KeyVaultRoleScope.GLOBAL, myRoleDefinitionName)
+     *     .subscribe(response ->
+     *         System.out.printf("Response successful with status code: %d. Role definition with name '%s' and role"
+     *             + " name '%s' was retrieved.%n", response.getStatusCode(), response.getValue().getName(),
+     *             response.getValue().getRoleName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. @@ -488,7 +568,14 @@ Mono> getRoleDefinitionWithResponse(KeyVaultRol * *

Code Samples

*

Deletes a {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.deleteRoleDefinition#KeyVaultRoleScope-String} + * + *
+     * String roleDefinitionName = "e3c7c51a-8abd-4b1b-9201-48ded34d0358";
+     *
+     * keyVaultAccessControlAsyncClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName)
+     *     .subscribe(unused -> System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * Managed HSM only supports '/'. @@ -511,7 +598,16 @@ public Mono deleteRoleDefinition(KeyVaultRoleScope roleScope, String roleD *

Code Samples

*

Deletes a {@link KeyVaultRoleDefinition role definition}. Prints out the details of the * {@link Response HTTP response}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.deleteRoleDefinitionWithResponse#KeyVaultRoleScope-String} + * + *
+     * String myRoleDefinitionName = "ccaafb00-31fb-40fe-9ccc-39a2ad2af082";
+     *
+     * keyVaultAccessControlAsyncClient.deleteRoleDefinitionWithResponse(KeyVaultRoleScope.GLOBAL,
+     *     myRoleDefinitionName).subscribe(response ->
+     *         System.out.printf("Response successful with status code: %d. Role definition with name '%s' was"
+     *             + " deleted.%n", response.getStatusCode(), myRoleDefinitionName));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. @@ -678,7 +774,17 @@ Mono> listRoleAssignmentsNextPage(String c *

Code Samples

*

Creates a {@link KeyVaultRoleAssignment role assignment} with a randomly generated name. Prints out the * details of the created {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.createRoleAssignment#KeyVaultRoleScope-String-String} + * + *
+     * String roleDefinitionId = "142e42c1-ab29-4dc7-9dfa-8fd7c0815128";
+     * String servicePrincipalId = "07dca82e-b625-4a60-977b-859d2a162ca7";
+     *
+     * keyVaultAccessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId,
+     *     servicePrincipalId).subscribe(roleAssignment ->
+     *         System.out.printf("Created role assignment with randomly generated name '%s' for principal with id"
+     *             + "'%s'.%n", roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment} * to create. @@ -704,7 +810,18 @@ public Mono createRoleAssignment(KeyVaultRoleScope roleS *

Code Samples

*

Creates a {@link KeyVaultRoleAssignment role assignment}. Prints out the details of the created * {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.createRoleAssignment#KeyVaultRoleScope-String-String-String} + * + *
+     * String myRoleDefinitionId = "e1ca67d0-4332-465c-b9cd-894b2834401b";
+     * String myServicePrincipalId = "31af81fe-6123-4838-92c0-7c2531ec13d7";
+     * String myRoleAssignmentName = "94d7827f-f8c9-4a5d-94fd-9fd2cd02d12f";
+     *
+     * keyVaultAccessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, myRoleDefinitionId,
+     *     myServicePrincipalId, myRoleAssignmentName).subscribe(roleAssignment ->
+     *         System.out.printf("Created role assignment with name '%s' for principal with id '%s'.%n",
+     *             roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment} * to create. @@ -733,7 +850,22 @@ public Mono createRoleAssignment(KeyVaultRoleScope roleS *

Code Samples

*

Creates a {@link KeyVaultRoleAssignment role assignment}. Prints out details of the * {@link Response HTTP response} and the created {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.createRoleAssignmentWithResponse#KeyVaultRoleScope-String-String-String} + * + *
+     * String someRoleDefinitionId = "686b0f78-5012-4def-8a70-eba36aa54d3d";
+     * String someServicePrincipalId = "345ec980-904b-4238-aafc-1eaeed3e23cf";
+     * String someRoleAssignmentName = "1c79927c-6e08-4e5c-8a6c-f58c13c9bbb5";
+     *
+     * keyVaultAccessControlAsyncClient.createRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL,
+     *     someRoleDefinitionId, someServicePrincipalId, someRoleAssignmentName).subscribe(response -> {
+     *         KeyVaultRoleAssignment createdRoleAssignment = response.getValue();
+     *
+     *         System.out.printf("Response successful with status code: %d. Role assignment with name '%s' for"
+     *             + " principal with id '%s' was created.%n", response.getStatusCode(),
+     *             createdRoleAssignment.getName(), createdRoleAssignment.getProperties().getPrincipalId());
+     *     });
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment} * to create. @@ -823,7 +955,15 @@ Mono> createRoleAssignmentWithResponse(KeyVault *

Code Samples

*

Gets a {@link KeyVaultRoleAssignment role assignment}. Prints out details of the retrieved * {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.getRoleAssignment#KeyVaultRoleScope-String} + * + *
+     * String roleAssignmentName = "c5a305c0-e17a-40f5-af79-73801bdd8867";
+     *
+     * keyVaultAccessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName)
+     *     .subscribe(roleAssignment ->
+     *         System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. * @param roleAssignmentName The name used of the {@link KeyVaultRoleAssignment role assignment}. @@ -846,7 +986,16 @@ public Mono getRoleAssignment(KeyVaultRoleScope roleScop *

Code Samples

*

Gets a {@link KeyVaultRoleAssignment role assignment}. Prints out details of the * {@link Response HTTP response} and the retrieved {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.getRoleAssignmentWithResponse#KeyVaultRoleScope-String} + * + *
+     * String myRoleAssignmentName = "76ccbf52-4d49-4fcc-ad3f-044c254be114";
+     *
+     * keyVaultAccessControlAsyncClient.getRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL, myRoleAssignmentName)
+     *     .subscribe(response ->
+     *         System.out.printf("Response successful with status code: %d. Role assignment with name '%s' was"
+     *             + " retrieved.%n", response.getStatusCode(), response.getValue().getName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. * @param roleAssignmentName The name of the {@link KeyVaultRoleAssignment role assignment}. @@ -910,7 +1059,15 @@ Mono> getRoleAssignmentWithResponse(KeyVaultRol * *

Code Samples

*

Deletes a {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.deleteRoleAssignment#KeyVaultRoleScope-String} + * + *
+     * String roleAssignmentName = "f05d11ce-578a-4524-950c-fb4c53e5fb96";
+     *
+     * keyVaultAccessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName)
+     *     .subscribe(unused ->
+     *         System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. * @param roleAssignmentName The name of the {@link KeyVaultRoleAssignment role assignment}. @@ -932,7 +1089,16 @@ public Mono deleteRoleAssignment(KeyVaultRoleScope roleScope, String roleA *

Code Samples

*

Deletes a {@link KeyVaultRoleAssignment role assignment}. Prints out details of the * {@link Response HTTP response}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.deleteRoleAssignmentWithResponse#KeyVaultRoleScope-String} + * + *
+     * String myRoleAssignmentName = "06aaea13-e4f3-4d3f-8a93-088dff6e90ed";
+     *
+     * keyVaultAccessControlAsyncClient.deleteRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL,
+     *     myRoleAssignmentName).subscribe(response ->
+     *         System.out.printf("Response successful with status code: %d. Role assignment with name '%s' was"
+     *             + " deleted.%n", response.getStatusCode(), myRoleAssignmentName));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. * @param roleAssignmentName The name of the {@link KeyVaultRoleAssignment role assignment}. diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClient.java index 4d63af822a605..cb8e9e4cfeb66 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClient.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClient.java @@ -28,7 +28,14 @@ * method on a {@link KeyVaultAccessControlClientBuilder} object.

* *

Samples to construct a sync client

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.instantiation} + * + *
+ * KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder()
+ *     .vaultUrl("https://myaccount.managedhsm.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildClient();
+ * 
+ * * * @see KeyVaultAccessControlClientBuilder */ @@ -61,7 +68,15 @@ public String getVaultUrl() { *

Code Samples

*

Lists all {@link KeyVaultRoleDefinition role definitions}. Prints out the details of the retrieved * {@link KeyVaultRoleDefinition role definitions}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.listRoleDefinitions#KeyVaultRoleScope} + * + *
+     * PagedIterable<KeyVaultRoleDefinition> roleDefinitions =
+     *     keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL);
+     *
+     * roleDefinitions.forEach(roleDefinition ->
+     *     System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope roleScope} of the {@link KeyVaultRoleDefinition role definitions}. * @@ -83,7 +98,15 @@ public PagedIterable listRoleDefinitions(KeyVaultRoleSco *

Code Samples

*

Lists all {@link KeyVaultRoleDefinition role definitions}. Prints out the details of the retrieved * {@link KeyVaultRoleDefinition role definitions}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.listRoleDefinitions#KeyVaultRoleScope-Context} + * + *
+     * PagedIterable<KeyVaultRoleDefinition> keyVaultRoleDefinitions =
+     *     keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL, new Context("key1", "value1"));
+     *
+     * keyVaultRoleDefinitions.forEach(roleDefinition ->
+     *     System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope scope} of the {@link KeyVaultRoleDefinition role definitions}. * @param context Additional {@link Context} that is passed through the HTTP pipeline during the service call. @@ -105,7 +128,14 @@ public PagedIterable listRoleDefinitions(KeyVaultRoleSco *

Code Samples

*

Creates a {@link KeyVaultRoleDefinition role definition} with a randomly generated name. Prints out the * details of the created {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.setRoleDefinition#KeyVaultRoleScope} + * + *
+     * KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL);
+     *
+     * System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n",
+     *     roleDefinition.getName(), roleDefinition.getRoleName());
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * Managed HSM only supports '/'. @@ -127,7 +157,16 @@ public KeyVaultRoleDefinition setRoleDefinition(KeyVaultRoleScope roleScope) { *

Code Samples

*

Creates or updates a {@link KeyVaultRoleDefinition role definition} with a given generated name. Prints out * the details of the created {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.setRoleDefinition#KeyVaultRoleScope-String} + * + *
+     * String myRoleDefinitionName = "b67c3cf4-cbfd-451e-89ab-97c01906a2e0";
+     * KeyVaultRoleDefinition myRoleDefinition =
+     *     keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL, myRoleDefinitionName);
+     *
+     * System.out.printf("Set role definition with name '%s' and role name '%s'.%n", myRoleDefinition.getName(),
+     *     myRoleDefinition.getRoleName());
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * Managed HSM only supports '/'. @@ -151,7 +190,40 @@ public KeyVaultRoleDefinition setRoleDefinition(KeyVaultRoleScope roleScope, Str *

Code Samples

*

Creates or updates a {@link KeyVaultRoleDefinition role definition}. Prints out the details of the * {@link Response HTTP response} and the created {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.setRoleDefinitionWithResponse#SetRoleDefinitionOptions-Context} + * + *
+     * String roleDefinitionName = "a86990e4-2080-4666-bd36-6e1664d3706f";
+     *
+     * List<KeyVaultRoleScope> assignableScopes = new ArrayList<>();
+     * assignableScopes.add(KeyVaultRoleScope.GLOBAL);
+     * assignableScopes.add(KeyVaultRoleScope.KEYS);
+     *
+     * List<KeyVaultDataAction> dataActions = new ArrayList<>();
+     * dataActions.add(KeyVaultDataAction.START_HSM_RESTORE);
+     * dataActions.add(KeyVaultDataAction.START_HSM_BACKUP);
+     * dataActions.add(KeyVaultDataAction.READ_HSM_BACKUP_STATUS);
+     * dataActions.add(KeyVaultDataAction.READ_HSM_RESTORE_STATUS);
+     * dataActions.add(KeyVaultDataAction.BACKUP_HSM_KEYS);
+     * dataActions.add(KeyVaultDataAction.RESTORE_HSM_KEYS);
+     *
+     * List<KeyVaultPermission> permissions = new ArrayList<>();
+     * permissions.add(new KeyVaultPermission(null, null, dataActions, null));
+     *
+     * SetRoleDefinitionOptions setRoleDefinitionOptions =
+     *     new SetRoleDefinitionOptions(KeyVaultRoleScope.GLOBAL, roleDefinitionName)
+     *         .setRoleName("Backup and Restore Role Definition")
+     *         .setDescription("Can backup and restore a whole Managed HSM, as well as individual keys.")
+     *         .setAssignableScopes(assignableScopes)
+     *         .setPermissions(permissions);
+     *
+     * Response<KeyVaultRoleDefinition> response =
+     *     keyVaultAccessControlClient.setRoleDefinitionWithResponse(setRoleDefinitionOptions,
+     *         new Context("key1", "value1"));
+     *
+     * System.out.printf("Response successful with status code: %d. Role definition with name '%s' and role name '%s' "
+     *     + "was set.%n", response.getStatusCode(), response.getValue().getName(), response.getValue().getRoleName());
+     * 
+ * * * @param options Object representing the configurable options to create or update a * {@link KeyVaultRoleDefinition role definition}. @@ -176,7 +248,16 @@ public Response setRoleDefinitionWithResponse(SetRoleDef *

Code Samples

*

Gets a {@link KeyVaultRoleDefinition role definition}. Prints out the details of the retrieved * {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.getRoleDefinition#KeyVaultRoleScope-String} + * + *
+     * String roleDefinitionName = "de8df120-987e-4477-b9cc-570fd219a62c";
+     * KeyVaultRoleDefinition roleDefinition =
+     *     keyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);
+     *
+     * System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(),
+     *     roleDefinition.getRoleName());
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * @param roleDefinitionName The name used of the {@link KeyVaultRoleDefinition role definition}. @@ -199,7 +280,18 @@ public KeyVaultRoleDefinition getRoleDefinition(KeyVaultRoleScope roleScope, Str *

Code Samples

*

Gets a {@link KeyVaultRoleDefinition role definition}. Prints out the details of the * {@link Response HTTP response} and the retrieved {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.getRoleDefinitionWithResponse#KeyVaultRoleScope-String-Context} + * + *
+     * String myRoleDefinitionName = "cb15ef18-b32c-4224-b048-3a91cd68acc3";
+     * Response<KeyVaultRoleDefinition> response =
+     *     keyVaultAccessControlClient.getRoleDefinitionWithResponse(KeyVaultRoleScope.GLOBAL, myRoleDefinitionName,
+     *         new Context("key1", "value1"));
+     *
+     * System.out.printf("Response successful with status code: %d. Role definition with name '%s' and role name '%s'"
+     *     + " was retrieved.%n", response.getStatusCode(), response.getValue().getName(),
+     *     response.getValue().getRoleName());
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. @@ -224,7 +316,15 @@ public Response getRoleDefinitionWithResponse(KeyVaultRo * *

Code Samples

*

Deletes a {@link KeyVaultRoleDefinition role definition}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.deleteRoleDefinition#KeyVaultRoleScope-String} + * + *
+     * String roleDefinitionName = "6a709e6e-8964-4012-a99b-6b0131e8ce40";
+     *
+     * keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);
+     *
+     * System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName);
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * Managed HSM only supports '/'. @@ -245,7 +345,17 @@ public void deleteRoleDefinition(KeyVaultRoleScope roleScope, String roleDefinit *

Code Samples

*

Deletes a {@link KeyVaultRoleDefinition role definition}. Prints out the details of the * {@link Response HTTP response}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.deleteRoleDefinitionWithResponse#KeyVaultRoleScope-String-Context} + * + *
+     * String myRoleDefinitionName = "6b2d0b58-4108-44d6-b7e0-4fd02f77fe7e";
+     * Response<Void> response =
+     *     keyVaultAccessControlClient.deleteRoleDefinitionWithResponse(KeyVaultRoleScope.GLOBAL, myRoleDefinitionName,
+     *         new Context("key1", "value1"));
+     *
+     * System.out.printf("Response successful with status code: %d. Role definition with name '%s' was deleted.%n",
+     *     response.getStatusCode(), myRoleDefinitionName);
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. @@ -271,7 +381,15 @@ public Response deleteRoleDefinitionWithResponse(KeyVaultRoleScope roleSco *

Code Samples

*

Lists all {@link KeyVaultRoleAssignment role assignments}. Prints out the details of the retrieved * {@link KeyVaultRoleAssignment role assignments}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.listRoleAssignments#KeyVaultRoleScope} + * + *
+     * PagedIterable<KeyVaultRoleAssignment> roleAssignments =
+     *     keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL);
+     *
+     * roleAssignments.forEach(roleAssignment ->
+     *     System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope scope} of the {@link KeyVaultRoleAssignment role assignment}. * @@ -293,7 +411,15 @@ public PagedIterable listRoleAssignments(KeyVaultRoleSco *

Code Samples

*

Lists all {@link KeyVaultRoleAssignment role assignments}. Prints out the details of the retrieved * {@link KeyVaultRoleAssignment role assignments}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.listRoleAssignments#KeyVaultRoleScope-Context} + * + *
+     * PagedIterable<KeyVaultRoleAssignment> keyVaultRoleAssignments =
+     *     keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL, new Context("key1", "value1"));
+     *
+     * keyVaultRoleAssignments.forEach(roleAssignment ->
+     *     System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()));
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope scope} of the {@link KeyVaultRoleAssignment role assignment}. * @param context Additional context that is passed through the HTTP pipeline during the service call. @@ -315,7 +441,18 @@ public PagedIterable listRoleAssignments(KeyVaultRoleSco *

Code Samples

*

Creates a {@link KeyVaultRoleAssignment role assignment} with a randomly generated name. Prints out the * details of the created {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.createRoleAssignment#KeyVaultRoleScope-String-String} + * + *
+     * String roleDefinitionId = "b0b43a39-920c-475b-b34c-32ecc2bbb0ea";
+     * String servicePrincipalId = "169d6a86-61b3-4615-ac7e-2da09edfeed4";
+     * KeyVaultRoleAssignment roleAssignment =
+     *     keyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId,
+     *         servicePrincipalId);
+     *
+     * System.out.printf("Created role assignment with randomly generated name '%s' for principal with id '%s'.%n",
+     *     roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId());
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment} * to create. @@ -342,7 +479,19 @@ public KeyVaultRoleAssignment createRoleAssignment(KeyVaultRoleScope roleScope, *

Code Samples

*

Creates a {@link KeyVaultRoleAssignment role assignment}. Prints out the details of the created * {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.createRoleAssignment#KeyVaultRoleScope-String-String-String} + * + *
+     * String myRoleDefinitionId = "c7d4f70f-944d-494a-a73e-ff62fe7f04da";
+     * String myServicePrincipalId = "4196fc8f-7312-46b9-9a08-05bf44fdff37";
+     * String myRoleAssignmentName = "d80e9366-47a6-4f42-ba84-f2eefb084972";
+     * KeyVaultRoleAssignment myRoleAssignment =
+     *     keyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, myRoleDefinitionId,
+     *         myServicePrincipalId, myRoleAssignmentName);
+     *
+     * System.out.printf("Created role assignment with name '%s' for principal with id '%s'.%n",
+     *     myRoleAssignment.getName(), myRoleAssignment.getProperties().getPrincipalId());
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment} * to create. @@ -371,7 +520,22 @@ public KeyVaultRoleAssignment createRoleAssignment(KeyVaultRoleScope roleScope, *

Code Samples

*

Creates a {@link KeyVaultRoleAssignment role assignment}. Prints out details of the * {@link Response HTTP response} and the created {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.createRoleAssignmentWithResponse#KeyVaultRoleScope-String-String-String-Context} + * + *
+     * String someRoleDefinitionId = "11385c39-5efa-4e5f-8748-055aa51d4d23";
+     * String someServicePrincipalId = "eab943f7-a204-4434-9681-ef2cc0c85b51";
+     * String someRoleAssignmentName = "4d95e0ea-4808-43a4-b7f9-d9e61dba7ea9";
+     *
+     * Response<KeyVaultRoleAssignment> response =
+     *     keyVaultAccessControlClient.createRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL, someRoleDefinitionId,
+     *         someServicePrincipalId, someRoleAssignmentName, new Context("key1", "value1"));
+     * KeyVaultRoleAssignment createdRoleAssignment = response.getValue();
+     *
+     * System.out.printf("Response successful with status code: %d. Role assignment with name '%s' for principal with"
+     *     + "id '%s' was created.%n", response.getStatusCode(), createdRoleAssignment.getName(),
+     *     createdRoleAssignment.getProperties().getPrincipalId());
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment} * to create. @@ -406,7 +570,15 @@ public Response createRoleAssignmentWithResponse(KeyVaul *

Code Samples

*

Deletes a {@link KeyVaultRoleAssignment role assignment}. Prints out details of the retrieved * {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.getRoleAssignment#KeyVaultRoleScope-String} + * + *
+     * String roleAssignmentName = "06d1ae8b-0791-4f02-b976-f631251f5a95";
+     * KeyVaultRoleAssignment roleAssignment =
+     *     keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);
+     *
+     * System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName());
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. * @param roleAssignmentName The name of the {@link KeyVaultRoleAssignment role assignment}. @@ -429,7 +601,17 @@ public KeyVaultRoleAssignment getRoleAssignment(KeyVaultRoleScope roleScope, Str *

Code Samples

*

Deletes a {@link KeyVaultRoleAssignment role assignment}. Prints out details of the * {@link Response HTTP response} and the retrieved {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.getRoleAssignmentWithResponse#KeyVaultRoleScope-String-Context} + * + *
+     * String myRoleAssignmentName = "b4a970d5-c581-4760-bba5-61d3d5aa24f9";
+     * Response<KeyVaultRoleAssignment> response =
+     *     keyVaultAccessControlClient.getRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL, myRoleAssignmentName,
+     *         new Context("key1", "value1"));
+     *
+     * System.out.printf("Response successful with status code: %d. Role assignment with name '%s' was retrieved.%n",
+     *     response.getStatusCode(), response.getValue().getName());
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. * @param roleAssignmentName The name of the {@link KeyVaultRoleAssignment role assignment}. @@ -453,7 +635,15 @@ public Response getRoleAssignmentWithResponse(KeyVaultRo * *

Code Samples

*

Deletes a {@link KeyVaultRoleAssignment role assignment}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.deleteRoleAssignment#KeyVaultRoleScope-String} + * + *
+     * String roleAssignmentName = "c3ed874a-64a9-4a87-8581-2a1ad84b9ddb";
+     *
+     * keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);
+     *
+     * System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName);
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. * @param roleAssignmentName The name of the {@link KeyVaultRoleAssignment role assignment}. @@ -473,7 +663,17 @@ public void deleteRoleAssignment(KeyVaultRoleScope roleScope, String roleAssignm *

Code Samples

*

Deletes a {@link KeyVaultRoleAssignment role assignment}. Prints out details of the * {@link Response HTTP response}.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.deleteRoleAssignmentWithResponse#KeyVaultRoleScope-String-Context} + * + *
+     * String myRoleAssignmentName = "8ac293e1-1ac8-4a71-b254-7caf9f7c2646";
+     * Response<Void> response =
+     *     keyVaultAccessControlClient.deleteRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL, myRoleAssignmentName,
+     *         new Context("key1", "value1"));
+     *
+     * System.out.printf("Response successful with status code: %d. Role assignment with name '%s' was deleted.%n",
+     *     response.getStatusCode(), myRoleAssignmentName);
+     * 
+ * * * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. * @param roleAssignmentName The name of the {@link KeyVaultRoleAssignment role assignment}. diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilder.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilder.java index cdd911a94263c..a62746bc8a289 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilder.java @@ -43,9 +43,23 @@ * an {@link KeyVaultAccessControlAsyncClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

* *

Samples to construct a sync client

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlClient.instantiation} + * + *
+ * KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder()
+ *     .vaultUrl("https://myaccount.managedhsm.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildClient();
+ * 
+ * *

Samples to construct an async client

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultAccessControlAsyncClient.instantiation} + * + *
+ * KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder()
+ *     .vaultUrl("https://myaccount.managedhsm.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildAsyncClient();
+ * 
+ * * * @see KeyVaultAccessControlClient * @see KeyVaultAccessControlAsyncClient diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationServiceVersion.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationServiceVersion.java index 7a92b7357de9d..9a571cde4ecb2 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationServiceVersion.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationServiceVersion.java @@ -9,7 +9,14 @@ * The versions of Azure Key Vault Administration service supported by this client library. */ public enum KeyVaultAdministrationServiceVersion implements ServiceVersion { + /** + * Service version {@code 7.2}. + */ V7_2("7.2"), + + /** + * Service version {@code 7.3-preview}. + */ V7_3_PREVIEW("7.3-preview"); private final String version; diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClient.java index 8e590f8e20610..6733da603051e 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClient.java @@ -57,7 +57,14 @@ * method on a {@link KeyVaultBackupClientBuilder} object.

* *

Samples to construct an async client

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupAsyncClient.instantiation} + * + *
+ * KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder()
+ *     .vaultUrl("https://myaccount.managedhsm.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildAsyncClient();
+ * 
+ * * * @see KeyVaultBackupClientBuilder */ @@ -141,7 +148,23 @@ HttpPipeline getHttpPipeline() { *

Starts a {@link KeyVaultBackupOperation backup operation}, polls for its status and waits for it to complete. * Prints out the details of the operation's final result in case of success or prints out details of an error in * case the operation fails.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupAsyncClient.beginBackup#String-String} + * + *
+     * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
+     * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"
+     *     + "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";
+     *
+     * client.beginBackup(blobStorageUrl, sasToken)
+     *     .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval.
+     *     .doOnError(e -> System.out.printf("Backup failed with error: %s.%n", e.getMessage()))
+     *     .doOnNext(pollResponse ->
+     *         System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()))
+     *     .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)
+     *     .flatMap(AsyncPollResponse::getFinalResult)
+     *     .subscribe(folderUrl ->
+     *         System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl));
+     * 
+ * * * @param blobStorageUrl The URL for the Blob Storage resource where the backup will be located. * @param sasToken A Shared Access Signature (SAS) token to authorize access to the blob. @@ -303,7 +326,22 @@ private static LongRunningOperationStatus toLongRunningOperationStatus(String op *

Code Samples

*

Starts a {@link KeyVaultRestoreOperation restore operation}, polls for its status and waits for it to * complete. Prints out error details in case the operation fails.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupAsyncClient.beginRestore#String-String} + * + *
+     * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
+     * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"
+     *     + "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";
+     *
+     * client.beginRestore(folderUrl, sasToken)
+     *     .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval.
+     *     .doOnError(e -> System.out.printf("Restore failed with error: %s.%n", e.getMessage()))
+     *     .doOnNext(pollResponse ->
+     *         System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()))
+     *     .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)
+     *     .flatMap(AsyncPollResponse::getFinalResult)
+     *     .subscribe(unused -> System.out.printf("Backup restored successfully.%n"));
+     * 
+ * * * @param folderUrl The URL for the Blob Storage resource where the backup is located, including the path to * the blob container where the backup resides. This would be the exact value that is returned as the result of a @@ -449,7 +487,23 @@ private static Mono> processRestoreOperat *

Code Samples

*

Starts a {@link KeyVaultSelectiveKeyRestoreOperation selective key restore operation}, polls for its status * and waits for it to complete. Prints out error details in case the operation fails.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupAsyncClient.beginSelectiveKeyRestore#String-String-String} + * + *
+     * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
+     * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"
+     *     + "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";
+     * String keyName = "myKey";
+     *
+     * client.beginSelectiveKeyRestore(folderUrl, sasToken, keyName)
+     *     .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval.
+     *     .doOnError(e -> System.out.printf("Key restoration failed with error: %s.%n", e.getMessage()))
+     *     .doOnNext(pollResponse ->
+     *         System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()))
+     *     .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)
+     *     .flatMap(AsyncPollResponse::getFinalResult)
+     *     .subscribe(unused -> System.out.printf("Key restored successfully.%n"));
+     * 
+ * * * @param keyName The name of the key to be restored. * @param folderUrl The URL for the Blob Storage resource where the backup is located, including the path to diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClient.java index 2c7fae0e6a2d0..c3020b71b2410 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClient.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClient.java @@ -22,7 +22,14 @@ * method on a {@link KeyVaultBackupClientBuilder} object.

* *

Samples to construct a sync client

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupClient.instantiation} + * + *
+ * KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder()
+ *     .vaultUrl("https://myaccount.managedhsm.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildClient();
+ * 
+ * * * @see KeyVaultBackupClientBuilder */ @@ -55,7 +62,31 @@ public String getVaultUrl() { *

Starts a {@link KeyVaultBackupOperation backup operation}, polls for its status and waits for it to complete. * Prints out the details of the operation's final result in case of success or prints out error details in case the * operation fails.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupClient.beginBackup#String-String} + * + *
+     * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
+     * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"
+     *     + "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";
+     *
+     * SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken);
+     *
+     * PollResponse<KeyVaultBackupOperation> pollResponse = backupPoller.poll();
+     *
+     * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
+     *
+     * PollResponse<KeyVaultBackupOperation> finalPollResponse = backupPoller.waitForCompletion();
+     *
+     * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
+     *     String folderUrl = backupPoller.getFinalResult();
+     *
+     *     System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl);
+     * } else {
+     *     KeyVaultBackupOperation operation = backupPoller.poll().getValue();
+     *
+     *     System.out.printf("Backup failed with error: %s.%n", operation.getError().getMessage());
+     * }
+     * 
+ * * * @param blobStorageUrl The URL for the Blob Storage resource where the backup will be located. * @param sasToken A Shared Access Signature (SAS) token to authorize access to the blob. @@ -76,7 +107,31 @@ public SyncPoller beginBackup(String blobStorag *

Code Samples

*

Starts a {@link KeyVaultRestoreOperation restore operation}, polls for its status and waits for it to * complete. Prints out error details in case the operation fails.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupClient.beginBackup#String-String} + * + *
+     * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
+     * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"
+     *     + "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";
+     *
+     * SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken);
+     *
+     * PollResponse<KeyVaultBackupOperation> pollResponse = backupPoller.poll();
+     *
+     * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
+     *
+     * PollResponse<KeyVaultBackupOperation> finalPollResponse = backupPoller.waitForCompletion();
+     *
+     * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
+     *     String folderUrl = backupPoller.getFinalResult();
+     *
+     *     System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl);
+     * } else {
+     *     KeyVaultBackupOperation operation = backupPoller.poll().getValue();
+     *
+     *     System.out.printf("Backup failed with error: %s.%n", operation.getError().getMessage());
+     * }
+     * 
+ * * * @param folderUrl The URL for the Blob Storage resource where the backup is located, including the path to * the blob container where the backup resides. This would be the exact value that is returned as the result of a @@ -101,7 +156,31 @@ public SyncPoller beginRestore( *

Code Samples

*

Starts a {@link KeyVaultSelectiveKeyRestoreOperation selective key restore operation}, polls for its status * and waits for it to complete. Prints out error details in case the operation fails.

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupClient.beginSelectiveKeyRestore#String-String-String} + * + *
+     * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
+     * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"
+     *     + "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";
+     * String keyName = "myKey";
+     *
+     * SyncPoller<KeyVaultSelectiveKeyRestoreOperation, KeyVaultSelectiveKeyRestoreResult> backupPoller =
+     *     client.beginSelectiveKeyRestore(folderUrl, sasToken, keyName);
+     *
+     * PollResponse<KeyVaultSelectiveKeyRestoreOperation> pollResponse = backupPoller.poll();
+     *
+     * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
+     *
+     * PollResponse<KeyVaultSelectiveKeyRestoreOperation> finalPollResponse = backupPoller.waitForCompletion();
+     *
+     * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
+     *     System.out.printf("Key restored successfully.%n");
+     * } else {
+     *     KeyVaultSelectiveKeyRestoreOperation operation = backupPoller.poll().getValue();
+     *
+     *     System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage());
+     * }
+     * 
+ * * * @param keyName The name of the key to be restored. * @param folderUrl The URL for the Blob Storage resource where the backup is located, including the path to diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilder.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilder.java index 5ff890f1111e0..428fbe8374fde 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilder.java @@ -42,9 +42,23 @@ * an {@link KeyVaultBackupAsyncClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

* *

Samples to construct a sync client

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupClient.instantiation} + * + *
+ * KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder()
+ *     .vaultUrl("https://myaccount.managedhsm.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildClient();
+ * 
+ * *

Samples to construct an async client

- * {@codesnippet com.azure.security.keyvault.administration.keyVaultBackupAsyncClient.instantiation} + * + *
+ * KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder()
+ *     .vaultUrl("https://myaccount.managedhsm.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildAsyncClient();
+ * 
+ * * * @see KeyVaultBackupClient * @see KeyVaultBackupAsyncClient diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleScope.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleScope.java index 6bd6295819ee2..2d9a9b61364f8 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleScope.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleScope.java @@ -12,7 +12,14 @@ * A class that defines the scope of a role. */ public final class KeyVaultRoleScope extends ExpandableStringEnum { + /** + * Global role scope. + */ public static final KeyVaultRoleScope GLOBAL = fromString("/"); + + /** + * Keys role scope. + */ public static final KeyVaultRoleScope KEYS = fromString("/keys"); /** diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/ReadmeSamples.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/ReadmeSamples.java index 85aa3e830ff16..0bdd7a79214f2 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/ReadmeSamples.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/ReadmeSamples.java @@ -3,6 +3,7 @@ package com.azure.security.keyvault.administration; +import com.azure.core.exception.HttpResponseException; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.polling.AsyncPollResponse; import com.azure.core.util.polling.LongRunningOperationStatus; @@ -21,95 +22,113 @@ import java.time.Duration; /** - * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS ARE USED TO EXTRACT - * APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING LINE NUMBERS OF EXISTING CODE - * SAMPLES. - * * Class containing code snippets that will be injected to README.md. */ +@SuppressWarnings("unused") public class ReadmeSamples { private final KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); - private final KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = null; + private final KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = + new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); private final KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder() .vaultUrl("") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); - private final KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = null; + private final KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = + new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); /** * Code sample for creating a {@link KeyVaultAccessControlClient}. */ public void createAccessControlClient() { + // BEGIN: readme-sample-createAccessControlClient KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); + // END: readme-sample-createAccessControlClient } /** * Code sample for listing {@link KeyVaultRoleDefinition role definitions}. */ public void listRoleDefinitions() { + // BEGIN: readme-sample-listRoleDefinitions PagedIterable roleDefinitions = keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL); roleDefinitions.forEach(roleDefinition -> System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); + // END: readme-sample-listRoleDefinitions } /** * Code sample for creating or updating a {@link KeyVaultRoleDefinition role definition}. */ public void setRoleDefinition() { + // BEGIN: readme-sample-setRoleDefinition KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL); System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n", roleDefinition.getName(), roleDefinition.getRoleName()); + // END: readme-sample-setRoleDefinition } /** * Code sample for getting a {@link KeyVaultRoleDefinition role definition}. */ public void getRoleDefinition() { + // BEGIN: readme-sample-getRoleDefinition String roleDefinitionName = ""; KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(), roleDefinition.getRoleName()); + // END: readme-sample-getRoleDefinition } /** * Code sample for deleting a {@link KeyVaultRoleDefinition role definition}. */ public void deleteRoleDefinition() { + // BEGIN: readme-sample-deleteRoleDefinition String roleDefinitionName = ""; keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName); + // END: readme-sample-deleteRoleDefinition } /** * Code sample for listing {@link KeyVaultRoleAssignment role assignments}. */ public void listRoleAssignments() { + // BEGIN: readme-sample-listRoleAssignments PagedIterable roleAssignments = keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL); roleAssignments.forEach(roleAssignment -> System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); + // END: readme-sample-listRoleAssignments } /** * Code sample for creating a {@link KeyVaultRoleAssignment role assignment}. */ public void createRoleAssignment() { + // BEGIN: readme-sample-createRoleAssignment String roleDefinitionId = ""; String servicePrincipalId = ""; KeyVaultRoleAssignment roleAssignment = @@ -118,84 +137,100 @@ public void createRoleAssignment() { System.out.printf("Created role assignment with randomly generated name '%s' for principal with id '%s'.%n", roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId()); + // END: readme-sample-createRoleAssignment } /** * Code sample for getting a {@link KeyVaultRoleAssignment role assignment}. */ public void getRoleAssignment() { + // BEGIN: readme-sample-getRoleAssignment String roleAssignmentName = ""; KeyVaultRoleAssignment roleAssignment = keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()); + // END: readme-sample-getRoleAssignment } /** * Code sample for deleting a {@link KeyVaultRoleAssignment role assignment}. */ public void deleteRoleAssignment() { + // BEGIN: readme-sample-deleteRoleAssignment String roleAssignmentName = ""; keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName); + // END: readme-sample-deleteRoleAssignment } /** * Code sample for listing {@link KeyVaultRoleDefinition role definitions} asynchronously. */ public void listRoleDefinitionsAsync() { + // BEGIN: readme-sample-listRoleDefinitionsAsync keyVaultAccessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL) .subscribe(roleDefinition -> System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); + // END: readme-sample-listRoleDefinitionsAsync } /** * Code sample for creating or updating a {@link KeyVaultRoleDefinition role definition} asynchronously. */ public void setRoleDefinitionAsync() { + // BEGIN: readme-sample-setRoleDefinitionAsync keyVaultAccessControlAsyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL) .subscribe(roleDefinition -> System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n", roleDefinition.getName(), roleDefinition.getRoleName())); + // END: readme-sample-setRoleDefinitionAsync } /** * Code sample for getting a {@link KeyVaultRoleDefinition role definition} asynchronously. */ public void getRoleDefinitionAsync() { + // BEGIN: readme-sample-getRoleDefinitionAsync String roleDefinitionName = ""; keyVaultAccessControlAsyncClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) .subscribe(roleDefinition -> System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(), roleDefinition.getRoleName())); + // END: readme-sample-getRoleDefinitionAsync } /** * Code sample for deleting a {@link KeyVaultRoleDefinition role definition} asynchronously. */ public void deleteRoleDefinitionAsync() { + // BEGIN: readme-sample-deleteRoleDefinitionAsync String roleDefinitionName = ""; keyVaultAccessControlAsyncClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) .subscribe(unused -> System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName)); + // END: readme-sample-deleteRoleDefinitionAsync } /** * Code sample for listing {@link KeyVaultRoleAssignment role assignments} asynchronously. */ public void listRoleAssignmentsAsync() { + // BEGIN: readme-sample-listRoleAssignmentsAsync keyVaultAccessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL) .subscribe(roleAssignment -> System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); + // END: readme-sample-listRoleAssignmentsAsync } /** * Code sample for creating a {@link KeyVaultRoleAssignment role assignment} asynchronously. */ public void createRoleAssignmentAsync() { + // BEGIN: readme-sample-createRoleAssignmentAsync String roleDefinitionId = ""; String servicePrincipalId = ""; @@ -203,44 +238,52 @@ public void createRoleAssignmentAsync() { servicePrincipalId).subscribe(roleAssignment -> System.out.printf("Created role assignment with randomly generated name '%s' for principal with id" + "'%s'.%n", roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId())); + // END: readme-sample-createRoleAssignmentAsync } /** * Code sample for getting a {@link KeyVaultRoleAssignment role assignment} asynchronously. */ public void getRoleAssignmentAsync() { + // BEGIN: readme-sample-getRoleAssignmentAsync String roleAssignmentName = ""; keyVaultAccessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) .subscribe(roleAssignment -> System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); + // END: readme-sample-getRoleAssignmentAsync } /** * Code sample for deleting a {@link KeyVaultRoleAssignment role assignment} asynchronously. */ public void deleteRoleAssignmentAsync() { + // BEGIN: readme-sample-deleteRoleAssignmentAsync String roleAssignmentName = ""; keyVaultAccessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) .subscribe(unused -> System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName)); + // END: readme-sample-deleteRoleAssignmentAsync } /** * Code sample for creating a {@link KeyVaultBackupClient}. */ public void createBackupClient() { + // BEGIN: readme-sample-createBackupClient KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder() .vaultUrl("") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); + // END: readme-sample-createBackupClient } /** * Code sample for starting a {@link KeyVaultBackupOperation backup operation}. */ public void beginBackup() { + // BEGIN: readme-sample-beginBackup String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; @@ -262,12 +305,14 @@ public void beginBackup() { System.out.printf("Backup failed with error: %s.%n", operation.getError().getMessage()); } + // END: readme-sample-beginBackup } /** * Code sample for starting a {@link KeyVaultRestoreOperation restore operation}. */ public void beginRestore() { + // BEGIN: readme-sample-beginRestore String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; @@ -287,12 +332,14 @@ public void beginRestore() { System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage()); } + // END: readme-sample-beginRestore } /** * Code sample for starting a {@link KeyVaultSelectiveKeyRestoreOperation selective key restore operation}. */ public void beginSelectiveKeyRestore() { + // BEGIN: readme-sample-beginSelectiveKeyRestore String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; String keyName = "myKey"; @@ -313,12 +360,14 @@ public void beginSelectiveKeyRestore() { System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage()); } + // END: readme-sample-beginSelectiveKeyRestore } /** * Code sample for starting a {@link KeyVaultBackupOperation backup operation} asynchronously. */ public void beginBackupAsync() { + // BEGIN: readme-sample-beginBackupAsync String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; @@ -331,12 +380,14 @@ public void beginBackupAsync() { .flatMap(AsyncPollResponse::getFinalResult) .subscribe(folderUrl -> System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl)); + // END: readme-sample-beginBackupAsync } /** * Code sample for starting a {@link KeyVaultRestoreOperation restore operation} asynchronously. */ public void beginRestoreAsync() { + // BEGIN: readme-sample-beginRestoreAsync String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; @@ -348,6 +399,7 @@ public void beginRestoreAsync() { .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(unused -> System.out.printf("Backup restored successfully.%n")); + // END: readme-sample-beginRestoreAsync } /** @@ -355,6 +407,7 @@ public void beginRestoreAsync() { * asynchronously. */ public void beginSelectiveKeyRestoreAsync() { + // BEGIN: readme-sample-beginSelectiveKeyRestoreAsync String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D"; String keyName = "myKey"; @@ -367,5 +420,16 @@ public void beginSelectiveKeyRestoreAsync() { .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(unused -> System.out.printf("Key restored successfully.%n")); + // END: readme-sample-beginSelectiveKeyRestoreAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, ""); + } catch (HttpResponseException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/README.md b/sdk/keyvault/azure-security-keyvault-certificates/README.md index c6949687a3ca9..656871ac1ca1c 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/README.md +++ b/sdk/keyvault/azure-security-keyvault-certificates/README.md @@ -24,14 +24,14 @@ Maven dependency for the Azure Key Vault Certificate client library. Add it to y - [Azure Subscription][azure_subscription] - An existing [Azure Key Vault][azure_keyvault]. If you need to create a Key Vault, you can use the [Azure Cloud Shell][azure_cloud_shell] to create one with this Azure CLI command. Replace `` and `` with your own, unique names: - ```Bash - az keyvault create --resource-group --name - ``` +```bash +az keyvault create --resource-group --name +``` ### Authenticate the client In order to interact with the Azure Key Vault service, you'll need to create an instance of the [CertificateClient](#create-certificate-client) class. You need a **vault url** and **client secret credentials (client id, client secret, tenant id)** to instantiate a client object using the `DefaultAzureCredential` examples shown in this document. -The `DefaultAzureCredential` way of authentication by providing client secret credentials is being used in this getting started section but you can find more ways to authenticate with [azure-identity][azure_identity]. +The `DefaultAzureCredential` way of authentication by providing client secret credentials is being used in this getting started section, but you can find more ways to authenticate with [azure-identity][azure_identity]. #### Create/Get credentials To create/get client secret credentials you can use the [Azure Portal][azure_create_application_in_portal], [Azure CLI][azure_keyvault_cli_full] or [Azure Cloud Shell][azure_cloud_shell] @@ -40,55 +40,51 @@ Here is an [Azure Cloud Shell][azure_cloud_shell] snippet below to * Create a service principal and configure its access to Azure resources: - ```Bash - az ad sp create-for-rbac -n --skip-assignment - ``` +```bash +az ad sp create-for-rbac -n --skip-assignment +``` - Output: +Output: - ```json - { - "appId": "generated-app-ID", - "displayName": "dummy-app-name", - "name": "http://dummy-app-name", - "password": "random-password", - "tenant": "tenant-ID" - } - ``` +```json +{ + "appId": "generated-app-ID", + "displayName": "dummy-app-name", + "name": "http://dummy-app-name", + "password": "random-password", + "tenant": "tenant-ID" +} +``` * Use the above returned credentials information to set the **AZURE_CLIENT_ID** (appId), **AZURE_CLIENT_SECRET** (password), and **AZURE_TENANT_ID** (tenantId) environment variables. The following example shows a way to do this in Bash: - ```Bash - export AZURE_CLIENT_ID="generated-app-ID" - export AZURE_CLIENT_SECRET="random-password" - export AZURE_TENANT_ID="tenant-ID" - ``` +```bash +export AZURE_CLIENT_ID="generated-app-ID" +export AZURE_CLIENT_SECRET="random-password" +export AZURE_TENANT_ID="tenant-ID" +``` * Grant the aforementioned application authorization to perform certificate operations on the Key Vault: - ```Bash - az keyvault set-policy --name --spn $AZURE_CLIENT_ID --certificate-permissions backup delete get list create update - ``` +```bash +az keyvault set-policy --name --spn $AZURE_CLIENT_ID --certificate-permissions backup delete get list create update +``` - > --certificate-permissions: - > Accepted values: backup, create, delete, deleteissuers, get, getissuers, import, list, listissuers, managecontacts, manageissuers, purge, recover, restore, setissuers, update +> --certificate-permissions: +> Accepted values: backup, create, delete, deleteissuers, get, getissuers, import, list, listissuers, managecontacts, manageissuers, purge, recover, restore, setissuers, update - If you have enabled role-based access control (RBAC) for Key Vault instead, you can find roles like "Key Vault Certificates Officer" in our [RBAC guide][rbac_guide]. +If you have enabled role-based access control (RBAC) for Key Vault instead, you can find roles like "Key Vault Certificates Officer" in our [RBAC guide][rbac_guide]. * Use the aforementioned Key Vault name to retrieve details of your Key Vault, which also contain your Key Vault URL: - ```Bash - az keyvault show --name - ``` +```bash +az keyvault show --name +``` #### Create certificate client Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET**, and **AZURE_TENANT_ID** environment variables and replaced **your-key-vault-url** with the URI returned above, you can create the CertificateClient: -```Java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.certificates.CertificateClient; -import com.azure.security.keyvault.certificates.CertificateClientBuilder; - +```java readme-sample-createCertificateClient CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl("") .credential(new DefaultAzureCredentialBuilder().build()) @@ -120,22 +116,7 @@ The following sections provide several code snippets covering some of the most c Create a certificate to be stored in the Azure Key Vault. - `beginCreateCertificate` creates a new certificate in the Azure Key Vault. If a certificate with the same name already exists then a new version of the certificate is created. -```Java -import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.core.util.polling.SyncPoller; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.certificates.CertificateClient; -import com.azure.security.keyvault.certificates.CertificateClientBuilder; -import com.azure.security.keyvault.certificates.models.CertificateOperation; -import com.azure.security.keyvault.certificates.models.CertificatePolicy; -import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; -import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; - -CertificateClient certificateClient = new CertificateClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - +```java readme-sample-createCertificate SyncPoller certificatePoller = certificateClient.beginCreateCertificate("certificateName", CertificatePolicy.getDefault()); certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); @@ -146,16 +127,16 @@ System.out.printf("Certificate created with name \"%s\"%n", certificate.getName( ### Retrieve a certificate Retrieve a previously stored certificate by calling `getCertificate` or `getCertificateVersion`. -```Java +```java readme-sample-retrieveCertificate KeyVaultCertificateWithPolicy certificate = certificateClient.getCertificate(""); -System.out.printf("Recevied certificate with name \"%s\", version %s and secret id %s%n", +System.out.printf("Received certificate with name \"%s\", version %s and secret id %s%n", certificate.getProperties().getName(), certificate.getProperties().getVersion(), certificate.getSecretId()); ``` ### Update an existing certificate Update an existing certificate by calling `updateCertificateProperties`. -```Java +```java readme-sample-updateCertificate // Get the certificate to update. KeyVaultCertificate certificate = certificateClient.getCertificate(""); // Update certificate enabled status. @@ -168,7 +149,7 @@ System.out.printf("Updated certificate with name \"%s\" and enabled status \"%s\ ### Delete a certificate Delete an existing certificate by calling `beginDeleteCertificate`. -```Java +```java readme-sample-deleteCertificate SyncPoller deleteCertificatePoller = certificateClient.beginDeleteCertificate(""); @@ -186,7 +167,7 @@ deleteCertificatePoller.waitForCompletion(); ### List certificates List the certificates in the key vault by calling `listPropertiesOfCertificates`. -```java +```java readme-sample-listCertificates // List operations don't return the certificates with their full information. So, for each returned certificate we call // getCertificate to get the certificate with all its properties excluding the policy. for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) { @@ -211,16 +192,7 @@ The following sections provide several code snippets covering some of the most c Create a certificate to be stored in the Azure Key Vault. - `beginCreateCertificate` creates a new certificate in the Azure Key Vault. If a certificate with same name already exists then a new version of the certificate is created. -```Java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.certificates.CertificateClient; -import com.azure.security.keyvault.certificates.CertificateClientBuilder; - -CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - +```java readme-sample-createCertificateAsync // Creates a certificate using the default policy and polls on its progress. certificateAsyncClient.beginCreateCertificate("", CertificatePolicy.getDefault()) .subscribe(pollResponse -> { @@ -234,7 +206,7 @@ certificateAsyncClient.beginCreateCertificate("", CertificateP ### Retrieve a certificate asynchronously Retrieve a previously stored certificate by calling `getCertificate` or `getCertificateVersion`. -```Java +```java readme-sample-retrieveCertificateAsync certificateAsyncClient.getCertificate("") .subscribe(certificateResponse -> System.out.printf("Certificate was returned with name \"%s\" and secretId %s%n", @@ -244,23 +216,20 @@ certificateAsyncClient.getCertificate("") ### Update an existing certificate asynchronously Update an existing certificate by calling `updateCertificateProperties`. -```Java +```java readme-sample-updateCertificateAsync certificateAsyncClient.getCertificate("") - .subscribe(certificateResponseValue -> { - KeyVaultCertificate certificate = certificateResponseValue; + .flatMap(certificate -> { // Update enabled status of the certificate. certificate.getProperties().setEnabled(false); - certificateAsyncClient.updateCertificateProperties(certificate.getProperties()) - .subscribe(certificateResponse -> - System.out.printf("Certificate's enabled status: %s%n", - certificateResponse.getProperties().isEnabled())); - }); + return certificateAsyncClient.updateCertificateProperties(certificate.getProperties()); + }).subscribe(certificateResponse -> System.out.printf("Certificate's enabled status: %s%n", + certificateResponse.getProperties().isEnabled())); ``` ### Delete a certificate asynchronously Delete an existing certificate by calling `beginDeleteCertificate`. -```java +```java readme-sample-deleteCertificateAsync certificateAsyncClient.beginDeleteCertificate("") .subscribe(pollResponse -> { System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); @@ -272,25 +241,24 @@ certificateAsyncClient.beginDeleteCertificate("") ### List certificates asynchronously List the certificates in the Azure Key Vault by calling `listPropertiesOfCertificates`. -```Java +```java readme-sample-listCertificateAsync // The List Certificates operation returns certificates without their full properties, so for each certificate returned // we call `getCertificate` to get all its attributes excluding the policy. certificateAsyncClient.listPropertiesOfCertificates() - .subscribe(certificateProperties -> - certificateAsyncClient.getCertificateVersion(certificateProperties.getName(), - certificateProperties.getVersion()) - .subscribe(certificateResponse -> - System.out.printf("Received certificate with name \"%s\" and key id %s", certificateResponse.getName(), - certificateResponse.getKeyId()))); + .flatMap(certificateProperties -> certificateAsyncClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion())) + .subscribe(certificateResponse -> + System.out.printf("Received certificate with name \"%s\" and key id %s", certificateResponse.getName(), + certificateResponse.getKeyId())); ``` ## Troubleshooting ### General Azure Key Vault Certificate clients raise exceptions. For example, if you try to retrieve a certificate after it is deleted a `404` error is returned, indicating the resource was not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error. -```java +```java readme-sample-troubleshooting try { - certificateClient.getCertificate("") + certificateClient.getCertificate(""); } catch (ResourceNotFoundException e) { System.out.println(e.getMessage()); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/pom.xml b/sdk/keyvault/azure-security-keyvault-certificates/pom.xml index f8724aae55b2b..5057d4c2da0ae 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-certificates/pom.xml @@ -39,6 +39,9 @@ --add-opens com.azure.security.keyvault.certificates/com.azure.security.keyvault.certificates=ALL-UNNAMED --add-opens com.azure.security.keyvault.certificates/com.azure.security.keyvault.certificates.models=ALL-UNNAMED + false + + diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateAsyncClient.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateAsyncClient.java index 215546e37fa65..27d5b0d61e6a5 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateAsyncClient.java @@ -65,7 +65,15 @@ * *

Samples to construct the async client

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation} + * + *
+ * CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .vaultUrl("https://myvault.vault.azure.net/")
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .buildAsyncClient();
+ * 
+ * * * @see CertificateClientBuilder * @see PagedFlux @@ -132,7 +140,20 @@ Duration getDefaultPollingInterval() { *

Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate * operation status. It is possible to monitor each intermediate poll response during the poll operation.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map} + * + *
+     * CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
+     * Map<String, String> tags = new HashMap<>();
+     * tags.put("foo", "bar");
+     * certificateAsyncClient.beginCreateCertificate("certificateName", policy, true, tags)
+     *     .subscribe(pollResponse -> {
+     *         System.out.println("---------------------------------------------------------------------------------");
+     *         System.out.println(pollResponse.getStatus());
+     *         System.out.println(pollResponse.getValue().getStatus());
+     *         System.out.println(pollResponse.getValue().getStatusDetails());
+     *     });
+     * 
+ * * * @param certificateName The name of the certificate to be created. * @param policy The policy of the certificate to be created. @@ -185,7 +206,18 @@ Mono> fetchResultOperation(String certificateName *

Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate * operation status. It is possible to monitor each intermediate poll response during the poll operation.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy} + * + *
+     * CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
+     * certificateAsyncClient.beginCreateCertificate("certificateName", certPolicy)
+     *     .subscribe(pollResponse -> {
+     *         System.out.println("---------------------------------------------------------------------------------");
+     *         System.out.println(pollResponse.getStatus());
+     *         System.out.println(pollResponse.getValue().getStatus());
+     *         System.out.println(pollResponse.getValue().getStatusDetails());
+     *     });
+     * 
+ * * * @param certificateName The name of the certificate to be created. * @param policy The policy of the certificate to be created. @@ -252,7 +284,17 @@ Mono> createCertificateWithResponse(String certif *

Get a pending certificate operation. The {@link PollerFlux poller} allows users to automatically poll on the certificate * operation status. It is possible to monitor each intermediate poll response during the poll operation.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateOperation#String} + * + *
+     * certificateAsyncClient.getCertificateOperation("certificateName")
+     *     .subscribe(pollResponse -> {
+     *         System.out.println("---------------------------------------------------------------------------------");
+     *         System.out.println(pollResponse.getStatus());
+     *         System.out.println(pollResponse.getValue().getStatus());
+     *         System.out.println(pollResponse.getValue().getStatusDetails());
+     *     });
+     * 
+ * * * @param certificateName The name of the certificate. * @throws ResourceNotFoundException when a certificate operation for a certificate with {@code certificateName} doesn't exist. @@ -274,7 +316,15 @@ public PollerFlux getCertif *

Gets a specific version of the certificate in the key vault. Prints out the * returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate#String} + * + *
+     * certificateAsyncClient.getCertificate("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateResponse ->
+     *         System.out.printf("Certificate is returned with name %s and secretId %s %n",
+     *             certificateResponse.getProperties().getName(), certificateResponse.getSecretId()));
+     * 
+ * * * @param certificateName The name of the certificate to retrieve, cannot be null * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -298,7 +348,16 @@ public Mono getCertificate(String certificateName *

Gets a specific version of the certificate in the key vault. Prints out the * returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateWithResponse#String} + * + *
+     * certificateAsyncClient.getCertificateWithResponse("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateResponse ->
+     *         System.out.printf("Certificate is returned with name %s and secretId %s %n",
+     *             certificateResponse.getValue().getProperties().getName(),
+     *             certificateResponse.getValue().getSecretId()));
+     * 
+ * * * @param certificateName The name of the certificate to retrieve, cannot be null * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -340,7 +399,17 @@ Mono> getCertificateVersionWithResponse(String cer *

Gets a specific version of the certificate in the key vault. Prints out the * returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersionWithResponse#string-string} + * + *
+     * String certificateVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * certificateAsyncClient.getCertificateVersionWithResponse("certificateName", certificateVersion)
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateWithVersion ->
+     *         System.out.printf("Certificate is returned with name %s and secretId %s %n",
+     *             certificateWithVersion.getValue().getProperties().getName(),
+     *             certificateWithVersion.getValue().getSecretId()));
+     * 
+ * * * @param certificateName The name of the certificate to retrieve, cannot be null * @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved. @@ -365,7 +434,15 @@ public Mono> getCertificateVersionWithResponse(Str *

Gets a specific version of the certificate in the key vault. Prints out the * returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersion#String-String} + * + *
+     * certificateAsyncClient.getCertificateVersion("certificateName", certificateVersion)
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateWithVersion ->
+     *         System.out.printf("Certificate is returned with name %s and secretId %s %n",
+     *             certificateWithVersion.getProperties().getName(), certificateWithVersion.getSecretId()));
+     * 
+ * * * @param certificateName The name of the certificate to retrieve, cannot be null * @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved. @@ -391,7 +468,21 @@ public Mono getCertificateVersion(String certificateName, S *

Gets latest version of the certificate, changes its tags and enabled status and then updates it in the Azure Key Vault. Prints out the * returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificateProperties#CertificateProperties} + * + *
+     * certificateAsyncClient.getCertificate("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateResponseValue -> {
+     *         KeyVaultCertificate certificate = certificateResponseValue;
+     *         //Update enabled status of the certificate
+     *         certificate.getProperties().setEnabled(false);
+     *         certificateAsyncClient.updateCertificateProperties(certificate.getProperties())
+     *             .subscribe(certificateResponse ->
+     *                 System.out.printf("Certificate's enabled status %s %n",
+     *                     certificateResponse.getProperties().isEnabled().toString()));
+     *     });
+     * 
+ * * * @param properties The {@link CertificateProperties} object with updated properties. * @throws NullPointerException if {@code certificate} is {@code null}. @@ -416,7 +507,21 @@ public Mono updateCertificateProperties(CertificateProperti *

Gets latest version of the certificate, changes its enabled status and then updates it in the Azure Key Vault. Prints out the * returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePropertiesWithResponse#CertificateProperties} + * + *
+     * certificateAsyncClient.getCertificate("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateResponseValue -> {
+     *         KeyVaultCertificate certificate = certificateResponseValue;
+     *         //Update the enabled status of the certificate.
+     *         certificate.getProperties().setEnabled(false);
+     *         certificateAsyncClient.updateCertificatePropertiesWithResponse(certificate.getProperties())
+     *             .subscribe(certificateResponse ->
+     *                 System.out.printf("Certificate's enabled status %s %n",
+     *                     certificateResponse.getValue().getProperties().isEnabled().toString()));
+     *     });
+     * 
+ * * * @param properties The {@link CertificateProperties} object with updated properties. * @throws NullPointerException if {@code properties} is {@code null}. @@ -457,7 +562,16 @@ Mono> updateCertificatePropertiesWithResponse(Cert *

Code Samples

*

Deletes the certificate in the Azure Key Vault. Prints out the deleted certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginDeleteCertificate#String} + * + *
+     * certificateAsyncClient.beginDeleteCertificate("certificateName")
+     *     .subscribe(pollResponse -> {
+     *         System.out.println("Delete Status: " + pollResponse.getStatus().toString());
+     *         System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName());
+     *         System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString());
+     *     });
+     * 
+ * * * @param certificateName The name of the certificate to be deleted. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -519,7 +633,14 @@ Mono> deleteCertificateWithResponse(String certific *

Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the * deleted certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificate#string} + * + *
+     * certificateAsyncClient.getDeletedCertificate("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(deletedSecretResponse ->
+     *         System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
+     * 
+ * * * @param certificateName The name of the deleted certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -545,7 +666,15 @@ public Mono getDeletedCertificate(String certificateName) { *

Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the * deleted certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificateWithResponse#string} + * + *
+     * certificateAsyncClient.getDeletedCertificateWithResponse("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(deletedSecretResponse ->
+     *         System.out.printf("Deleted Certificate's Recovery Id %s %n",
+     *             deletedSecretResponse.getValue().getRecoveryId()));
+     * 
+ * * * @param certificateName The name of the deleted certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -579,7 +708,14 @@ Mono> getDeletedCertificateWithResponse(String cert *

Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the * status code from the server response when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse#string} + * + *
+     * certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(purgeResponse ->
+     *         System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
+     * 
+ * * * @param certificateName The name of the deleted certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -603,7 +739,14 @@ public Mono purgeDeletedCertificate(String certificateName) { *

Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the * status code from the server response when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse#string} + * + *
+     * certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(purgeResponse ->
+     *         System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
+     * 
+ * * * @param certificateName The name of the deleted certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -638,7 +781,16 @@ Mono> purgeDeletedCertificateWithResponse(String certificateName, *

Recovers the deleted certificate from the key vault enabled for soft-delete. Prints out the * recovered certificate details when a response has been received.

* - * {@codesnippet com.azure.security.certificatevault.certificates.CertificateAsyncClient.beginRecoverDeletedCertificate#String} + * + *
+     * certificateAsyncClient.beginRecoverDeletedCertificate("deletedCertificateName")
+     *     .subscribe(pollResponse -> {
+     *         System.out.println("Recovery Status: " + pollResponse.getStatus().toString());
+     *         System.out.println("Recover Certificate Name: " + pollResponse.getValue().getName());
+     *         System.out.println("Recover Certificate Id: " + pollResponse.getValue().getId());
+     *     });
+     * 
+ * * * @param certificateName The name of the deleted certificate to be recovered. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the certificate vault. @@ -701,7 +853,14 @@ Mono> recoverDeletedCertificateWithRespo *

Backs up the certificate from the key vault. Prints out the * length of the certificate's backup byte array returned in the response.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificate#string} + * + *
+     * certificateAsyncClient.backupCertificate("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateBackupResponse ->
+     *         System.out.printf("Certificate's Backup Byte array's length %s %n", certificateBackupResponse.length));
+     * 
+ * * * @param certificateName The name of the certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -725,7 +884,15 @@ public Mono backupCertificate(String certificateName) { *

Backs up the certificate from the key vault. Prints out the * length of the certificate's backup byte array returned in the response.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificateWithResponse#string} + * + *
+     * certificateAsyncClient.backupCertificateWithResponse("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateBackupResponse ->
+     *         System.out.printf("Certificate's Backup Byte array's length %s %n",
+     *             certificateBackupResponse.getValue().length));
+     * 
+ * * * @param certificateName The name of the certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -761,7 +928,15 @@ Mono> backupCertificateWithResponse(String certificateName, Con *

Restores the certificate in the key vault from its backup. Prints out the restored certificate * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificate#byte} + * + *
+     * byte[] certificateBackupByteArray = {};
+     * certificateAsyncClient.restoreCertificateBackup(certificateBackupByteArray)
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n",
+     *         certificateResponse.getProperties().getName(), certificateResponse.getKeyId()));
+     * 
+ * * * @param backup The backup blob associated with the certificate. * @throws ResourceModifiedException when {@code backup} blob is malformed. @@ -784,7 +959,15 @@ public Mono restoreCertificateBackup(byte[] backu *

Restores the certificate in the key vault from its backup. Prints out the restored certificate * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificateWithResponse#byte} + * + *
+     * byte[] certificateBackup = {};
+     * certificateAsyncClient.restoreCertificateBackup(certificateBackup)
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n",
+     *         certificateResponse.getProperties().getName(), certificateResponse.getKeyId()));
+     * 
+ * * * @param backup The backup blob associated with the certificate. * @throws ResourceModifiedException when {@code backup} blob is malformed. @@ -819,7 +1002,16 @@ Mono> restoreCertificateBackupWithRespon *

It is possible to get certificates with all the properties excluding the policy from this information. Convert the {@link Flux} containing {@link CertificateProperties} to * {@link Flux} containing {@link KeyVaultCertificate certificate} using {@link CertificateAsyncClient#getCertificateVersion(String, String)} within {@link Flux#flatMap(Function)}.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificates} + * + *
+     * certificateAsyncClient.listPropertiesOfCertificates()
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificate -> certificateAsyncClient.getCertificateVersion(certificate.getName(),
+     *         certificate.getVersion())
+     *         .subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
+     *             certificateResponse.getName(), certificateResponse.getKeyId())));
+     * 
+ * * * @param includePending indicate if pending certificates should be included in the results. * @return A {@link PagedFlux} containing {@link CertificateProperties certificate} for all the certificates in the vault. @@ -845,7 +1037,16 @@ public PagedFlux listPropertiesOfCertificates(boolean inc *

It is possible to get certificates with all the properties excluding the policy from this information. Convert the {@link Flux} containing {@link CertificateProperties} to * {@link Flux} containing {@link KeyVaultCertificate certificate} using {@link CertificateAsyncClient#getCertificateVersion(String, String)} within {@link Flux#flatMap(Function)}.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificates} + * + *
+     * certificateAsyncClient.listPropertiesOfCertificates()
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificate -> certificateAsyncClient.getCertificateVersion(certificate.getName(),
+     *         certificate.getVersion())
+     *         .subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
+     *             certificateResponse.getName(), certificateResponse.getKeyId())));
+     * 
+ * * * @return A {@link PagedFlux} containing {@link CertificateProperties certificate} for all the certificates in the vault. */ @@ -912,7 +1113,14 @@ private Mono> listCertificatesFirstPage(boo *

Lists the deleted certificates in the key vault. Prints out the * recovery id of each deleted certificate when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.listDeletedCertificates} + * + *
+     * certificateAsyncClient.listDeletedCertificates()
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(deletedCertificateResponse ->  System.out.printf("Deleted Certificate's Recovery Id %s %n",
+     *         deletedCertificateResponse.getRecoveryId()));
+     * 
+ * * * @return A {@link PagedFlux} containing all of the {@link DeletedCertificate deleted certificates} in the vault. */ @@ -939,7 +1147,14 @@ public PagedFlux listDeletedCertificates() { *

Lists the deleted certificates in the key vault. Prints out the * recovery id of each deleted certificate when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.listDeletedCertificates} + * + *
+     * certificateAsyncClient.listDeletedCertificates()
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(deletedCertificateResponse ->  System.out.printf("Deleted Certificate's Recovery Id %s %n",
+     *         deletedCertificateResponse.getRecoveryId()));
+     * 
+ * * * @param includePending indicate if pending deleted certificates should be included in the results. * @return A {@link PagedFlux} containing all of the {@link DeletedCertificate deleted certificates} in the vault. @@ -1008,7 +1223,16 @@ private Mono> listDeletedCertificatesFirstPage * containing {@link CertificateProperties} to {@link PagedFlux} containing {@link KeyVaultCertificate certificate} using * {@link CertificateAsyncClient#getCertificateVersion(String, String)} within {@link Flux#flatMap(Function)}.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificateVersions} + * + *
+     * certificateAsyncClient.listPropertiesOfCertificateVersions("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificate -> certificateAsyncClient.getCertificateVersion(certificate.getName(),
+     *         certificate.getVersion())
+     *         .subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
+     *             certificateResponse.getProperties().getName(), certificateResponse.getKeyId())));
+     * 
+ * * * @param certificateName The name of the certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -1067,7 +1291,16 @@ private Mono> listCertificateVersionsNextPa *

Code Samples

*

Merges a certificate with a kay pair available in the service.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificate#config} + * + *
+     * List<byte[]> x509CertificatesToMerge = new ArrayList<>();
+     * MergeCertificateOptions config =
+     *     new MergeCertificateOptions("certificateName", x509CertificatesToMerge).setEnabled(false);
+     * certificateAsyncClient.mergeCertificate(config)
+     *     .subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
+     *         certificate.getProperties().getName(), certificate.getKeyId()));
+     * 
+ * * * @param mergeCertificateOptions the merge certificate options holding the x509 certificates. * @@ -1091,7 +1324,16 @@ public Mono mergeCertificate(MergeCertificateOptions mergeC *

Code Samples

*

Merges a certificate with a kay pair available in the service.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificateWithResponse#config} + * + *
+     * List<byte[]> x509CertsToMerge = new ArrayList<>();
+     * MergeCertificateOptions mergeConfig =
+     *     new MergeCertificateOptions("certificateName", x509CertsToMerge).setEnabled(false);
+     * certificateAsyncClient.mergeCertificateWithResponse(mergeConfig)
+     *     .subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
+     *         certificateResponse.getValue().getProperties().getName(), certificateResponse.getValue().getKeyId()));
+     * 
+ * * * @param mergeCertificateOptions the merge certificate options holding the x509 certificates. * @@ -1128,7 +1370,15 @@ Mono> mergeCertificateWithResponse(Merge *

Gets the policy of a certirifcate in the key vault. Prints out the * returned certificate policy details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicy#string} + * + *
+     * certificateAsyncClient.getCertificatePolicy("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(policy ->
+     *         System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
+     *             policy.getIssuerName(), policy.getSubject()));
+     * 
+ * * * @param certificateName The name of the certificate whose policy is to be retrieved, cannot be null * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -1151,7 +1401,15 @@ public Mono getCertificatePolicy(String certificateName) { *

Gets the policy of a certirifcate in the key vault. Prints out the * returned certificate policy details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicyWithResponse#string} + * + *
+     * certificateAsyncClient.getCertificatePolicyWithResponse("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(policyResponse ->
+     *         System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
+     *             policyResponse.getValue().getIssuerName(), policyResponse.getValue().getSubject()));
+     * 
+ * * * @param certificateName The name of the certificate whose policy is to be retrieved, cannot be null * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -1184,7 +1442,21 @@ Mono> getCertificatePolicyWithResponse(String certif *

Gets the certificate policy, changes its properties and then updates it in the Azure Key Vault. Prints out the * returned policy details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicy#string} + * + *
+     * certificateAsyncClient.getCertificatePolicy("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificatePolicyResponseValue -> {
+     *         CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
+     *         // Update transparency
+     *         certificatePolicy.setCertificateTransparent(true);
+     *         certificateAsyncClient.updateCertificatePolicy("certificateName", certificatePolicy)
+     *             .subscribe(updatedPolicy ->
+     *                 System.out.printf("Certificate policy's updated transparency status %s %n",
+     *                     updatedPolicy.isCertificateTransparent()));
+     *     });
+     * 
+ * * * @param certificateName The name of the certificate whose policy is to be updated. * @param policy The certificate policy to be updated. @@ -1210,7 +1482,22 @@ public Mono updateCertificatePolicy(String certificateName, C *

Gets the certificate policy, changes its properties and then updates it in the Azure Key Vault. Prints out the * returned policy details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicyWithResponse#string} + * + *
+     * certificateAsyncClient.getCertificatePolicy("certificateName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(certificatePolicyResponseValue -> {
+     *         CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
+     *         // Update transparency
+     *         certificatePolicy.setCertificateTransparent(true);
+     *         certificateAsyncClient.updateCertificatePolicyWithResponse("certificateName",
+     *             certificatePolicy)
+     *             .subscribe(updatedPolicyResponse ->
+     *                 System.out.printf("Certificate policy's updated transparency status %s %n",
+     *                     updatedPolicyResponse.getValue().isCertificateTransparent()));
+     *     });
+     * 
+ * * * @param certificateName The name of the certificate whose policy is to be updated. * @param policy The certificate policy is to be updated. @@ -1246,7 +1533,19 @@ Mono> updateCertificatePolicyWithResponse(String cer *

Creates a new certificate issuer in the key vault. Prints out the created certificate * issuer details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuer#CertificateIssuer} + * + *
+     * CertificateIssuer issuer = new CertificateIssuer("issuerName", "providerName")
+     *     .setAccountId("keyvaultuser")
+     *     .setPassword("temp2");
+     * certificateAsyncClient.createIssuer(issuer)
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(issuerResponse -> {
+     *         System.out.printf("Issuer created with %s and %s", issuerResponse.getName(),
+     *             issuerResponse.getProvider());
+     *     });
+     * 
+ * * * @param issuer The configuration of the certificate issuer to be created. * @throws ResourceModifiedException when invalid certificate issuer {@code issuer} configuration is provided. @@ -1271,7 +1570,19 @@ public Mono createIssuer(CertificateIssuer issuer) { *

Creates a new certificate issuer in the key vault. Prints out the created certificate * issuer details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuerWithResponse#CertificateIssuer} + * + *
+     * CertificateIssuer newIssuer = new CertificateIssuer("issuerName", "providerName")
+     *     .setAccountId("keyvaultuser")
+     *     .setPassword("temp2");
+     * certificateAsyncClient.createIssuerWithResponse(newIssuer)
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(issuerResponse -> {
+     *         System.out.printf("Issuer created with %s and %s", issuerResponse.getValue().getName(),
+     *             issuerResponse.getValue().getProvider());
+     *     });
+     * 
+ * * * @param issuer The configuration of the certificate issuer to be created. Use * {@link CertificateIssuer#CertificateIssuer(String, String)} to initialize the issuer object @@ -1309,7 +1620,16 @@ Mono> createIssuerWithResponse(CertificateIssuer iss *

Gets the specificed certifcate issuer in the key vault. Prints out the * returned certificate issuer details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuerWithResponse#string} + * + *
+     * certificateAsyncClient.getIssuerWithResponse("issuerName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(issuerResponse -> {
+     *         System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().getName(),
+     *             issuerResponse.getValue().getProvider());
+     *     });
+     * 
+ * * * @param issuerName The name of the certificate issuer to retrieve, cannot be null * @throws ResourceNotFoundException when a certificate issuer with {@code issuerName} doesn't exist in the key vault. @@ -1332,7 +1652,16 @@ public Mono> getIssuerWithResponse(String issuerName *

Gets the specified certificate issuer in the key vault. Prints out the * returned certificate issuer details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuer#string} + * + *
+     * certificateAsyncClient.getIssuer("issuerName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(issuer -> {
+     *         System.out.printf("Issuer returned with %s and %s", issuer.getName(),
+     *             issuer.getProvider());
+     *     });
+     * 
+ * * * @param issuerName The name of the certificate to retrieve, cannot be null * @throws ResourceNotFoundException when a certificate issuer with {@code issuerName} doesn't exist in the key vault. @@ -1366,7 +1695,14 @@ Mono> getIssuerWithResponse(String issuerName, Conte *

Deletes the certificate issuer in the Azure Key Vault. Prints out the * deleted certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuerWithResponse#string} + * + *
+     * certificateAsyncClient.deleteIssuerWithResponse("issuerName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(deletedIssuerResponse ->
+     *         System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().getName()));
+     * 
+ * * * @param issuerName The name of the certificate issuer to be deleted. * @throws ResourceNotFoundException when a certificate issuer with {@code issuerName} doesn't exist in the key vault. @@ -1390,7 +1726,14 @@ public Mono> deleteIssuerWithResponse(String issuerN *

Deletes the certificate issuer in the Azure Key Vault. Prints out the * deleted certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuer#string} + * + *
+     * certificateAsyncClient.deleteIssuer("issuerName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(deletedIssuerResponse ->
+     *         System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getName()));
+     * 
+ * * * @param issuerName The name of the certificate issuer to be deleted. * @throws ResourceNotFoundException when a certificate issuer with {@code issuerName} doesn't exist in the key vault. @@ -1425,7 +1768,15 @@ Mono> deleteIssuerWithResponse(String issuerName, Co *

It is possible to get the certificate issuer with all of its properties from this information. Convert the {@link PagedFlux} * containing {@link IssuerProperties issuerProperties} to {@link PagedFlux} containing {@link CertificateIssuer issuer} using * {@link CertificateAsyncClient#getIssuer(String)} - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.listPropertiesOfIssuers} + * + *

+     * certificateAsyncClient.listPropertiesOfIssuers()
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(issuerProperties -> certificateAsyncClient.getIssuer(issuerProperties.getName())
+     *         .subscribe(issuerResponse -> System.out.printf("Received issuer with name %s and provider %s",
+     *             issuerResponse.getName(), issuerResponse.getProvider())));
+     * 
+ * * * @return A {@link PagedFlux} containing all of the {@link IssuerProperties certificate issuers} in the vault. */ @@ -1486,7 +1837,21 @@ private Mono> listPropertiesOfIssuersNextPage(St *

Gets the certificate issuer, changes its attributes/properties then updates it in the Azure Key Vault. Prints out the * returned certificate issuer details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuer#CertificateIssuer} + * + *
+     * certificateAsyncClient.getIssuer("issuerName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(issuerResponseValue -> {
+     *         CertificateIssuer issuer = issuerResponseValue;
+     *         //Update the enabled status of the issuer.
+     *         issuer.setEnabled(false);
+     *         certificateAsyncClient.updateIssuer(issuer)
+     *             .subscribe(issuerResponse ->
+     *                 System.out.printf("Issuer's enabled status %s %n",
+     *                     issuerResponse.isEnabled().toString()));
+     *     });
+     * 
+ * * * @param issuer The {@link CertificateIssuer issuer} with updated properties. Use * {@link CertificateIssuer#CertificateIssuer(String)} to initialize the issuer object @@ -1513,7 +1878,21 @@ public Mono updateIssuer(CertificateIssuer issuer) { *

Gets the certificate issuer, changes its attributes/properties then updates it in the Azure Key Vault. Prints out the * returned certificate issuer details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuer#CertificateIssuer} + * + *
+     * certificateAsyncClient.getIssuer("issuerName")
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(issuerResponseValue -> {
+     *         CertificateIssuer issuer = issuerResponseValue;
+     *         //Update the enabled status of the issuer.
+     *         issuer.setEnabled(false);
+     *         certificateAsyncClient.updateIssuer(issuer)
+     *             .subscribe(issuerResponse ->
+     *                 System.out.printf("Issuer's enabled status %s %n",
+     *                     issuerResponse.isEnabled().toString()));
+     *     });
+     * 
+ * * * @param issuer The {@link CertificateIssuer issuer} with updated properties. * @throws NullPointerException if {@code issuer} is {@code null}. @@ -1552,7 +1931,14 @@ Mono> updateIssuerWithResponse(CertificateIssuer iss *

Sets the certificate contacts in the Azure Key Vault. Prints out the * returned contacts details.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.setContacts#contacts} + * + *
+     * CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com");
+     * certificateAsyncClient.setContacts(Collections.singletonList(contactToAdd)).subscribe(contact ->
+     *     System.out.printf("Contact name %s and email %s", contact.getName(), contact.getEmail())
+     * );
+     * 
+ * * * @param contacts The list of contacts to set on the vault. * @throws HttpResponseException when a contact information provided is invalid/incomplete. @@ -1589,7 +1975,13 @@ private Mono> setCertificateContactsWithRespon *

Lists the certificate contacts in the Azure Key Vault. Prints out the * returned contacts details.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.listContacts} + * + *
+     * certificateAsyncClient.listContacts().subscribe(contact ->
+     *     System.out.printf("Contact name %s and email %s", contact.getName(), contact.getEmail())
+     * );
+     * 
+ * * * @return A {@link PagedFlux} containing all of the {@link CertificateContact certificate contacts} in the vault. */ @@ -1627,7 +2019,13 @@ private Mono> listCertificateContactsFirstPage *

Deletes the certificate contacts in the Azure Key Vault. Prints out the * deleted contacts details.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteContacts} + * + *
+     * certificateAsyncClient.deleteContacts().subscribe(contact ->
+     *     System.out.printf("Deleted Contact name %s and email %s", contact.getName(), contact.getEmail())
+     * );
+     * 
+ * * * @return A {@link PagedFlux} containing all of the {@link CertificateContact deleted certificate contacts} in the vault. */ @@ -1662,7 +2060,13 @@ private Mono> deleteCertificateContactsWithRes *

Triggers certificate creation and then deletes the certificate creation operation in the Azure Key Vault. Prints out the * deleted certificate operation details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperation#string} + * + *
+     * certificateAsyncClient.deleteCertificateOperation("certificateName")
+     *     .subscribe(certificateOperation -> System.out.printf("Deleted Certificate operation last status %s",
+     *         certificateOperation.getStatus()));
+     * 
+ * * * @param certificateName The name of the certificate which is in the process of being created. * @throws ResourceNotFoundException when a certificate operation for a certificate with {@code certificateName} doesn't exist in the key vault. @@ -1686,7 +2090,13 @@ public Mono deleteCertificateOperation(String certificateN *

Triggers certificate creation and then deletes the certificate creation operation in the Azure Key Vault. Prints out the * deleted certificate operation details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperationWithResponse#string} + * + *
+     * certificateAsyncClient.deleteCertificateOperationWithResponse("certificateName")
+     *     .subscribe(certificateOperationResponse -> System.out.printf("Deleted Certificate operation's last"
+     *         + " status %s", certificateOperationResponse.getValue().getStatus()));
+     * 
+ * * * @param certificateName The name of the certificate which is in the process of being created. * @throws ResourceNotFoundException when a certificate operation for a certificate with {@code certificateName} doesn't exist in the key vault. @@ -1728,7 +2138,13 @@ Mono> cancelCertificateOperationWithResponse(Stri *

Triggers certificate creation and then cancels the certificate creation operation in the Azure Key Vault. Prints out the * updated certificate operation details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperation#string} + * + *
+     * certificateAsyncClient.cancelCertificateOperation("certificateName")
+     *     .subscribe(certificateOperation -> System.out.printf("Certificate operation status %s",
+     *         certificateOperation.getStatus()));
+     * 
+ * * * @param certificateName The name of the certificate which is in the process of being created. * @throws ResourceNotFoundException when a certificate operation for a certificate with {@code name} doesn't exist in the key vault. @@ -1751,7 +2167,13 @@ public Mono cancelCertificateOperation(String certificateN *

Triggers certificate creation and then cancels the certificate creation operation in the Azure Key Vault. Prints out the * updated certificate operation details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperationWithResponse#string} + * + *
+     * certificateAsyncClient.cancelCertificateOperationWithResponse("certificateName")
+     *     .subscribe(certificateOperationResponse -> System.out.printf("Certificate operation status %s",
+     *         certificateOperationResponse.getValue().getStatus()));
+     * 
+ * * * @param certificateName The name of the certificate which is in the process of being created. * @throws ResourceNotFoundException when a certificate operation for a certificate with {@code name} doesn't exist in the key vault. @@ -1776,7 +2198,16 @@ public Mono> cancelCertificateOperationWithRespon *

Code Samples

*

Imports a certificate into the key vault.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificate#options} + * + *
+     * byte[] certificateToImport = new byte[100];
+     * ImportCertificateOptions config =
+     *     new ImportCertificateOptions("certificateName", certificateToImport).setEnabled(false);
+     * certificateAsyncClient.importCertificate(config)
+     *     .subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
+     *         certificate.getProperties().getName(), certificate.getKeyId()));
+     * 
+ * * * @param importCertificateOptions The details of the certificate to import to the key vault * @throws HttpResponseException when the {@code importCertificateOptions} are invalid. @@ -1798,7 +2229,16 @@ public Mono importCertificate(ImportCertificateOp *

Code Samples

*

Imports a certificate into the key vault.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificateWithResponse#options} + * + *
+     * byte[] certToImport = new byte[100];
+     * ImportCertificateOptions importCertificateOptions  =
+     *     new ImportCertificateOptions("certificateName", certToImport).setEnabled(false);
+     * certificateAsyncClient.importCertificateWithResponse(importCertificateOptions)
+     *     .subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
+     *         certificateResponse.getValue().getProperties().getName(), certificateResponse.getValue().getKeyId()));
+     * 
+ * * * @param importCertificateOptions The details of the certificate to import to the key vault * @throws HttpResponseException when the {@code importCertificateOptions} are invalid. diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClient.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClient.java index 713f1896de322..ef516cd2985ea 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClient.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClient.java @@ -43,7 +43,15 @@ * *

Samples to construct the sync client

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.instantiation} + * + *
+ * CertificateClient certificateClient = new CertificateClientBuilder()
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .vaultUrl("https://myvault.vault.azure.net/")
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .buildClient();
+ * 
+ * * * @see CertificateClientBuilder * @see PagedIterable @@ -79,7 +87,17 @@ public String getVaultUrl() { *

Create certificate is a long running operation. The createCertificate indefinitely waits for the operation to complete and * returns its last status. The details of the last certificate operation status are printed when a response is received

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map} + * + *
+     * CertificatePolicy certificatePolicyPkcsSelf = new CertificatePolicy("Self",
+     *     "CN=SelfSignedJavaPkcs12");
+     * SyncPoller<CertificateOperation, KeyVaultCertificateWithPolicy> certificateSyncPoller = certificateClient
+     *     .beginCreateCertificate("certificateName", certificatePolicyPkcsSelf, true, new HashMap<>());
+     * certificateSyncPoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED);
+     * KeyVaultCertificate createdCertificate = certificateSyncPoller.getFinalResult();
+     * System.out.printf("Certificate created with name %s%n", createdCertificate.getName());
+     * 
+ * * * @param certificateName The name of the certificate to be created. * @param policy The policy of the certificate to be created. @@ -103,7 +121,17 @@ public SyncPoller beginCrea *

Create certificate is a long running operation. The createCertificate indefinitely waits for the operation to complete and * returns its last status. The details of the last certificate operation status are printed when a response is received

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy} + * + *
+     * CertificatePolicy certPolicy = new CertificatePolicy("Self",
+     *     "CN=SelfSignedJavaPkcs12");
+     * SyncPoller<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateClient
+     *     .beginCreateCertificate("certificateName", certPolicy);
+     * certPoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED);
+     * KeyVaultCertificate cert = certPoller.getFinalResult();
+     * System.out.printf("Certificate created with name %s%n", cert.getName());
+     * 
+ * * * @param certificateName The name of the certificate to be created. * @param policy The policy of the certificate to be created. @@ -122,7 +150,15 @@ public SyncPoller beginCrea *

Geta a pending certificate operation. The {@link SyncPoller poller} allows users to automatically poll on the certificate * operation status.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getCertificateOperation#String} + * + *
+     * SyncPoller<CertificateOperation, KeyVaultCertificateWithPolicy> getCertPoller = certificateClient
+     *     .getCertificateOperation("certificateName");
+     * getCertPoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED);
+     * KeyVaultCertificate cert = getCertPoller.getFinalResult();
+     * System.out.printf("Certificate created with name %s%n", cert.getName());
+     * 
+ * * * @param certificateName The name of the certificate. * @throws ResourceNotFoundException when a certificate operation for a certificate with {@code certificateName} doesn't exist. @@ -138,7 +174,14 @@ public SyncPoller getCertif *

Code Samples

*

Gets a specific version of the certificate in the key vault. Prints out the returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getCertificate#String} + * + *
+     * KeyVaultCertificateWithPolicy certificate = certificateClient.getCertificate("certificateName");
+     * System.out.printf("Received certificate with name %s and version %s and secret id %s%n",
+     *     certificate.getProperties().getName(),
+     *     certificate.getProperties().getVersion(), certificate.getSecretId());
+     * 
+ * * * @param certificateName The name of the certificate to retrieve, cannot be null * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -156,7 +199,15 @@ public KeyVaultCertificateWithPolicy getCertificate(String certificateName) { *

Code Samples

*

Gets a specific version of the certificate in the key vault. Prints out the returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getCertificateWithResponse#String-Context} + * + *
+     * Response<KeyVaultCertificateWithPolicy> certificateWithResponse = certificateClient
+     *     .getCertificateWithResponse("certificateName", new Context(key1, value1));
+     * System.out.printf("Received certificate with name %s and version %s and secret id %s%n",
+     *     certificateWithResponse.getValue().getProperties().getName(),
+     *     certificateWithResponse.getValue().getProperties().getVersion(), certificate.getSecretId());
+     * 
+ * * * @param certificateName The name of the certificate to retrieve, cannot be null * @param context Additional context that is passed through the Http pipeline during the service call. @@ -175,7 +226,17 @@ public Response getCertificateWithResponse(String *

Code Samples

*

Gets a specific version of the certificate in the key vault. Prints out the returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersionWithResponse#String-String-Context} + * + *
+     * Response<KeyVaultCertificate> returnedCertificateWithResponse = certificateClient
+     *     .getCertificateVersionWithResponse("certificateName", "certificateVersion",
+     *         new Context(key1, value1));
+     * System.out.printf("Received certificate with name %s and version %s and secret id %s%n",
+     *     returnedCertificateWithResponse.getValue().getProperties().getName(),
+     *     returnedCertificateWithResponse.getValue().getProperties().getVersion(),
+     *     returnedCertificateWithResponse.getValue().getSecretId());
+     * 
+ * * * @param certificateName The name of the certificate to retrieve, cannot be null * @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved. @@ -195,7 +256,15 @@ public Response getCertificateVersionWithResponse(String ce *

Code Samples

*

Gets a specific version of the certificate in the key vault. Prints out the returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersion#String-String} + * + *
+     * KeyVaultCertificate returnedCertificate = certificateClient.getCertificateVersion("certificateName",
+     *     "certificateVersion");
+     * System.out.printf("Received certificate with name %s and version %s and secret id %s%n",
+     *     returnedCertificate.getProperties().getName(), returnedCertificate.getProperties().getVersion(),
+     *     returnedCertificate.getSecretId());
+     * 
+ * * * @param certificateName The name of the certificate to retrieve, cannot be null * @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved. @@ -216,7 +285,16 @@ public KeyVaultCertificate getCertificateVersion(String certificateName, String *

Gets latest version of the certificate, changes its tags and enabled status and then updates it in the Azure Key Vault. Prints out the * returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.updateCertificateProperties#CertificateProperties} + * + *
+     * KeyVaultCertificate certificate = certificateClient.getCertificate("certificateName");
+     * // Update certificate enabled status
+     * certificate.getProperties().setEnabled(false);
+     * KeyVaultCertificate updatedCertificate = certificateClient.updateCertificateProperties(certificate.getProperties());
+     * System.out.printf("Updated Certificate with name %s and enabled status %s%n",
+     *     updatedCertificate.getProperties().getName(), updatedCertificate.getProperties().isEnabled());
+     * 
+ * * * @param properties The {@link CertificateProperties} object with updated properties. * @throws NullPointerException if {@code certificate} is {@code null}. @@ -237,7 +315,18 @@ public KeyVaultCertificate updateCertificateProperties(CertificateProperties pro *

Gets latest version of the certificate, changes its tags and enabled status and then updates it in the Azure Key Vault. Prints out the * returned certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePropertiesWithResponse#CertificateProperties-Context} + * + *
+     * KeyVaultCertificate certificateToUpdate = certificateClient.getCertificate("certificateName");
+     * // Update certificate enabled status
+     * certificateToUpdate.getProperties().setEnabled(false);
+     * Response<KeyVaultCertificate> updatedCertificateResponse = certificateClient.
+     *     updateCertificatePropertiesWithResponse(certificateToUpdate.getProperties(), new Context(key1, value1));
+     * System.out.printf("Updated Certificate with name %s and enabled status %s%n",
+     *     updatedCertificateResponse.getValue().getProperties().getName(),
+     *     updatedCertificateResponse.getValue().getProperties().isEnabled());
+     * 
+ * * * @param properties The {@link CertificateProperties} object with updated properties. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -261,7 +350,17 @@ public Response updateCertificatePropertiesWithResponse(Cer *

Deletes the certificate in the Azure Key Vault. Prints out the * deleted certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.beginDeleteCertificate#String} + * + *
+     * SyncPoller<DeletedCertificate, Void> deleteCertPoller =
+     *     certificateClient.beginDeleteCertificate("certificateName");
+     * // Deleted Certificate is accessible as soon as polling beings.
+     * PollResponse<DeletedCertificate> deleteCertPollResponse = deleteCertPoller.poll();
+     * System.out.printf("Deleted certificate with name %s and recovery id %s%n",
+     *     deleteCertPollResponse.getValue().getName(), deleteCertPollResponse.getValue().getRecoveryId());
+     * deleteCertPoller.waitForCompletion();
+     * 
+ * * * @param certificateName The name of the certificate to be deleted. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -282,7 +381,13 @@ public SyncPoller beginDeleteCertificate(String certif *

Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the * deleted certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificate#string} + * + *
+     * DeletedCertificate deletedCertificate = certificateClient.getDeletedCertificate("certificateName");
+     * System.out.printf("Deleted certificate with name %s and recovery id %s%n", deletedCertificate.getName(),
+     *     deletedCertificate.getRecoveryId());
+     * 
+ * * * @param certificateName The name of the deleted certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -303,7 +408,15 @@ public DeletedCertificate getDeletedCertificate(String certificateName) { *

Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the * deleted certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificateWithResponse#String-Context} + * + *
+     * Response<DeletedCertificate> deletedCertificateWithResponse = certificateClient
+     *     .getDeletedCertificateWithResponse("certificateName", new Context(key1, value1));
+     * System.out.printf("Deleted certificate with name %s and recovery id %s%n",
+     *     deletedCertificateWithResponse.getValue().getName(),
+     *     deletedCertificateWithResponse.getValue().getRecoveryId());
+     * 
+ * * * @param certificateName The name of the deleted certificate. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -324,7 +437,11 @@ public Response getDeletedCertificateWithResponse(String cer *

Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the * status code from the server response when a response has been received.

- * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificate#string} + * + *
+     * certificateClient.purgeDeletedCertificate("certificateName");
+     * 
+ * * * @param certificateName The name of the deleted certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -343,7 +460,13 @@ public void purgeDeletedCertificate(String certificateName) { *

Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the * status code from the server response when a response has been received.

- * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificateWithResponse#string-Context} + * + *
+     * Response<Void> purgeResponse = certificateClient.purgeDeletedCertificateWithResponse("certificateName",
+     *     new Context(key1, value1));
+     * System.out.printf("Purged Deleted certificate with status %d%n", purgeResponse.getStatusCode());
+     * 
+ * * * @param certificateName The name of the deleted certificate. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -365,7 +488,18 @@ public Response purgeDeletedCertificateWithResponse(String certificateName *

Recovers the deleted certificate from the key vault enabled for soft-delete. Prints out the * recovered certificate details when a response has been received.

- * {@codesnippet com.azure.security.certificatevault.certificates.CertificateClient.beginRecoverDeletedCertificate#String} + * + *
+     * SyncPoller<KeyVaultCertificateWithPolicy, Void> recoverDeletedCertPoller = certificateClient
+     *     .beginRecoverDeletedCertificate("deletedCertificateName");
+     * // Recovered certificate is accessible as soon as polling beings
+     * PollResponse<KeyVaultCertificateWithPolicy> recoverDeletedCertPollResponse = recoverDeletedCertPoller.poll();
+     * System.out.printf(" Recovered Deleted certificate with name %s and id %s%n",
+     *     recoverDeletedCertPollResponse.getValue().getProperties().getName(),
+     *     recoverDeletedCertPollResponse.getValue().getProperties().getId());
+     * recoverDeletedCertPoller.waitForCompletion();
+     * 
+ * * * @param certificateName The name of the deleted certificate to be recovered. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the certificate vault. @@ -385,7 +519,12 @@ public SyncPoller beginRecoverDeletedCertif *

Backs up the certificate from the key vault. Prints out the * length of the certificate's backup byte array returned in the response.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.backupCertificate#string} + * + *
+     * byte[] certificateBackup = certificateClient.backupCertificate("certificateName");
+     * System.out.printf("Backed up certificate with back up blob length %d%n", certificateBackup.length);
+     * 
+ * * * @param certificateName The name of the certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -405,7 +544,14 @@ public byte[] backupCertificate(String certificateName) { *

Backs up the certificate from the key vault. Prints out the * length of the certificate's backup byte array returned in the response.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.backupCertificateWithResponse#String-Context} + * + *
+     * Response<byte[]> certificateBackupWithResponse = certificateClient
+     *     .backupCertificateWithResponse("certificateName", new Context(key1, value1));
+     * System.out.printf("Backed up certificate with back up blob length %d%n",
+     *     certificateBackupWithResponse.getValue().length);
+     * 
+ * * * @param certificateName The certificateName of the certificate. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -426,7 +572,14 @@ public Response backupCertificateWithResponse(String certificateName, Co *

Restores the certificate in the key vault from its backup. Prints out the restored certificate * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.restoreCertificate#byte} + * + *
+     * byte[] certificateBackupBlob = {};
+     * KeyVaultCertificate certificate = certificateClient.restoreCertificateBackup(certificateBackupBlob);
+     * System.out.printf(" Restored certificate with name %s and id %s%n",
+     *     certificate.getProperties().getName(), certificate.getProperties().getId());
+     * 
+ * * * @param backup The backup blob associated with the certificate. * @throws ResourceModifiedException when {@code backup} blob is malformed. @@ -445,7 +598,16 @@ public KeyVaultCertificateWithPolicy restoreCertificateBackup(byte[] backup) { *

Restores the certificate in the key vault from its backup. Prints out the restored certificate * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.restoreCertificateWithResponse#byte-Context} + * + *
+     * byte[] certificateBackupBlobArray = {};
+     * Response<KeyVaultCertificateWithPolicy> certificateResponse = certificateClient
+     *     .restoreCertificateBackupWithResponse(certificateBackupBlobArray, new Context(key1, value1));
+     * System.out.printf(" Restored certificate with name %s and id %s%n",
+     *     certificateResponse.getValue().getProperties().getName(),
+     *     certificateResponse.getValue().getProperties().getId());
+     * 
+ * * * @param backup The backup blob associated with the certificate. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -467,7 +629,17 @@ public Response restoreCertificateBackupWithRespo * call {@link CertificateClient#getCertificateVersion(String, String)} . This will return the {@link KeyVaultCertificate certificate} * with all its properties excluding the policy.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listCertificates} + * + *
+     * for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) {
+     *     KeyVaultCertificate certificateWithAllProperties = certificateClient
+     *         .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion());
+     *     System.out.printf("Received certificate with name %s and secret id %s%n",
+     *         certificateWithAllProperties.getProperties().getName(),
+     *         certificateWithAllProperties.getSecretId());
+     * }
+     * 
+ * * * @return A {@link PagedIterable} containing {@link CertificateProperties certificate} for all the certificates in the vault. */ @@ -486,7 +658,18 @@ public PagedIterable listPropertiesOfCertificates() { * call {@link CertificateClient#getCertificateVersion(String, String)} . This will return the {@link KeyVaultCertificate certificate} * with all its properties excluding the policy.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listCertificates#context} + * + *
+     * for (CertificateProperties certificateProperties : certificateClient
+     *     .listPropertiesOfCertificates(true, new Context(key1, value1))) {
+     *     KeyVaultCertificate certificateWithAllProperties = certificateClient
+     *         .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion());
+     *     System.out.printf("Received certificate with name %s and secret id %s%n",
+     *         certificateWithAllProperties.getProperties().getName(),
+     *         certificateWithAllProperties.getSecretId());
+     * }
+     * 
+ * * * @param includePending indicate if pending certificates should be included in the results. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -506,7 +689,13 @@ public PagedIterable listPropertiesOfCertificates(boolean *

Lists the deleted certificates in the key vault. Prints out the * recovery id of each deleted certificate when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates} + * + *
+     * for (DeletedCertificate deletedCertificate : certificateClient.listDeletedCertificates()) {
+     *     System.out.printf("Deleted certificate's recovery Id %s%n", deletedCertificate.getRecoveryId());
+     * }
+     * 
+ * * * @return A {@link PagedIterable} containing all of the {@link DeletedCertificate deleted certificates} in the vault. */ @@ -524,7 +713,14 @@ public PagedIterable listDeletedCertificates() { *

Lists the deleted certificates in the key vault. Prints out the * recovery id of each deleted certificate when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates#context} + * + *
+     * for (DeletedCertificate deletedCertificate : certificateClient
+     *     .listDeletedCertificates(true, new Context(key1, value1))) {
+     *     System.out.printf("Deleted certificate's recovery Id %s%n", deletedCertificate.getRecoveryId());
+     * }
+     * 
+ * * * @param includePending indicate if pending deleted certificates should be included in the results. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -544,7 +740,18 @@ public PagedIterable listDeletedCertificates(boolean include * call {@link CertificateClient#getCertificateVersion(String, String)}. This will return the {@link KeyVaultCertificate certificate} * with all its properties excluding the policy.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions} + * + *
+     * for (CertificateProperties certificateProperties : certificateClient
+     *     .listPropertiesOfCertificateVersions("certificateName")) {
+     *     KeyVaultCertificate certificateWithAllProperties = certificateClient
+     *         .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion());
+     *     System.out.printf("Received certificate's version with name %s, version %s and secret id %s%n",
+     *         certificateWithAllProperties.getProperties().getName(),
+     *         certificateWithAllProperties.getProperties().getVersion(), certificateWithAllProperties.getSecretId());
+     * }
+     * 
+ * * * @param certificateName The name of the certificate. * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -565,7 +772,18 @@ public PagedIterable listPropertiesOfCertificateVersions( * call {@link CertificateClient#getCertificateVersion(String, String)}. This will return the {@link KeyVaultCertificate certificate} * with all its properties excluding the policy.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions#context} + * + *
+     * for (CertificateProperties certificateProperties : certificateClient
+     *     .listPropertiesOfCertificateVersions("certificateName")) {
+     *     KeyVaultCertificate certificateWithAllProperties = certificateClient
+     *         .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion());
+     *     System.out.printf("Received certificate's version with name %s, version %s and secret id %s%n",
+     *         certificateWithAllProperties.getProperties().getName(),
+     *         certificateWithAllProperties.getProperties().getVersion(), certificateWithAllProperties.getSecretId());
+     * }
+     * 
+ * * * @param certificateName The name of the certificate. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -585,7 +803,12 @@ public PagedIterable listPropertiesOfCertificateVersions( *

Gets the policy of a certirifcate in the key vault. Prints out the * returned certificate policy details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicy#string} + * + *
+     * CertificatePolicy policy = certificateClient.getCertificatePolicy("certificateName");
+     * System.out.printf("Received policy with subject name %s%n", policy.getSubject());
+     * 
+ * * * @param certificateName The name of the certificate whose policy is to be retrieved, cannot be null * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. @@ -604,7 +827,14 @@ public CertificatePolicy getCertificatePolicy(String certificateName) { *

Gets the policy of a certirifcate in the key vault. Prints out the * returned certificate policy details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicyWithResponse#string} + * + *
+     * Response<CertificatePolicy> returnedPolicyWithResponse = certificateClient.getCertificatePolicyWithResponse(
+     *     "certificateName", new Context(key1, value1));
+     * System.out.printf("Received policy with subject name %s%n",
+     *     returnedPolicyWithResponse.getValue().getSubject());
+     * 
+ * * * @param certificateName The name of the certificate whose policy is to be retrieved, cannot be null * @param context Additional context that is passed through the Http pipeline during the service call. @@ -625,7 +855,17 @@ public Response getCertificatePolicyWithResponse(String certi *

Gets the certificate policy, changes its properties and then updates it in the Azure Key Vault. Prints out the * returned policy details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicy#string} + * + *
+     * CertificatePolicy certificatePolicy = certificateClient.getCertificatePolicy("certificateName");
+     * //Update the certificate policy cert transparency property.
+     * certificatePolicy.setCertificateTransparent(true);
+     * CertificatePolicy updatedCertPolicy = certificateClient.updateCertificatePolicy("certificateName",
+     *     certificatePolicy);
+     * System.out.printf("Updated Certificate Policy transparency status %s%n",
+     *     updatedCertPolicy.isCertificateTransparent());
+     * 
+ * * * @param certificateName The name of the certificate whose policy is to be updated. * @param policy The certificate policy to be updated. @@ -647,7 +887,18 @@ public CertificatePolicy updateCertificatePolicy(String certificateName, Certifi *

Gets the certificate policy, changes its properties and then updates it in the Azure Key Vault. Prints out the * returned policy details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicyWithResponse#string} + * + *
+     * CertificatePolicy certificatePolicyToUpdate = certificateClient.getCertificatePolicy("certificateName");
+     * //Update the certificate policy cert transparency property.
+     * certificatePolicyToUpdate.setCertificateTransparent(true);
+     * Response<CertificatePolicy> updatedCertPolicyWithResponse = certificateClient
+     *     .updateCertificatePolicyWithResponse("certificateName", certificatePolicyToUpdate,
+     *         new Context(key1, value1));
+     * System.out.printf("Updated Certificate Policy transparency status %s%n", updatedCertPolicyWithResponse
+     *     .getValue().isCertificateTransparent());
+     * 
+ * * * @param certificateName The certificateName of the certificate whose policy is to be updated. * @param policy The certificate policy to be updated. @@ -670,7 +921,17 @@ public Response updateCertificatePolicyWithResponse(String ce *

Creates a new certificate issuer in the key vault. Prints out the created certificate issuer details when a * response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.createIssuer#CertificateIssuer} + * + *
+     * CertificateIssuer issuerToCreate = new CertificateIssuer("myissuer", "myProvider")
+     *     .setAccountId("testAccount")
+     *     .setAdministratorContacts(Collections.singletonList(new AdministratorContact().setFirstName("test")
+     *         .setLastName("name").setEmail("test@example.com")));
+     * CertificateIssuer returnedIssuer = certificateClient.createIssuer(issuerToCreate);
+     * System.out.printf("Created Issuer with name %s provider %s%n", returnedIssuer.getName(),
+     *     returnedIssuer.getProvider());
+     * 
+ * * * @param issuer The configuration of the certificate issuer to be created. * @throws ResourceModifiedException when invalid certificate issuer {@code issuer} configuration is provided. @@ -690,7 +951,18 @@ public CertificateIssuer createIssuer(CertificateIssuer issuer) { *

Creates a new certificate issuer in the key vault. Prints out the created certificate * issuer details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.createIssuerWithResponse#CertificateIssuer-Context} + * + *
+     * CertificateIssuer issuer = new CertificateIssuer("issuerName", "myProvider")
+     *     .setAccountId("testAccount")
+     *     .setAdministratorContacts(Collections.singletonList(new AdministratorContact().setFirstName("test")
+     *         .setLastName("name").setEmail("test@example.com")));
+     * Response<CertificateIssuer> issuerResponse = certificateClient.createIssuerWithResponse(issuer,
+     *     new Context(key1, value1));
+     * System.out.printf("Created Issuer with name %s provider %s%n", issuerResponse.getValue().getName(),
+     *     issuerResponse.getValue().getProvider());
+     * 
+ * * * @param issuer The configuration of the certificate issuer to be created. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -710,7 +982,14 @@ public Response createIssuerWithResponse(CertificateIssuer is *

Gets the specificed certifcate issuer in the key vault. Prints out the returned certificate issuer details when * a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getIssuerWithResponse#string-context} + * + *
+     * Response<CertificateIssuer> issuerResponse = certificateClient.getIssuerWithResponse("issuerName",
+     *     new Context(key1, value1));
+     * System.out.printf("Retrieved issuer with name %s and provider %s%n", issuerResponse.getValue().getName(),
+     *     issuerResponse.getValue().getProvider());
+     * 
+ * * * @param issuerName The name of the certificate issuer to retrieve, cannot be null * @param context Additional context that is passed through the Http pipeline during the service call. @@ -730,7 +1009,13 @@ public Response getIssuerWithResponse(String issuerName, Cont *

Gets the specified certificate issuer in the key vault. Prints out the returned certificate issuer details * when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.getIssuer#string} + * + *
+     * CertificateIssuer returnedIssuer = certificateClient.getIssuer("issuerName");
+     * System.out.printf("Retrieved issuer with name %s and provider %s%n", returnedIssuer.getName(),
+     *     returnedIssuer.getProvider());
+     * 
+ * * * @param issuerName The name of the certificate issuer to retrieve, cannot be null * @throws ResourceNotFoundException when a certificate issuer with {@code issuerName} doesn't exist in the key vault. @@ -750,7 +1035,13 @@ public CertificateIssuer getIssuer(String issuerName) { *

Deletes the certificate issuer in the Azure Key Vault. Prints out the * deleted certificate details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.deleteIssuerWithResponse#string-context} + * + *
+     * CertificateIssuer deletedIssuer = certificateClient.deleteIssuer("certificateName");
+     * System.out.printf("Deleted certificate issuer with name %s and provider id %s%n", deletedIssuer.getName(),
+     *     deletedIssuer.getProvider());
+     * 
+ * * * @param issuerName The name of the certificate issuer to be deleted. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -771,7 +1062,15 @@ public Response deleteIssuerWithResponse(String issuerName, C *

Deletes the certificate issuer in the Azure Key Vault. Prints out the deleted certificate details when a * response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.deleteIssuer#string} + * + *
+     * Response<CertificateIssuer> deletedIssuerWithResponse = certificateClient.
+     *     deleteIssuerWithResponse("certificateName", new Context(key1, value1));
+     * System.out.printf("Deleted certificate issuer with name %s and provider id %s%n",
+     *     deletedIssuerWithResponse.getValue().getName(),
+     *     deletedIssuerWithResponse.getValue().getProvider());
+     * 
+ * * * @param issuerName The name of the certificate issuer to be deleted. * @throws ResourceNotFoundException when a certificate issuer with {@code issuerName} doesn't exist in the key vault. @@ -792,7 +1091,15 @@ public CertificateIssuer deleteIssuer(String issuerName) { * call {@link CertificateClient#getIssuer(String)} . This will return the {@link CertificateIssuer issuer} * with all its properties.

. * - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers} + * + *
+     * for (IssuerProperties issuer : certificateClient.listPropertiesOfIssuers()) {
+     *     CertificateIssuer retrievedIssuer = certificateClient.getIssuer(issuer.getName());
+     *     System.out.printf("Received issuer with name %s and provider %s%n", retrievedIssuer.getName(),
+     *         retrievedIssuer.getProvider());
+     * }
+     * 
+ * * * @return A {@link PagedIterable} containing all of the {@link IssuerProperties certificate issuers} in the vault. */ @@ -810,7 +1117,15 @@ public PagedIterable listPropertiesOfIssuers() { * call {@link CertificateClient#getIssuer(String)}. This will return the {@link CertificateIssuer issuer} * with all its properties.

. * - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers#context} + * + *
+     * for (IssuerProperties issuer : certificateClient.listPropertiesOfIssuers(new Context(key1, value1))) {
+     *     CertificateIssuer retrievedIssuer = certificateClient.getIssuer(issuer.getName());
+     *     System.out.printf("Received issuer with name %s and provider %s%n", retrievedIssuer.getName(),
+     *         retrievedIssuer.getProvider());
+     * }
+     * 
+ * * * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link PagedIterable} containing all of the {@link IssuerProperties certificate issuers} in the vault. @@ -828,7 +1143,15 @@ public PagedIterable listPropertiesOfIssuers(Context context) *

Gets the certificate issuer, changes its attributes/properties then updates it in the Azure Key Vault. Prints out the * returned certificate issuer details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.updateIssuer#CertificateIssuer} + * + *
+     * CertificateIssuer returnedIssuer = certificateClient.getIssuer("issuerName");
+     * returnedIssuer.setAccountId("newAccountId");
+     * CertificateIssuer updatedIssuer = certificateClient.updateIssuer(returnedIssuer);
+     * System.out.printf("Updated issuer with name %s, provider %s and account Id %s%n", updatedIssuer.getName(),
+     *     updatedIssuer.getProvider(), updatedIssuer.getAccountId());
+     * 
+ * * * @param issuer The {@link CertificateIssuer issuer} with updated properties. * @throws NullPointerException if {@code issuer} is {@code null}. @@ -849,7 +1172,18 @@ public CertificateIssuer updateIssuer(CertificateIssuer issuer) { *

Gets the certificate issuer, changes its attributes/properties then updates it in the Azure Key Vault. Prints out the * returned certificate issuer details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.updateIssuerWithResponse#CertificateIssuer-Context} + * + *
+     * CertificateIssuer issuer = certificateClient.getIssuer("issuerName");
+     * returnedIssuer.setAccountId("newAccountId");
+     * Response<CertificateIssuer> updatedIssuerWithResponse = certificateClient.updateIssuerWithResponse(issuer,
+     *     new Context(key1, value1));
+     * System.out.printf("Updated issuer with name %s, provider %s and account Id %s%n",
+     *     updatedIssuerWithResponse.getValue().getName(),
+     *     updatedIssuerWithResponse.getValue().getProvider(),
+     *     updatedIssuerWithResponse.getValue().getAccountId());
+     * 
+ * * * @param issuer The {@link CertificateIssuer issuer} with updated properties. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -871,7 +1205,15 @@ public Response updateIssuerWithResponse(CertificateIssuer is *

Code Samples

*

Sets the certificate contacts in the Azure Key Vault. Prints out the returned contacts details.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts} + * + *
+     * CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com");
+     * for (CertificateContact contact : certificateClient.setContacts(Collections.singletonList(contactToAdd))) {
+     *     System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(),
+     *         contact.getEmail());
+     * }
+     * 
+ * * * @param contacts The list of contacts to set on the vault. * @throws HttpRequestException when a contact information provided is invalid/incomplete. @@ -890,7 +1232,16 @@ public PagedIterable setContacts(List co *

Code Samples

*

Sets the certificate contacts in the Azure Key Vault. Prints out the returned contacts details.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts-context} + * + *
+     * CertificateContact sampleContact = new CertificateContact().setName("user").setEmail("useremail@example.com");
+     * for (CertificateContact contact : certificateClient.setContacts(Collections.singletonList(sampleContact),
+     *     new Context(key1, value1))) {
+     *     System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(),
+     *         contact.getEmail());
+     * }
+     * 
+ * * * @param contacts The list of contacts to set on the vault. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -908,7 +1259,14 @@ public PagedIterable setContacts(List co *

Code Samples

*

Lists the certificate contacts in the Azure Key Vault. Prints out the returned contacts details in the response.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listContacts} + * + *
+     * for (CertificateContact contact : certificateClient.listContacts()) {
+     *     System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(),
+     *         contact.getEmail());
+     * }
+     * 
+ * * * @return A {@link PagedIterable} containing all of the {@link CertificateContact certificate contacts} in the vault. */ @@ -923,7 +1281,14 @@ public PagedIterable listContacts() { *

Code Samples

*

Lists the certificate contacts in the Azure Key Vault. Prints out the returned contacts details in the response.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.listContacts#context} + * + *
+     * for (CertificateContact contact : certificateClient.listContacts(new Context(key1, value1))) {
+     *     System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(),
+     *         contact.getEmail());
+     * }
+     * 
+ * * * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link PagedIterable} containing all of the {@link CertificateContact certificate contacts} in the vault. @@ -940,7 +1305,14 @@ public PagedIterable listContacts(Context context) { *

Deletes the certificate contacts in the Azure Key Vault. Subscribes to the call and prints out the * deleted contacts details.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.deleteContacts} + * + *
+     * for (CertificateContact contact : certificateClient.deleteContacts()) {
+     *     System.out.printf("Deleted contact with name %s and email %s from key vault%n", contact.getName(),
+     *         contact.getEmail());
+     * }
+     * 
+ * * * @return A {@link PagedIterable} containing all of the deleted {@link CertificateContact certificate contacts} in the vault. */ @@ -955,7 +1327,14 @@ public PagedIterable deleteContacts() { *

Code Samples

*

Deletes the certificate contacts in the Azure Key Vault. Prints out the deleted contacts details in the response.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.deleteContacts#context} + * + *
+     * for (CertificateContact contact : certificateClient.deleteContacts(new Context(key1, value1))) {
+     *     System.out.printf("Deleted contact with name %s and email %s from key vault%n", contact.getName(),
+     *         contact.getEmail());
+     * }
+     * 
+ * * * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link PagedIterable} containing all of the deleted {@link CertificateContact certificate contacts} in the vault. @@ -973,7 +1352,14 @@ public PagedIterable deleteContacts(Context context) { *

Triggers certificate creation and then deletes the certificate creation operation in the Azure Key Vault. Subscribes to the call and prints out the * deleted certificate operation details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperation#string} + * + *
+     * Response<CertificateOperation> deletedCertificateOperationWithResponse = certificateClient
+     *     .deleteCertificateOperationWithResponse("certificateName", new Context(key1, value1));
+     * System.out.printf("Deleted Certificate Operation's last status %s%n",
+     *     deletedCertificateOperationWithResponse.getValue().getStatus());
+     * 
+ * * * @param certificateName The name of the certificate. * @throws ResourceNotFoundException when a certificate operation for a certificate with {@code certificateName} doesn't exist in the key vault. @@ -993,7 +1379,13 @@ public CertificateOperation deleteCertificateOperation(String certificateName) { *

Triggers certificate creation and then deletes the certificate creation operation in the Azure Key Vault. Subscribes to the call and prints out the * deleted certificate operation details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperationWithResponse#string} + * + *
+     * CertificateOperation deletedCertificateOperation = certificateClient
+     *     .deleteCertificateOperation("certificateName");
+     * System.out.printf("Deleted Certificate Operation's last status %s%n", deletedCertificateOperation.getStatus());
+     * 
+ * * * @param certificateName The name of the certificate. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -1013,7 +1405,13 @@ public Response deleteCertificateOperationWithResponse(Str *

Triggers certificate creation and then cancels the certificate creation operation in the Azure Key Vault. Subscribes to the call and prints out the * updated certificate operation details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperation#string} + * + *
+     * CertificateOperation certificateOperation = certificateClient
+     *     .cancelCertificateOperation("certificateName");
+     * System.out.printf("Certificate Operation status %s%n", certificateOperation.getStatus());
+     * 
+ * * * @param certificateName The name of the certificate which is in the process of being created. * @throws ResourceNotFoundException when a certificate operation for a certificate with {@code name} doesn't exist in the key vault. @@ -1032,7 +1430,13 @@ public CertificateOperation cancelCertificateOperation(String certificateName) { *

Triggers certificate creation and then cancels the certificate creation operation in the Azure Key Vault. Subscribes to the call and prints out the * updated certificate operation details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperationWithResponse#string} + * + *
+     * Response<CertificateOperation> certificateOperationWithResponse = certificateClient
+     *     .cancelCertificateOperationWithResponse("certificateName", new Context(key1, value1));
+     * System.out.printf("Certificate Operation status %s%n", certificateOperationWithResponse.getValue().getStatus());
+     * 
+ * * * @param certificateName The name of the certificate which is in the process of being created. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -1052,7 +1456,17 @@ public Response cancelCertificateOperationWithResponse(Str *

Code Samples

*

Merges a certificate with a kay pair available in the service.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.mergeCertificate#config} + * + *
+     * List<byte[]> x509CertificatesToMerge = new ArrayList<>();
+     * MergeCertificateOptions config =
+     *     new MergeCertificateOptions("certificateName", x509CertificatesToMerge)
+     *         .setEnabled(false);
+     * KeyVaultCertificate mergedCertificate = certificateClient.mergeCertificate(config);
+     * System.out.printf("Received Certificate with name %s and key id %s%n",
+     *     mergedCertificate.getProperties().getName(), mergedCertificate.getKeyId());
+     * 
+ * * * @param mergeCertificateOptions the merge certificate configuration holding the x509 certificates. * @throws NullPointerException when {@code mergeCertificateOptions} is null. @@ -1071,7 +1485,19 @@ public KeyVaultCertificateWithPolicy mergeCertificate(MergeCertificateOptions me *

Code Samples

*

Merges a certificate with a kay pair available in the service.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.mergeCertificateWithResponse#config} + * + *
+     * List<byte[]> x509CertsToMerge = new ArrayList<>();
+     * MergeCertificateOptions mergeConfig =
+     *     new MergeCertificateOptions("certificateName", x509CertsToMerge)
+     *         .setEnabled(false);
+     * Response<KeyVaultCertificateWithPolicy> mergedCertificateWithResponse =
+     *     certificateClient.mergeCertificateWithResponse(mergeConfig, new Context(key2, value2));
+     * System.out.printf("Received Certificate with name %s and key id %s%n",
+     *     mergedCertificateWithResponse.getValue().getProperties().getName(),
+     *     mergedCertificateWithResponse.getValue().getKeyId());
+     * 
+ * * * @param mergeCertificateOptions the merge certificate configuration holding the x509 certificates. * @param context Additional context that is passed through the Http pipeline during the service call. @@ -1092,7 +1518,16 @@ public Response mergeCertificateWithResponse(Merg *

Code Samples

*

Imports a certificate into the key vault.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.importCertificate#options} + * + *
+     * byte[] certificateToImport = new byte[100];
+     * ImportCertificateOptions config =
+     *     new ImportCertificateOptions("certificateName", certificateToImport).setEnabled(false);
+     * KeyVaultCertificate importedCertificate = certificateClient.importCertificate(config);
+     * System.out.printf("Received Certificate with name %s and key id %s%n",
+     *     importedCertificate.getProperties().getName(), importedCertificate.getKeyId());
+     * 
+ * * * @param importCertificateOptions The details of the certificate to import to the key vault * @throws HttpRequestException when the {@code importCertificateOptions} are invalid. @@ -1110,7 +1545,18 @@ public KeyVaultCertificateWithPolicy importCertificate(ImportCertificateOptions *

Code Samples

*

Imports a certificate into the key vault.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.importCertificateWithResponse#options} + * + *
+     * byte[] certToImport = new byte[100];
+     * ImportCertificateOptions importCertificateOptions =
+     *     new ImportCertificateOptions("certificateName", certToImport).setEnabled(false);
+     * Response<KeyVaultCertificateWithPolicy> importedCertificateWithResponse =
+     *     certificateClient.importCertificateWithResponse(importCertificateOptions, new Context(key2, value2));
+     * System.out.printf("Received Certificate with name %s and key id %s%n",
+     *     importedCertificateWithResponse.getValue().getProperties().getName(),
+     *     importedCertificateWithResponse.getValue().getKeyId());
+     * 
+ * * * @param importCertificateOptions The details of the certificate to import to the key vault * @param context Additional context that is passed through the Http pipeline during the service call. diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClientBuilder.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClientBuilder.java index f755eea1d257e..63190aabe5507 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClientBuilder.java @@ -43,25 +43,60 @@ * CertificateAsyncClient} * are {@link String vaultUrl} and {@link TokenCredential credential}.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation} + * + *
+ * CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .vaultUrl("https://myvault.vault.azure.net/")
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .buildAsyncClient();
+ * 
+ * * *

The {@link HttpLogDetailLevel log detail level}, multiple custom {@link HttpLoggingPolicy policies} and custom * {@link HttpClient http client} can be optionally configured in the {@link CertificateClientBuilder}.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.withhttpclient.instantiation} + * + *
+ * CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .httpClient(HttpClient.createDefault())
+ *     .buildAsyncClient();
+ * 
+ * * *

Alternatively, custom {@link HttpPipeline http pipeline} with custom {@link HttpPipelinePolicy} policies and * {@link String vaultUrl} * can be specified. It provides finer control over the construction of {@link CertificateAsyncClient} and {@link * CertificateClient}

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.pipeline.instantiation} + * + *
+ * HttpPipeline pipeline = new HttpPipelineBuilder()
+ *     .policies(new KeyVaultCredentialPolicy(new DefaultAzureCredentialBuilder().build()), new RetryPolicy())
+ *     .build();
+ * CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
+ *     .pipeline(pipeline)
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .buildAsyncClient();
+ * 
+ * * *

The minimal configuration options required by {@link CertificateClientBuilder certificateClientBuilder} to build * {@link CertificateClient} * are {@link String vaultUrl} and {@link TokenCredential credential}.

* - * {@codesnippet com.azure.security.keyvault.certificates.CertificateClient.instantiation} + * + *
+ * CertificateClient certificateClient = new CertificateClientBuilder()
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .vaultUrl("https://myvault.vault.azure.net/")
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .buildClient();
+ * 
+ * * * @see CertificateAsyncClient * @see CertificateClient @@ -121,14 +156,14 @@ public CertificateClient buildClient() { /** * Creates a {@link CertificateAsyncClient} based on options set in the builder. Every time - * {@link #buildAsyncClient()} is called, a new instance of {@link CertificateAsyncClient} is created. + * {@code buildAsyncClient()} is called, a new instance of {@link CertificateAsyncClient} is created. * *

If {@link CertificateClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and * {@link CertificateClientBuilder#vaultUrl(String) serviceEndpoint} are used to create the {@link * CertificateClientBuilder client}. All other builder settings are ignored. If {@code pipeline} is not set, then - * {@link CertificateClientBuilder#credential(TokenCredential) key vault credential and {@link + * {@link CertificateClientBuilder#credential(TokenCredential) key vault credential} and {@link * CertificateClientBuilder#vaultUrl(String)} key vault url are required to build the {@link CertificateAsyncClient - * client}.}

+ * client}.

* * @return A {@link CertificateAsyncClient} with the options set from the builder. * diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateServiceVersion.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateServiceVersion.java index 2e88096369c0f..3cf5099a1d37e 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateServiceVersion.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateServiceVersion.java @@ -9,9 +9,24 @@ * The versions of Azure Key Vault Certificate supported by this client library. */ public enum CertificateServiceVersion implements ServiceVersion { + /** + * Service version {@code 7.0}. + */ V7_0("7.0"), + + /** + * Service version {@code 7.1}. + */ V7_1("7.1"), + + /** + * Service version {@code 7.2}. + */ V7_2("7.2"), + + /** + * Service version {@code 7.3-preview}. + */ V7_3_PREVIEW("7.3-preview"); private final String version; diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/samples/java/com/azure/security/keyvault/certificates/ReadmeSamples.java b/sdk/keyvault/azure-security-keyvault-certificates/src/samples/java/com/azure/security/keyvault/certificates/ReadmeSamples.java new file mode 100644 index 0000000000000..bbf24b92e143b --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/samples/java/com/azure/security/keyvault/certificates/ReadmeSamples.java @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; + +@SuppressWarnings("unused") +public class ReadmeSamples { + private final CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + private final CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + public void createCertificateClient() { + // BEGIN: readme-sample-createCertificateClient + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createCertificateClient + } + + public void createCertificate() { + // BEGIN: readme-sample-createCertificate + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certificateName", CertificatePolicy.getDefault()); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + KeyVaultCertificate certificate = certificatePoller.getFinalResult(); + System.out.printf("Certificate created with name \"%s\"%n", certificate.getName()); + // END: readme-sample-createCertificate + } + + public void retrieveCertificate() { + // BEGIN: readme-sample-retrieveCertificate + KeyVaultCertificateWithPolicy certificate = certificateClient.getCertificate(""); + System.out.printf("Received certificate with name \"%s\", version %s and secret id %s%n", + certificate.getProperties().getName(), certificate.getProperties().getVersion(), certificate.getSecretId()); + // END: readme-sample-retrieveCertificate + } + + public void updateCertificate() { + // BEGIN: readme-sample-updateCertificate + // Get the certificate to update. + KeyVaultCertificate certificate = certificateClient.getCertificate(""); + // Update certificate enabled status. + certificate.getProperties().setEnabled(false); + KeyVaultCertificate updatedCertificate = certificateClient.updateCertificateProperties(certificate.getProperties()); + System.out.printf("Updated certificate with name \"%s\" and enabled status \"%s\"%n", + updatedCertificate.getProperties().getName(), updatedCertificate.getProperties().isEnabled()); + // END: readme-sample-updateCertificate + } + + public void deleteCertificate() { + // BEGIN: readme-sample-deleteCertificate + SyncPoller deleteCertificatePoller = + certificateClient.beginDeleteCertificate(""); + + // Deleted certificate is accessible as soon as polling beings. + PollResponse pollResponse = deleteCertificatePoller.poll(); + + // Deletion date only works for a SoftDelete-enabled Key Vault. + System.out.printf("Deleted certificate with name \"%s\" and recovery id %s", pollResponse.getValue().getName(), + pollResponse.getValue().getRecoveryId()); + + // Certificate is being deleted on server. + deleteCertificatePoller.waitForCompletion(); + // END: readme-sample-deleteCertificate + } + + public void listCertificates() { + // BEGIN: readme-sample-listCertificates + // List operations don't return the certificates with their full information. So, for each returned certificate we call + // getCertificate to get the certificate with all its properties excluding the policy. + for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) { + KeyVaultCertificate certificateWithAllProperties = + certificateClient.getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate with name \"%s\" and secret id %s", + certificateWithAllProperties.getProperties().getName(), certificateWithAllProperties.getSecretId()); + } + // END: readme-sample-listCertificates + } + + public void createCertificateAsync() { + // BEGIN: readme-sample-createCertificateAsync + // Creates a certificate using the default policy and polls on its progress. + certificateAsyncClient.beginCreateCertificate("", CertificatePolicy.getDefault()) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + // END: readme-sample-createCertificateAsync + } + + public void retrieveCertificateAsync() { + // BEGIN: readme-sample-retrieveCertificateAsync + certificateAsyncClient.getCertificate("") + .subscribe(certificateResponse -> + System.out.printf("Certificate was returned with name \"%s\" and secretId %s%n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId())); + // END: readme-sample-retrieveCertificateAsync + } + + public void updateCertificateAsync() { + // BEGIN: readme-sample-updateCertificateAsync + certificateAsyncClient.getCertificate("") + .flatMap(certificate -> { + // Update enabled status of the certificate. + certificate.getProperties().setEnabled(false); + return certificateAsyncClient.updateCertificateProperties(certificate.getProperties()); + }).subscribe(certificateResponse -> System.out.printf("Certificate's enabled status: %s%n", + certificateResponse.getProperties().isEnabled())); + // END: readme-sample-updateCertificateAsync + } + + public void deleteCertificateAsync() { + // BEGIN: readme-sample-deleteCertificateAsync + certificateAsyncClient.beginDeleteCertificate("") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deleted certificate name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Certificate deletion date: %s%n", pollResponse.getValue().getDeletedOn()); + }); + // END: readme-sample-deleteCertificateAsync + } + + public void listCertificateAsync() { + // BEGIN: readme-sample-listCertificateAsync + // The List Certificates operation returns certificates without their full properties, so for each certificate returned + // we call `getCertificate` to get all its attributes excluding the policy. + certificateAsyncClient.listPropertiesOfCertificates() + .flatMap(certificateProperties -> certificateAsyncClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion())) + .subscribe(certificateResponse -> + System.out.printf("Received certificate with name \"%s\" and key id %s", certificateResponse.getName(), + certificateResponse.getKeyId())); + // END: readme-sample-listCertificateAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + certificateClient.getCertificate(""); + } catch (ResourceNotFoundException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } +} diff --git a/sdk/keyvault/azure-security-keyvault-jca/README.md b/sdk/keyvault/azure-security-keyvault-jca/README.md index f3687da5f4d46..1288e5d1017d4 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/README.md +++ b/sdk/keyvault/azure-security-keyvault-jca/README.md @@ -38,8 +38,7 @@ az keyvault create --resource-group --name -```java +```java readme-sample-serverSSL KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); Security.addProvider(provider); @@ -60,8 +59,7 @@ Note if you want to use Azure Managed Identity, you should set the value of `azu ### Client side SSL If you are looking to integrate the JCA provider for client side socket connections, see the Apache HTTP client example below. - -```java +```java readme-sample-clientSSL KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); Security.addProvider(provider); diff --git a/sdk/keyvault/azure-security-keyvault-jca/pom.xml b/sdk/keyvault/azure-security-keyvault-jca/pom.xml index 7cd2ab13e6816..aae747f537d83 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-jca/pom.xml @@ -22,6 +22,9 @@ UTF-8 0 0.05 + false + + diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultJcaProvider.java b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultJcaProvider.java index 479fd1c936112..51e2e494d3c90 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultJcaProvider.java +++ b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultJcaProvider.java @@ -10,7 +10,6 @@ import com.azure.security.keyvault.jca.implementation.signature.AbstractKeyVaultKeyLessSignature; import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; import java.security.PrivilegedAction; import java.security.Provider; import java.util.Arrays; @@ -55,7 +54,7 @@ public KeyVaultJcaProvider() { */ @SuppressWarnings("removal") private void initialize() { - AccessController.doPrivileged((PrivilegedAction) () -> { + java.security.AccessController.doPrivileged((PrivilegedAction) () -> { putService( new Provider.Service( this, diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultPrivateKey.java b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultPrivateKey.java index c45851bd00017..760b42a536ed0 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultPrivateKey.java +++ b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultPrivateKey.java @@ -20,8 +20,14 @@ public class KeyVaultPrivateKey implements PrivateKey, SecretKey { */ private static final long serialVersionUID = 30_10_00; + /** + * Key ID. + */ private String kid; + /** + * Algorithm. + */ private String algorithm; /** diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultTrustManagerFactoryProvider.java b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultTrustManagerFactoryProvider.java index 768885006e52f..1261376b882fa 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultTrustManagerFactoryProvider.java +++ b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultTrustManagerFactoryProvider.java @@ -3,7 +3,6 @@ package com.azure.security.keyvault.jca; -import java.security.AccessController; import java.security.PrivilegedAction; import java.security.Provider; @@ -45,7 +44,7 @@ public KeyVaultTrustManagerFactoryProvider() { */ @SuppressWarnings("removal") private void initialize() { - AccessController.doPrivileged((PrivilegedAction) () -> { + java.security.AccessController.doPrivileged((PrivilegedAction) () -> { putService( new Provider.Service( this, diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/JREKeyStoreFactory.java b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/JREKeyStoreFactory.java index f4475e5c70583..8548e32ce3051 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/JREKeyStoreFactory.java +++ b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/JREKeyStoreFactory.java @@ -8,7 +8,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.security.AccessController; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; @@ -85,7 +84,7 @@ private static Path getConfiguredKeyStorePath() { @SuppressWarnings("removal") private static String privilegedGetProperty(String theProp, String defaultVal) { - return AccessController.doPrivileged( + return java.security.AccessController.doPrivileged( (PrivilegedAction) () -> { String value = System.getProperty(theProp, ""); return (value.isEmpty()) ? defaultVal : value; diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/KeyVaultPrivateKey.java b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/KeyVaultPrivateKey.java index 31749b803f7d5..e7bbfdfa92cfc 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/KeyVaultPrivateKey.java +++ b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/KeyVaultPrivateKey.java @@ -16,8 +16,14 @@ public class KeyVaultPrivateKey implements PrivateKey, SecretKey { */ private static final long serialVersionUID = 30_10_00; + /** + * Key ID. + */ private String kid; + /** + * Algorithm. + */ private String algorithm; private final KeyVaultClient keyVaultClient; diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ClientSSLSample.java b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ClientSSLSample.java index 421977f571507..6de8d95522985 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ClientSSLSample.java +++ b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ClientSSLSample.java @@ -25,6 +25,7 @@ public class ClientSSLSample { public static void main(String[] args) throws Exception { + // BEGIN: readme-sample-clientSSL KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); Security.addProvider(provider); @@ -59,6 +60,7 @@ public static void main(String[] args) throws Exception { } catch (IOException ioe) { ioe.printStackTrace(); } + // END: readme-sample-clientSSL } } diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ServerSSLSample.java b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ServerSSLSample.java index 58006054aadb5..94a148036badd 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ServerSSLSample.java +++ b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ServerSSLSample.java @@ -15,6 +15,7 @@ public class ServerSSLSample { public static void main(String[] args) throws Exception { + // BEGIN: readme-sample-serverSSL KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); Security.addProvider(provider); @@ -28,6 +29,7 @@ public static void main(String[] args) throws Exception { SSLServerSocketFactory socketFactory = context.getServerSocketFactory(); SSLServerSocket serverSocket = (SSLServerSocket) socketFactory.createServerSocket(8765); + // END: readme-sample-serverSSL } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/README.md b/sdk/keyvault/azure-security-keyvault-keys/README.md index 9baa2c2e2b17e..a55b6404be0be 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/README.md +++ b/sdk/keyvault/azure-security-keyvault-keys/README.md @@ -26,9 +26,9 @@ Maven dependency for the Azure Key Vault Key client library. Add it to your proj - [Azure Subscription][azure_subscription] - An existing [Azure Key Vault][azure_keyvault]. If you need to create a Key Vault, you can use the [Azure Cloud Shell][azure_cloud_shell] to create one with this Azure CLI command. Replace `` and `` with your own, unique names: - ```Bash - az keyvault create --resource-group --name - ``` +```bash +az keyvault create --resource-group --name +``` ### Authenticate the client In order to interact with the Azure Key Vault service, you'll need to create an instance of the [KeyClient](#create-key-client) class. You would need a **vault url** and **client secret credentials (client id, client secret, tenant id)** to instantiate a client object using the default `DefaultAzureCredential` examples shown in this document. @@ -42,56 +42,56 @@ Here is an [Azure Cloud Shell][azure_cloud_shell] snippet below to * Create a service principal and configure its access to Azure resources: - ```Bash - az ad sp create-for-rbac -n --skip-assignment - ``` - - Output: - - ```json - { - "appId": "generated-app-ID", - "displayName": "dummy-app-name", - "name": "http://dummy-app-name", - "password": "random-password", - "tenant": "tenant-ID" - } - ``` +```bash +az ad sp create-for-rbac -n --skip-assignment +```` + +Output: + +```json +{ + "appId": "generated-app-ID", + "displayName": "dummy-app-name", + "name": "http://dummy-app-name", + "password": "random-password", + "tenant": "tenant-ID" +} +``` * Take note of the service principal objectId - ```PowerShell - az ad sp show --id --query objectId - ``` - Output: - ``` - "" - ``` +```PowerShell +az ad sp show --id --query objectId +``` +Output: +``` +"" +``` * Use the returned credentials above to set the **AZURE_CLIENT_ID** (appId), **AZURE_CLIENT_SECRET** (password), and **AZURE_TENANT_ID** (tenantId) environment variables. The following example shows a way to do this in Bash: - ```Bash - export AZURE_CLIENT_ID="generated-app-ID" - export AZURE_CLIENT_SECRET="random-password" - export AZURE_TENANT_ID="tenant-ID" - ``` +```bash +export AZURE_CLIENT_ID="generated-app-ID" +export AZURE_CLIENT_SECRET="random-password" +export AZURE_TENANT_ID="tenant-ID" +``` * Grant the aforementioned application authorization to perform key operations on the Key Vault: - ```Bash - az keyvault set-policy --name --spn $AZURE_CLIENT_ID --key-permissions backup delete get list create update encrypt decrypt - ``` +```bash +az keyvault set-policy --name --spn $AZURE_CLIENT_ID --key-permissions backup delete get list create update encrypt decrypt +``` - > --key-permissions: - > Accepted values: backup, delete, get, list, purge, recover, restore, create, update, encrypt, decrypt, import, wrapkey, unwrapkey, verify, sign +> --key-permissions: +> Accepted values: backup, delete, get, list, purge, recover, restore, create, update, encrypt, decrypt, import, wrapkey, unwrapkey, verify, sign - If you have enabled role-based access control (RBAC) for Key Vault instead, you can find roles like "Key Vault Crypto Officer" in our [RBAC guide][rbac_guide]. - If you are managing your keys using Managed HSM, read about its [access control][access_control] that supports different built-in roles isolated from Azure Resource Manager (ARM). +If you have enabled role-based access control (RBAC) for Key Vault instead, you can find roles like "Key Vault Crypto Officer" in our [RBAC guide][rbac_guide]. +If you are managing your keys using Managed HSM, read about its [access control][access_control] that supports different built-in roles isolated from Azure Resource Manager (ARM). * Use the aforementioned Key Vault name to retrieve details of your Key Vault, which also contain your Key Vault URL: - ```Bash - az keyvault show --name - ``` +```bash +az keyvault show --name +``` * Create the Azure Key Vault or Managed HSM and grant the above mentioned application authorization to perform administrative operations on the Managed HSM (replace `` and `` with your own unique names and `` with the value from above): @@ -134,11 +134,7 @@ az keyvault security-domain download --hsm-name --sd-wrapp #### Create Key client Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET**, and **AZURE_TENANT_ID** environment variables and replaced **your-key-vault-url** with the URI returned above, you can create the KeyClient: -```Java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.KeyClientBuilder; - +```java readme-sample-createKeyClient KeyClient keyClient = new KeyClientBuilder() .vaultUrl("") .credential(new DefaultAzureCredentialBuilder().build()) @@ -150,11 +146,7 @@ KeyClient keyClient = new KeyClientBuilder() #### Create Cryptography client Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET**, and **AZURE_TENANT_ID** environment variables and replaced **your-vault-url** with the URI returned above, you can create the CryptographyClient: -```Java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.cryptography.CryptographyClient; -import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder; - +```java readme-sample-createCryptographyClient // Create client with key identifier from key vault. CryptographyClient cryptoClient = new CryptographyClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) @@ -194,20 +186,7 @@ The following sections provide several code snippets covering some of the most c Create a key to be stored in the Azure Key Vault. - `createKey` creates a new key in the key vault. If a key with the same name already exists then a new version of the key is created. -```Java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import com.azure.security.keyvault.keys.KeyClientBuilder; - -KeyClient keyClient = new KeyClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - +```java readme-sample-createKey KeyVaultKey rsaKey = keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") .setExpiresOn(OffsetDateTime.now().plusYears(1)) .setKeySize(2048)); @@ -222,7 +201,7 @@ System.out.printf("Key created with name \"%s\" and id %s%n", ecKey.getName(), e ### Retrieve a key Retrieve a previously stored key by calling `getKey`. -```Java +```java readme-sample-retrieveKey KeyVaultKey key = keyClient.getKey(""); System.out.printf("A key was returned with name \"%s\" and id %s%n", key.getName(), key.getId()); ``` @@ -230,7 +209,7 @@ System.out.printf("A key was returned with name \"%s\" and id %s%n", key.getName ### Update an existing key Update an existing key by calling `updateKeyProperties`. -```Java +```java readme-sample-updateKey // Get the key to update. KeyVaultKey key = keyClient.getKey(""); // Update the expiry time of the key. @@ -242,7 +221,7 @@ System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties(). ### Delete a key Delete an existing key by calling `beginDeleteKey`. -```Java +```java readme-sample-deleteKey SyncPoller deletedKeyPoller = keyClient.beginDeleteKey(""); PollResponse deletedKeyPollResponse = deletedKeyPoller.poll(); @@ -259,7 +238,7 @@ deletedKeyPoller.waitForCompletion(); ### List keys List the keys in the key vault by calling `listPropertiesOfKeys`. -```java +```java readme-sample-listKeys // List operations don't return the keys with key material information. So, for each returned key we call getKey to // get the key with its key material information. for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { @@ -272,14 +251,9 @@ for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { ### Encrypt Encrypt plain text by calling `encrypt`. -```java -CryptographyClient cryptoClient = new CryptographyClientBuilder() - .credential(new DefaultAzureCredentialBuilder().build()) - .keyIdentifier("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - +```java readme-sample-createKeyAsync keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1)) - .setKeySize(2048)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)) .subscribe(key -> System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") - .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .setExpiresOn(OffsetDateTime.now().plusYears(1))) .subscribe(key -> System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); ``` @@ -343,7 +306,7 @@ keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") ### Retrieve a key asynchronously Retrieve a previously stored key by calling `getKey`. -```Java +```java readme-sample-retrieveKeyAsync keyAsyncClient.getKey("") .subscribe(key -> System.out.printf("Key was returned with name \"%s\" and id %s%n", key.getName(), key.getId())); @@ -352,25 +315,23 @@ keyAsyncClient.getKey("") ### Update an existing key asynchronously Update an existing key by calling `updateKeyProperties`. -```Java -// Get the key. +```java readme-sample-updateKeyAsync keyAsyncClient.getKey("") - .subscribe(key -> { + .flatMap(key -> { // Update the expiry time of the key. key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); - keyAsyncClient.updateKeyProperties(key.getProperties()) - .subscribe(updatedKey -> - System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn())); - }); + return keyAsyncClient.updateKeyProperties(key.getProperties()); + }).subscribe(updatedKey -> + System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn())); ``` ### Delete a key asynchronously Delete an existing key by calling `beginDeleteKey`. -```java +```java readme-sample-deleteKeyAsync keyAsyncClient.beginDeleteKey("") .subscribe(pollResponse -> { - System.out.printf("Deletetion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); System.out.printf("Deleted key name: %s%n", pollResponse.getValue().getName()); System.out.printf("Key deletion date: %s%n", pollResponse.getValue().getDeletedOn()); }); @@ -379,62 +340,53 @@ keyAsyncClient.beginDeleteKey("") ### List keys asynchronously List the keys in the Azure Key Vault by calling `listPropertiesOfKeys`. -```Java +```java readme-sample-listKeysAsync // The List Keys operation returns keys without their value, so for each key returned we call `getKey` to get its value // as well. keyAsyncClient.listPropertiesOfKeys() - .subscribe(keyProperties -> - keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion()) - .subscribe(key -> - System.out.printf("Received key with name \"%s\" and type \"%s\"", key.getName(), key.getKeyType()))); + .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) + .subscribe(key -> + System.out.printf("Received key with name \"%s\" and type \"%s\"", key.getName(), key.getKeyType())); ``` ### Encrypt asynchronously Encrypt plain text by calling `encrypt`. -```java -CryptographyAsyncClient cryptoAsyncClient = new CryptographyClientBuilder() - .credential(new DefaultAzureCredentialBuilder().build()) - .keyIdentifier("") - .buildAsyncClient(); - +```java readme-sample-encryptAsync byte[] plaintext = new byte[100]; -new Random(0x1234567L).nextBytes(plaintext); +new SecureRandom(SEED).nextBytes(plaintext); // Let's encrypt a simple plain text of size 100 bytes. cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) - .subscribe(encryptionResult -> { - System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", - encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); - }); + .subscribe(encryptionResult -> System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm())); ``` ### Decrypt asynchronously Decrypt encrypted content by calling `decrypt`. -```java +```java readme-sample-decryptAsync byte[] plaintext = new byte[100]; -new Random(0x1234567L).nextBytes(plaintext); +new SecureRandom(SEED).nextBytes(plaintext); // Let's encrypt a simple plain text of size 100 bytes. cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) - .subscribe(encryptionResult -> { + .flatMap(encryptionResult -> { System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); //Let's decrypt the encrypted response. - cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()) - .subscribe(decryptionResult -> - System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length)); - }); + return cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); + }).subscribe(decryptionResult -> + System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length)); ``` ## Troubleshooting ### General Azure Key Vault Key clients raise exceptions. For example, if you try to retrieve a key after it is deleted a `404` error is returned, indicating the resource was not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error. -```java +```java readme-sample-troubleshooting try { - keyClient.getKey("") + keyClient.getKey(""); } catch (ResourceNotFoundException e) { System.out.println(e.getMessage()); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/pom.xml b/sdk/keyvault/azure-security-keyvault-keys/pom.xml index 7ba4be3c105da..3a5b5b27d746b 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-keys/pom.xml @@ -55,6 +55,9 @@ --add-opens com.azure.security.keyvault.keys/com.azure.security.keyvault.keys.cryptography=ALL-UNNAMED --add-opens com.azure.security.keyvault.keys/com.azure.security.keyvault.keys.models=ALL-UNNAMED + false + + diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java index 3b870256af332..adae1c1023132 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java @@ -75,7 +75,14 @@ * soft-delete enabled Azure Key Vault. * *

Samples to construct the async client

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.instantiation} + * + *
+ * KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildAsyncClient();
+ * 
+ * * * @see KeyClientBuilder * @see PagedFlux @@ -228,7 +235,15 @@ String generateKeyId(String keyName, String keyVersion) { *

Code Samples

*

Creates a new {@link KeyVaultKey EC key}. Subscribes to the call asynchronously and prints out the newly * {@link KeyVaultKey created key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.createKey#String-KeyType} + * + *
+     * keyAsyncClient.createKey("keyName", KeyType.EC)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(key ->
+     *         System.out.printf("Created key with name: %s and id: %s %n", key.getName(),
+     *             key.getId()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key} being created. * @param keyType The type of {@link KeyVaultKey key} to create. For valid values, see {@link KeyType KeyType}. @@ -262,7 +277,19 @@ public Mono createKey(String name, KeyType keyType) { *

Creates a new {@link KeyVaultKey EC key}. Subscribes to the call asynchronously and prints out the newly * {@link KeyVaultKey created key} details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.createKeyWithResponse#CreateKeyOptions} + * + *
+     * CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     *
+     * keyAsyncClient.createKeyWithResponse(createKeyOptions)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(createKeyResponse ->
+     *         System.out.printf("Created key with name: %s and: id %s%n", createKeyResponse.getValue().getName(),
+     *             createKeyResponse.getValue().getId()));
+     * 
+ * * * @param createKeyOptions The {@link CreateKeyOptions options object} containing information about the * {@link KeyVaultKey key} being created. @@ -312,7 +339,19 @@ Mono> createKeyWithResponse(String name, KeyType keyType, *

Creates a new {@link KeyVaultKey RSA key} which activates in one day and expires in one year. Subscribes to * the call asynchronously and prints out the newly {@link KeyVaultKey created key} details when a response has been * received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.createKey#CreateKeyOptions} + * + *
+     * CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     *
+     * keyAsyncClient.createKey(createKeyOptions)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(key ->
+     *         System.out.printf("Created key with name: %s and id: %s %n", key.getName(),
+     *             key.getId()));
+     * 
+ * * * @param createKeyOptions The {@link CreateKeyOptions options object} containing information about the * {@link KeyVaultKey key} being created. @@ -370,7 +409,20 @@ Mono> createKeyWithResponse(CreateKeyOptions createKeyOpti *

Creates a new {@link KeyVaultKey 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 {@link KeyVaultKey created key} details when a * response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKey#CreateRsaKeyOptions} + * + *
+     * CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName")
+     *     .setKeySize(2048)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     *
+     * keyAsyncClient.createRsaKey(createRsaKeyOptions)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(rsaKey ->
+     *         System.out.printf("Created key with name: %s and id: %s %n", rsaKey.getName(),
+     *             rsaKey.getId()));
+     * 
+ * * * @param createRsaKeyOptions The {@link CreateRsaKeyOptions options object} containing information about the * {@link KeyVaultKey RSA key} being created. @@ -409,7 +461,20 @@ public Mono createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { *

Creates a new {@link KeyVaultKey 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 {@link KeyVaultKey created key} details when a * response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKeyWithResponse#CreateRsaKeyOptions} + * + *
+     * CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName")
+     *     .setKeySize(2048)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     *
+     * keyAsyncClient.createRsaKeyWithResponse(createRsaKeyOptions)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(createRsaKeyResponse ->
+     *         System.out.printf("Created key with name: %s and: id %s%n", createRsaKeyResponse.getValue().getName(),
+     *             createRsaKeyResponse.getValue().getId()));
+     * 
+ * * * @param createRsaKeyOptions The {@link CreateRsaKeyOptions options object} containing information about the * {@link KeyVaultKey RSA key} being created. @@ -470,7 +535,20 @@ Mono> createRsaKeyWithResponse(CreateRsaKeyOptions createR *

Creates a new {@link KeyVaultKey EC key} with a {@link KeyCurveName#P_384 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 * {@link KeyVaultKey created key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.createEcKey#CreateEcKeyOptions} + * + *
+     * CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName")
+     *     .setCurveName(KeyCurveName.P_384)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     *
+     * keyAsyncClient.createEcKey(createEcKeyOptions)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(ecKey ->
+     *         System.out.printf("Created key with name: %s and id: %s %n", ecKey.getName(),
+     *             ecKey.getId()));
+     * 
+ * * * @param createEcKeyOptions The {@link CreateEcKeyOptions options object} containing information about the * {@link KeyVaultKey EC key} being created. @@ -511,7 +589,20 @@ public Mono createEcKey(CreateEcKeyOptions createEcKeyOptions) { *

Creates a new {@link KeyVaultKey EC key} with a {@link KeyCurveName#P_384 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 * {@link KeyVaultKey created key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.createEcKeyWithResponse#CreateEcKeyOptions} + * + *
+     * CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName")
+     *     .setCurveName(KeyCurveName.P_384)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     *
+     * keyAsyncClient.createEcKeyWithResponse(createEcKeyOptions)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(createEcKeyResponse ->
+     *         System.out.printf("Created key with name: %s and: id %s%n", createEcKeyResponse.getValue().getName(),
+     *             createEcKeyResponse.getValue().getId()));
+     * 
+ * * * @param createEcKeyOptions The {@link CreateEcKeyOptions options object} containing information about the * {@link KeyVaultKey EC key} being created. @@ -568,7 +659,19 @@ Mono> createEcKeyWithResponse(CreateEcKeyOptions createEcK *

Creates a new {@link KeyVaultKey symmetric key}. The {@link KeyVaultKey key} activates in one day and expires * in one year. Subscribes to the call asynchronously and prints out the details of the newly * {@link KeyVaultKey created key} when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.createOctKey#CreateOctKeyOptions} + * + *
+     * CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName")
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     *
+     * keyAsyncClient.createOctKey(createOctKeyOptions)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(octKey ->
+     *         System.out.printf("Created key with name: %s and id: %s %n", octKey.getName(),
+     *             octKey.getId()));
+     * 
+ * * * @param createOctKeyOptions The {@link CreateOctKeyOptions options object} containing information about the * {@link KeyVaultKey symmetric key} being created. @@ -605,7 +708,19 @@ public Mono createOctKey(CreateOctKeyOptions createOctKeyOptions) { *

Creates a new {@link KeyVaultKey symmetric key}. The {@link KeyVaultKey key} activates in one day and expires * in one year. Subscribes to the call asynchronously and prints out the details of the newly * {@link KeyVaultKey created key} when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.createOctKeyWithResponse#CreateOctKeyOptions} + * + *
+     * CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName")
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     *
+     * keyAsyncClient.createOctKeyWithResponse(createOctKeyOptions)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(createOctKeyResponse ->
+     *         System.out.printf("Created key with name: %s and: id %s%n", createOctKeyResponse.getValue().getName(),
+     *             createOctKeyResponse.getValue().getId()));
+     * 
+ * * * @param createOctKeyOptions The {@link CreateOctKeyOptions options object} containing information about the * {@link KeyVaultKey symmetric key} being created. @@ -657,7 +772,14 @@ Mono> createOctKeyWithResponse(CreateOctKeyOptions createO *

Code Samples

*

Imports a new {@link KeyVaultKey key} into key vault. Subscribes to the call asynchronously and prints out the * newly {@link KeyVaultKey imported key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.importKey#String-JsonWebKey} + * + *
+     * keyAsyncClient.importKey("keyName", jsonWebKeyToImport)
+     *     .subscribe(keyVaultKey ->
+     *         System.out.printf("Imported key with name: %s and id: %s%n", keyVaultKey.getName(),
+     *             keyVaultKey.getId()));
+     * 
+ * * * @param name The name for the imported key. * @param keyMaterial The Json web key being imported. @@ -702,7 +824,15 @@ Mono> importKeyWithResponse(String name, JsonWebKey keyMat *

Code Samples

*

Imports a new {@link KeyVaultKey key} into key vault. Subscribes to the call asynchronously and prints out the * newly {@link KeyVaultKey imported key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.importKey#ImportKeyOptions} + * + *
+     * ImportKeyOptions options = new ImportKeyOptions("keyName", jsonWebKeyToImport)
+     *     .setHardwareProtected(false);
+     *
+     * keyAsyncClient.importKey(options).subscribe(keyVaultKey ->
+     *     System.out.printf("Imported key with name: %s and id: %s%n", keyVaultKey.getName(), keyVaultKey.getId()));
+     * 
+ * * * @param importKeyOptions The {@link ImportKeyOptions options object} containing information about the * {@link JsonWebKey} being imported. @@ -738,7 +868,16 @@ public Mono importKey(ImportKeyOptions importKeyOptions) { *

Code Samples

*

Imports a new {@link KeyVaultKey key} into key vault. Subscribes to the call asynchronously and prints out the * newly {@link KeyVaultKey imported key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.importKeyWithResponse#ImportKeyOptions} + * + *
+     * ImportKeyOptions importKeyOptions = new ImportKeyOptions("keyName", jsonWebKeyToImport)
+     *     .setHardwareProtected(false);
+     *
+     * keyAsyncClient.importKeyWithResponse(importKeyOptions).subscribe(response ->
+     *     System.out.printf("Imported key with name: %s and id: %s%n", response.getValue().getName(),
+     *         response.getValue().getId()));
+     * 
+ * * * @param importKeyOptions The {@link ImportKeyOptions options object} containing information about the * {@link JsonWebKey} being imported. @@ -783,7 +922,17 @@ Mono> importKeyWithResponse(ImportKeyOptions importKeyOpti *

Code Samples

*

Gets a specific version of the {@link KeyVaultKey key} in the key vault. Subscribes to the call asynchronously * and prints out the {@link KeyVaultKey retrieved key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String-String} + * + *
+     * String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
+     *
+     * keyAsyncClient.getKey("keyName", keyVersion)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(key ->
+     *         System.out.printf("Created key with name: %s and: id %s%n", key.getName(),
+     *             key.getId()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}. * @param version The version of the key to retrieve. If this is an empty String or null, this call is @@ -812,7 +961,17 @@ public Mono getKey(String name, String version) { *

Code Samples

*

Gets a specific version of the {@link KeyVaultKey key} in the key vault. Subscribes to the call asynchronously * and prints out the {@link KeyVaultKey retrieved key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.getKeyWithResponse#String-String} + * + *
+     * String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
+     *
+     * keyAsyncClient.getKeyWithResponse("keyName", keyVersion)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(getKeyResponse ->
+     *         System.out.printf("Created key with name: %s and: id %s%n",
+     *             getKeyResponse.getValue().getName(), getKeyResponse.getValue().getId()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}. * @param version The version of the key to retrieve. If this is an empty String or null, this call is @@ -851,7 +1010,15 @@ Mono> getKeyWithResponse(String name, String version, Cont *

Code Samples

*

Gets a specific version of the {@link KeyVaultKey key} in the key vault. Subscribes to the call asynchronously * and prints out the {@link KeyVaultKey retrieved key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String} + * + *
+     * keyAsyncClient.getKey("keyName")
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(key ->
+     *         System.out.printf("Created key with name: %s and: id %s%n", key.getName(),
+     *             key.getId()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}. * @@ -884,7 +1051,21 @@ public Mono getKey(String name) { *

Gets latest version of the {@link KeyVaultKey key}, changes its notBefore time and then updates it in the * Azure Key Vault. Subscribes to the call asynchronously and prints out the {@link KeyVaultKey returned key} * details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyPropertiesWithResponse#KeyProperties-KeyOperation} + * + *
+     * keyAsyncClient.getKey("keyName")
+     *     .subscribe(getKeyResponse -> {
+     *         //Update the not before time of the key.
+     *         getKeyResponse.getProperties().setNotBefore(OffsetDateTime.now().plusDays(50));
+     *         keyAsyncClient.updateKeyPropertiesWithResponse(getKeyResponse.getProperties(), KeyOperation.ENCRYPT,
+     *                 KeyOperation.DECRYPT)
+     *             .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *             .subscribe(updateKeyResponse ->
+     *                 System.out.printf("Updated key's \"not before time\": %s%n",
+     *                     updateKeyResponse.getValue().getProperties().getNotBefore().toString()));
+     *     });
+     * 
+ * * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated {@link KeyOperation key operations} to associate with the key. @@ -920,7 +1101,21 @@ public Mono> updateKeyPropertiesWithResponse(KeyProperties *

Gets latest version of the {@link KeyVaultKey key}, changes its notBefore time and then updates it in the * Azure Key Vault. Subscribes to the call asynchronously and prints out the {@link KeyVaultKey returned key} * details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyProperties#KeyProperties-KeyOperation} + * + *
+     * keyAsyncClient.getKey("keyName")
+     *     .subscribe(key -> {
+     *         //Update the not before time of the key.
+     *         key.getProperties().setNotBefore(OffsetDateTime.now().plusDays(50));
+     *         keyAsyncClient.updateKeyProperties(key.getProperties(), KeyOperation.ENCRYPT,
+     *                 KeyOperation.DECRYPT)
+     *             .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *             .subscribe(updatedKey ->
+     *                 System.out.printf("Updated key's \"not before time\": %s%n",
+     *                     updatedKey.getProperties().getNotBefore().toString()));
+     *     });
+     * 
+ * * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated {@link KeyOperation key operations} to associate with the key. @@ -976,7 +1171,16 @@ Mono> updateKeyPropertiesWithResponse(KeyProperties keyPro *

Code Samples

*

Deletes the {@link KeyVaultKey key} in the Azure Key Vault. Subscribes to the call asynchronously and prints * out the {@link KeyVaultKey deleted key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.deleteKey#String} + * + *
+     * keyAsyncClient.beginDeleteKey("keyName")
+     *     .subscribe(pollResponse -> {
+     *         System.out.printf("Deletion status: %s%n", pollResponse.getStatus());
+     *         System.out.printf("Key name: %s%n", pollResponse.getValue().getName());
+     *         System.out.printf("Key delete date: %s%n", pollResponse.getValue().getDeletedOn());
+     *     });
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key} to be deleted. * @@ -1038,7 +1242,14 @@ Mono> deleteKeyWithResponse(String name, Context context) { *

Code Samples

*

Gets the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete. Subscribes to the call * asynchronously and prints out the {@link KeyVaultKey deleted key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKey#String} + * + *
+     * keyAsyncClient.getDeletedKey("keyName")
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(deletedKey ->
+     *         System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()));
+     * 
+ * * * @param name The name of the deleted {@link KeyVaultKey key}. * @@ -1063,7 +1274,14 @@ public Mono getDeletedKey(String name) { *

Code Samples

*

Gets the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete. Subscribes to the call * asynchronously and prints out the {@link KeyVaultKey deleted key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKeyWithResponse#String} + * + *
+     * keyAsyncClient.getDeletedKeyWithResponse("keyName")
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(getDeletedKeyResponse ->
+     *         System.out.printf("Deleted key's recovery id: %s%n", getDeletedKeyResponse.getValue().getRecoveryId()));
+     * 
+ * * * @param name The name of the deleted {@link KeyVaultKey key}. * @@ -1099,7 +1317,13 @@ Mono> getDeletedKeyWithResponse(String name, Context contex *

Code Samples

*

Purges the {@link KeyVaultKey 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.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKey#String} + * + *
+     * keyAsyncClient.purgeDeletedKey("deletedKeyName")
+     *     .subscribe(ignored ->
+     *         System.out.println("Successfully purged deleted key"));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey deleted key}. * @@ -1125,7 +1349,14 @@ public Mono purgeDeletedKey(String name) { *

Code Samples

*

Purges the {@link KeyVaultKey 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.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKeyWithResponse#String} + * + *
+     * keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName")
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(purgeDeletedKeyResponse ->
+     *         System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey deleted key}. * @@ -1161,7 +1392,16 @@ Mono> purgeDeletedKeyWithResponse(String name, Context context) { *

Code Samples

*

Recovers the {@link KeyVaultKey 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.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.recoverDeletedKey#String} + * + *
+     * keyAsyncClient.beginRecoverDeletedKey("deletedKeyName")
+     *     .subscribe(pollResponse -> {
+     *         System.out.printf("Recovery status: %s%n", pollResponse.getStatus());
+     *         System.out.printf("Key name: %s%n", pollResponse.getValue().getName());
+     *         System.out.printf("Key type: %s%n", pollResponse.getValue().getKeyType());
+     *     });
+     * 
+ * * * @param name The name of the {@link KeyVaultKey deleted key} to be recovered. * @@ -1230,7 +1470,14 @@ Mono> recoverDeletedKeyWithResponse(String name, Context c *

Code Samples

*

Backs up the {@link KeyVaultKey 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.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.backupKey#String} + * + *
+     * keyAsyncClient.backupKey("keyName")
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(bytes ->
+     *         System.out.printf("Key backup byte array length: %s%n", bytes.length));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @@ -1264,7 +1511,14 @@ public Mono backupKey(String name) { *

Code Samples

*

Backs up the {@link KeyVaultKey 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.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.backupKeyWithResponse#String} + * + *
+     * keyAsyncClient.backupKeyWithResponse("keyName")
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(backupKeyResponse ->
+     *         System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @@ -1312,7 +1566,15 @@ Mono> backupKeyWithResponse(String name, Context context) { *

Restores the {@link KeyVaultKey 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.

* //Pass the Key Backup Byte array to the restore operation. - * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackup#byte} + * + *
+     * keyAsyncClient.restoreKeyBackup(keyBackupByteArray)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(restoreKeyResponse ->
+     *         System.out.printf("Restored key with name: %s and: id %s%n", restoreKeyResponse.getName(),
+     *             restoreKeyResponse.getId()));
+     * 
+ * * * @param backup The backup blob associated with the {@link KeyVaultKey key}. * @@ -1346,7 +1608,15 @@ public Mono restoreKeyBackup(byte[] backup) { *

Restores the {@link KeyVaultKey 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.

* //Pass the Key Backup Byte array to the restore operation. - * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackupWithResponse#byte} + * + *
+     * keyAsyncClient.restoreKeyBackupWithResponse(keyBackupByteArray)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(restoreKeyBackupResponse ->
+     *         System.out.printf("Restored key with name: %s and: id %s%n",
+     *             restoreKeyBackupResponse.getValue().getName(), restoreKeyBackupResponse.getValue().getId()));
+     * 
+ * * * @param backup The backup blob associated with the {@link KeyVaultKey key}. * @@ -1386,7 +1656,16 @@ Mono> restoreKeyBackupWithResponse(byte[] backup, Context * {@link Flux} containing {@link KeyProperties key properties} to {@link Flux} containing * {@link KeyVaultKey key} using {@link KeyAsyncClient#getKey(String, String)} within * {@link Flux#flatMap(Function)}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.listPropertiesOfKeys} + * + *
+     * keyAsyncClient.listPropertiesOfKeys()
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion()))
+     *     .subscribe(key -> System.out.printf("Retrieved key with name: %s and type: %s%n",
+     *         key.getName(),
+     *         key.getKeyType()));
+     * 
+ * * * @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault. */ @@ -1456,7 +1735,14 @@ private Mono> listKeysFirstPage(Context context) { *

Code Samples

*

Lists the {@link DeletedKey deleted keys} in the key vault. Subscribes to the call asynchronously and prints * out the recovery id of each {@link DeletedKey deleted key} when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.listDeletedKeys} + * + *
+     * keyAsyncClient.listDeletedKeys()
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(deletedKey ->
+     *         System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()));
+     * 
+ * * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ @@ -1527,7 +1813,16 @@ private Mono> listDeletedKeysFirstPage(Context context * {@link Flux} containing {@link KeyProperties key properties} to {@link Flux} containing * {@link KeyVaultKey key } using {@link KeyAsyncClient#getKey(String, String)} within * {@link Flux#flatMap(Function)}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.listKeyVersions} + * + *
+     * keyAsyncClient.listPropertiesOfKeyVersions("keyName")
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion()))
+     *     .subscribe(key ->
+     *         System.out.printf("Retrieved key version: %s with name: %s and type: %s%n",
+     *             key.getProperties().getVersion(), key.getName(), key.getKeyType()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @@ -1596,7 +1891,14 @@ private Mono> listKeyVersionsNextPage(String contin *

Code Samples

*

Gets a number of bytes containing random values from a Managed HSM. Prints out the retrieved bytes in * base64Url format.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytes#int} + * + *
+     * int amount = 16;
+     * keyAsyncClient.getRandomBytes(amount)
+     *     .subscribe(randomBytes ->
+     *         System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes.getBytes())));
+     * 
+ * * * @param count The requested number of random bytes. * @@ -1618,7 +1920,14 @@ public Mono getRandomBytes(int count) { *

Code Samples

*

Gets a number of bytes containing random values from a Managed HSM. Prints out the * {@link Response HTTP Response} details and the retrieved bytes in base64Url format.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytesWithResponse#int} + * + *
+     * int amountOfBytes = 16;
+     * keyAsyncClient.getRandomBytesWithResponse(amountOfBytes).subscribe(response ->
+     *     System.out.printf("Response received successfully with status code: %d. Retrieved %d random bytes: %s%n",
+     *         response.getStatusCode(), amountOfBytes, Arrays.toString(response.getValue().getBytes())));
+     * 
+ * * * @param count The requested number of random bytes. * @@ -1657,7 +1966,14 @@ Mono> getRandomBytesWithResponse(int count, Context contex *

Code Samples

*

Releases a {@link KeyVaultKey key}. Subscribes to the call asynchronously and prints out the signed object * that contains the {@link KeyVaultKey released key} when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String} + * + *
+     * String target = "someAttestationToken";
+     * ReleaseKeyResult releaseKeyResult = keyClient.releaseKey("keyName", target);
+     *
+     * System.out.printf("Signed object containing released key: %s%n", releaseKeyResult);
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key} to release. * @param target The attestation assertion for the target of the {@link KeyVaultKey key} release. @@ -1685,7 +2001,16 @@ public Mono releaseKey(String name, String target) { *

Code Samples

*

Releases a {@link KeyVaultKey key}. Subscribes to the call asynchronously and prints out the signed object * that contains the {@link KeyVaultKey released key} when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String-String} + * + *
+     * String myKeyVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * String myTarget = "someAttestationToken";
+     *
+     * keyAsyncClient.releaseKey("keyName", myKeyVersion, myTarget)
+     *     .subscribe(releaseKeyResult ->
+     *         System.out.printf("Signed object containing released key: %s%n", releaseKeyResult.getValue()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key} to release. * @param version The version of the key to retrieve. If this is empty or {@code null}, this call is equivalent to @@ -1716,7 +2041,21 @@ public Mono releaseKey(String name, String version, String tar *

Releases a {@link KeyVaultKey key}. Subscribes to the call asynchronously and prints out the * {@link Response HTTP Response} details and the signed object that contains the {@link KeyVaultKey released key} * when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions} + * + *
+     * String releaseKeyVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * String releaseTarget = "someAttestationToken";
+     * ReleaseKeyOptions releaseKeyOptions = new ReleaseKeyOptions()
+     *     .setAlgorithm(KeyExportEncryptionAlgorithm.RSA_AES_KEY_WRAP_256)
+     *     .setNonce("someNonce");
+     *
+     * keyAsyncClient.releaseKeyWithResponse("keyName", releaseKeyVersion, releaseTarget, releaseKeyOptions)
+     *     .subscribe(releaseKeyResponse ->
+     *         System.out.printf("Response received successfully with status code: %d. Signed object containing"
+     *                 + "released key: %s%n", releaseKeyResponse.getStatusCode(),
+     *             releaseKeyResponse.getValue().getValue()));
+     * 
+ * * * @param name The name of the key to release. * @param version The version of the key to retrieve. If this is empty or {@code null}, this call is equivalent to @@ -1774,7 +2113,14 @@ Mono> releaseKeyWithResponse(String name, String vers * *

Code Samples

*

Rotates a {@link KeyVaultKey key}. Prints out {@link KeyVaultKey rotated key} details.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.rotateKey#String} + * + *
+     * keyAsyncClient.rotateKey("keyName")
+     *     .subscribe(key ->
+     *         System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(),
+     *             key.getProperties().getVersion()));
+     * 
+ * * * @param name The name of {@link KeyVaultKey key} to be rotated. The system will generate a new version in the * specified {@link KeyVaultKey key}. @@ -1800,7 +2146,15 @@ public Mono rotateKey(String name) { *

Code Samples

*

Rotates a {@link KeyVaultKey key}. Subscribes to the call asynchronously and prints out the * {@link Response HTTP Response} and {@link KeyVaultKey rotated key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.rotateKeyWithResponse#String} + * + *
+     * keyAsyncClient.rotateKeyWithResponse("keyName")
+     *     .subscribe(rotateKeyResponse ->
+     *         System.out.printf("Response received successfully with status code: %d. Rotated key with name: %s and"
+     *                 + "version: %s%n", rotateKeyResponse.getStatusCode(), rotateKeyResponse.getValue().getName(),
+     *             rotateKeyResponse.getValue().getProperties().getVersion()));
+     * 
+ * * * @param name The name of {@link KeyVaultKey key} to be rotated. The system will generate a new version in the * specified {@link KeyVaultKey key}. @@ -1844,7 +2198,13 @@ Mono> rotateKeyWithResponse(String name, Context context) *

Retrieves the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Subscribes to the * call asynchronously and prints out the {@link KeyRotationPolicy rotation policy key} details when a response * has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicy#String} + * + *
+     * keyAsyncClient.getKeyRotationPolicy("keyName")
+     *     .subscribe(keyRotationPolicy ->
+     *         System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @@ -1870,7 +2230,15 @@ public Mono getKeyRotationPolicy(String name) { *

Retrieves the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Subscribes to the * call asynchronously and prints out the {@link Response HTTP Response} and * {@link KeyRotationPolicy rotation policy key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicyWithResponse#String} + * + *
+     * keyAsyncClient.getKeyRotationPolicyWithResponse("keyName")
+     *     .subscribe(getKeyRotationPolicyResponse ->
+     *         System.out.printf("Response received successfully with status code: %d. Retrieved key rotation policy"
+     *             + "with id: %s%n", getKeyRotationPolicyResponse.getStatusCode(),
+     *             getKeyRotationPolicyResponse.getValue().getId()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @@ -1914,7 +2282,26 @@ Mono> getKeyRotationPolicyWithResponse(String name, *

Updates the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Subscribes to the * call asynchronously and prints out the {@link KeyRotationPolicy rotation policy key} details when a response * has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicy#String-KeyRotationPolicyProperties} + * + *
+     * List<KeyRotationLifetimeAction> lifetimeActions = new ArrayList<>();
+     * KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE)
+     *     .setTimeAfterCreate("P90D");
+     * KeyRotationLifetimeAction notifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY)
+     *     .setTimeBeforeExpiry("P45D");
+     *
+     * lifetimeActions.add(rotateLifetimeAction);
+     * lifetimeActions.add(notifyLifetimeAction);
+     *
+     * KeyRotationPolicyProperties policyProperties = new KeyRotationPolicyProperties()
+     *     .setLifetimeActions(lifetimeActions)
+     *     .setExpiryTime("P6M");
+     *
+     * keyAsyncClient.updateKeyRotationPolicy("keyName", policyProperties)
+     *     .subscribe(keyRotationPolicy ->
+     *         System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @param keyRotationPolicyProperties The {@link KeyRotationPolicyProperties} for the key. @@ -1942,7 +2329,28 @@ public Mono updateKeyRotationPolicy(String name, *

Updates the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Subscribes to the * call asynchronously and prints out the {@link Response HTTP Response} and * {@link KeyRotationPolicy rotation policy key} details when a response has been received.

- * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicyProperties} + * + *
+     * List<KeyRotationLifetimeAction> myLifetimeActions = new ArrayList<>();
+     * KeyRotationLifetimeAction myRotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE)
+     *     .setTimeAfterCreate("P90D");
+     * KeyRotationLifetimeAction myNotifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY)
+     *     .setTimeBeforeExpiry("P45D");
+     *
+     * myLifetimeActions.add(myRotateLifetimeAction);
+     * myLifetimeActions.add(myNotifyLifetimeAction);
+     *
+     * KeyRotationPolicyProperties myPolicyProperties = new KeyRotationPolicyProperties()
+     *     .setLifetimeActions(myLifetimeActions)
+     *     .setExpiryTime("P6M");
+     *
+     * keyAsyncClient.updateKeyRotationPolicyWithResponse("keyName", myPolicyProperties)
+     *     .subscribe(updateKeyRotationPolicyResponse ->
+     *         System.out.printf("Response received successfully with status code: %d. Updated key rotation policy"
+     *             + "with id: %s%n", updateKeyRotationPolicyResponse.getStatusCode(),
+     *             updateKeyRotationPolicyResponse.getValue().getId()));
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @param keyRotationPolicyProperties The {@link KeyRotationPolicyProperties} for the key. diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java index aad1ac0c86552..2d855752e8a83 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java @@ -41,7 +41,14 @@ * soft-delete enabled Azure Key Vault. * *

Samples to construct the sync client

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.instantiation} + * + *
+ * KeyClient keyClient = new KeyClientBuilder()
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildClient();
+ * 
+ * * * @see KeyClientBuilder * @see PagedIterable @@ -118,7 +125,13 @@ public CryptographyClient getCryptographyClient(String keyName, String keyVersio * *

Code Samples

*

Creates a new {@link KeyVaultKey EC key}. Prints out the details of the {@link KeyVaultKey created key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.createKey#String-KeyType} + * + *
+     * KeyVaultKey key = keyClient.createKey("keyName", KeyType.EC);
+     *
+     * System.out.printf("Created key with name: %s and id: %s%n", key.getName(), key.getId());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key} being created. * @param keyType The type of {@link KeyVaultKey key} to create. For valid values, see {@link KeyType KeyType}. @@ -151,7 +164,16 @@ public KeyVaultKey createKey(String name, KeyType keyType) { *

Code Samples

*

Creates a new {@link KeyVaultKey RSA key} which activates in one day and expires in one year. Prints out the * details of the {@link KeyVaultKey created key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.createKey#CreateKeyOptions} + * + *
+     * CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     * KeyVaultKey optionsKey = keyClient.createKey(createKeyOptions);
+     *
+     * System.out.printf("Created key with name: %s and id: %s%n", optionsKey.getName(), optionsKey.getId());
+     * 
+ * * * @param createKeyOptions The {@link CreateKeyOptions options object} containing information about the * {@link KeyVaultKey key} being created. @@ -185,7 +207,18 @@ public KeyVaultKey createKey(CreateKeyOptions createKeyOptions) { *

Code Samples

*

Creates a new {@link KeyVaultKey RSA key} which activates in one day and expires in one year. Prints out the * details of the {@link KeyVaultKey created key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.createKeyWithResponse#CreateKeyOptions-Context} + * + *
+     * CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     * Response<KeyVaultKey> createKeyResponse =
+     *     keyClient.createKeyWithResponse(createKeyOptions, new Context("key1", "value1"));
+     *
+     * System.out.printf("Created key with name: %s and: id %s%n", createKeyResponse.getValue().getName(),
+     *     createKeyResponse.getValue().getId());
+     * 
+ * * * @param createKeyOptions The {@link CreateKeyOptions options object} containing information about the * {@link KeyVaultKey key} being created. @@ -221,7 +254,17 @@ public Response createKeyWithResponse(CreateKeyOptions createKeyOpt *

Code Samples

*

Creates a new {@link KeyVaultKey RSA key} with size 2048 which activates in one day and expires in one year. * Prints out the details of the {@link KeyVaultKey created key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.createRsaKey#CreateRsaKeyOptions} + * + *
+     * CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName")
+     *     .setKeySize(2048)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     * KeyVaultKey rsaKey = keyClient.createRsaKey(createRsaKeyOptions);
+     *
+     * System.out.printf("Created key with name: %s and id: %s%n", rsaKey.getName(), rsaKey.getId());
+     * 
+ * * * @param createRsaKeyOptions The {@link CreateRsaKeyOptions options object} containing information about the * {@link KeyVaultKey RSA key} being created. @@ -255,7 +298,19 @@ public KeyVaultKey createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) { *

Code Samples

*

Creates a new {@link KeyVaultKey RSA key} with size 2048 which activates in one day and expires in one year. * Prints out the details of the {@link KeyVaultKey created key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.createRsaKeyWithResponse#CreateRsaKeyOptions-Context} + * + *
+     * CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName")
+     *     .setKeySize(2048)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     * Response<KeyVaultKey> createRsaKeyResponse =
+     *     keyClient.createRsaKeyWithResponse(createRsaKeyOptions, new Context("key1", "value1"));
+     *
+     * System.out.printf("Created key with name: %s and: id %s%n", createRsaKeyResponse.getValue().getName(),
+     *     createRsaKeyResponse.getValue().getId());
+     * 
+ * * * @param createRsaKeyOptions The {@link CreateRsaKeyOptions options object} containing information about the * {@link KeyVaultKey RSA key} being created. @@ -292,7 +347,17 @@ public Response createRsaKeyWithResponse(CreateRsaKeyOptions create *

Code Samples

*

Creates a new {@link KeyVaultKey EC key} with a {@link KeyCurveName#P_384 P-384} web key curve. The key * activates in one day and expires in one year. Prints out the details of the {@link KeyVaultKey created key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.createEcKey#CreateOctKeyOptions} + * + *
+     * CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName")
+     *     .setCurveName(KeyCurveName.P_384)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     * KeyVaultKey ecKey = keyClient.createEcKey(createEcKeyOptions);
+     *
+     * System.out.printf("Created key with name: %s and id: %s%n", ecKey.getName(), ecKey.getId());
+     * 
+ * * * @param createEcKeyOptions The {@link CreateEcKeyOptions options object} containing information about the * {@link KeyVaultKey EC key} being created. @@ -328,7 +393,19 @@ public KeyVaultKey createEcKey(CreateEcKeyOptions createEcKeyOptions) { *

Code Samples

*

Creates a new {@link KeyVaultKey EC key} with a {@link KeyCurveName#P_384 P-384} web key curve. The key * activates in one day and expires in one year. Prints out the details of the {@link KeyVaultKey created key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.createEcKeyWithResponse#CreateEcKeyOptions-Context} + * + *
+     * CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName")
+     *     .setCurveName(KeyCurveName.P_384)
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     * Response<KeyVaultKey> createEcKeyResponse =
+     *     keyClient.createEcKeyWithResponse(createEcKeyOptions, new Context("key1", "value1"));
+     *
+     * System.out.printf("Created key with name: %s and: id %s%n", createEcKeyResponse.getValue().getName(),
+     *     createEcKeyResponse.getValue().getId());
+     * 
+ * * * @param createEcKeyOptions The {@link CreateEcKeyOptions options object} containing information about the * {@link KeyVaultKey EC key} being created. @@ -362,7 +439,16 @@ public Response createEcKeyWithResponse(CreateEcKeyOptions createEc *

Code Samples

*

Creates a new {@link KeyVaultKey symmetric key}. The {@link KeyVaultKey key} activates in one day and expires * in one year. Prints out the details of the newly {@link KeyVaultKey created key}.

- * {@codesnippet com.azure.security.keyvault.keys.async.KeyClient.createOctKey#CreateOctKeyOptions} + * + *
+     * CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName")
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     * KeyVaultKey octKey = keyClient.createOctKey(createOctKeyOptions);
+     *
+     * System.out.printf("Created key with name: %s and id: %s%n", octKey.getName(), octKey.getId());
+     * 
+ * * * @param createOctKeyOptions The {@link CreateOctKeyOptions options object} containing information about the * {@link KeyVaultKey symmetric key} being created. @@ -394,7 +480,18 @@ public KeyVaultKey createOctKey(CreateOctKeyOptions createOctKeyOptions) { *

Code Samples

*

Creates a new {@link KeyVaultKey symmetric key}. The {@link KeyVaultKey key} activates in one day and expires * in one year. Prints out the details of the newly {@link KeyVaultKey created key}.

- * {@codesnippet com.azure.security.keyvault.keys.async.KeyClient.createOctKey#CreateOctKeyOptions-Context} + * + *
+     * CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName")
+     *     .setNotBefore(OffsetDateTime.now().plusDays(1))
+     *     .setExpiresOn(OffsetDateTime.now().plusYears(1));
+     * Response<KeyVaultKey> createOctKeyResponse =
+     *     keyClient.createOctKeyWithResponse(createOctKeyOptions, new Context("key1", "value1"));
+     *
+     * System.out.printf("Created key with name: %s and: id %s%n", createOctKeyResponse.getValue().getName(),
+     *     createOctKeyResponse.getValue().getId());
+     * 
+ * * * @param createOctKeyOptions The {@link CreateOctKeyOptions options object} containing information about the * {@link KeyVaultKey symmetric key} being created. @@ -421,7 +518,13 @@ public Response createOctKeyWithResponse(CreateOctKeyOptions create *

Code Samples

*

Imports a new {@link KeyVaultKey key} into the key vault. Prints out the details of the * {@link KeyVaultKey imported key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.importKey#String-JsonWebKey} + * + *
+     * KeyVaultKey key = keyClient.importKey("keyName", jsonWebKeyToImport);
+     *
+     * System.out.printf("Imported key with name: %s and id: %s%n", key.getName(), key.getId());
+     * 
+ * * * @param name The name for the {@link KeyVaultKey imported key}. * @param keyMaterial The {@link JsonWebKey} being imported. @@ -452,7 +555,16 @@ public KeyVaultKey importKey(String name, JsonWebKey keyMaterial) { *

Code Samples

*

Imports a new {@link KeyVaultKey key} into the key vault. Prints out the details of the * {@link KeyVaultKey imported key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.importKey#ImportKeyOptions} + * + *
+     * ImportKeyOptions options = new ImportKeyOptions("keyName", jsonWebKeyToImport)
+     *     .setHardwareProtected(false);
+     * KeyVaultKey importedKey = keyClient.importKey(options);
+     *
+     * System.out.printf("Imported key with name: %s and id: %s%n", importedKey.getName(),
+     *     importedKey.getId());
+     * 
+ * * * @param importKeyOptions The {@link ImportKeyOptions options object} containing information about the * {@link JsonWebKey} being imported. @@ -484,7 +596,17 @@ public KeyVaultKey importKey(ImportKeyOptions importKeyOptions) { *

Code Samples

*

Imports a new {@link KeyVaultKey key} into the key vault. Prints out the details of the * {@link KeyVaultKey imported key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.importKeyWithResponse#ImportKeyOptions-Context} + * + *
+     * ImportKeyOptions importKeyOptions = new ImportKeyOptions("keyName", jsonWebKeyToImport)
+     *     .setHardwareProtected(false);
+     * Response<KeyVaultKey> response =
+     *     keyClient.importKeyWithResponse(importKeyOptions, new Context("key1", "value1"));
+     *
+     * System.out.printf("Imported key with name: %s and id: %s%n", response.getValue().getName(),
+     *     response.getValue().getId());
+     * 
+ * * * @param importKeyOptions The {@link ImportKeyOptions options object} containing information about the * {@link JsonWebKey} being imported. @@ -508,7 +630,15 @@ public Response importKeyWithResponse(ImportKeyOptions importKeyOpt *

Code Samples

*

Gets a specific version of the {@link KeyVaultKey key} in the key vault. Prints out the details of the * {@link KeyVaultKey retrieved key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.getKey#String-String} + * + *
+     * String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * KeyVaultKey keyWithVersion = keyClient.getKey("keyName", keyVersion);
+     *
+     * System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersion.getName(),
+     *     keyWithVersion.getId());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}. * @param version The version of the {@link KeyVaultKey key} to retrieve. If this is an empty string or @@ -534,7 +664,16 @@ public KeyVaultKey getKey(String name, String version) { *

Code Samples

*

Gets a specific version of the {@link KeyVaultKey key} in the key vault. Prints out the details of the * {@link KeyVaultKey retrieved key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.getKeyWithResponse#String-String-Context} + * + *
+     * String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * Response<KeyVaultKey> getKeyResponse =
+     *     keyClient.getKeyWithResponse("keyName", keyVersion, new Context("key1", "value1"));
+     *
+     * System.out.printf("Retrieved key with name: %s and: id %s%n", getKeyResponse.getValue().getName(),
+     *     getKeyResponse.getValue().getId());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service @@ -563,7 +702,14 @@ public Response getKeyWithResponse(String name, String version, Con *

Code Samples

*

Gets a specific version of the {@link KeyVaultKey key} in the key vault. Prints out the details of the * {@link KeyVaultKey retrieved key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.getKey#String} + * + *
+     * KeyVaultKey keyWithVersionValue = keyClient.getKey("keyName");
+     *
+     * System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersionValue.getName(),
+     *     keyWithVersionValue.getId());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}, cannot be {@code null}. * @@ -590,7 +736,18 @@ public KeyVaultKey getKey(String name) { *

Code Samples

*

Gets the latest version of the {@link KeyVaultKey key}, changes its expiry time and * {@link KeyOperation key operations} and the updates the {@link KeyVaultKey key} in the key vault.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.updateKeyProperties#KeyProperties-KeyOperation} + * + *
+     * KeyVaultKey key = keyClient.getKey("keyName");
+     *
+     * key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(60));
+     *
+     * KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties(), KeyOperation.ENCRYPT,
+     *     KeyOperation.DECRYPT);
+     *
+     * System.out.printf("Key is updated with name %s and id %s %n", updatedKey.getName(), updatedKey.getId());
+     * 
+ * * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param keyOperations The updated {@link KeyOperation key operations} to associate with the key. @@ -620,7 +777,20 @@ public KeyVaultKey updateKeyProperties(KeyProperties keyProperties, KeyOperation *

Code Samples

*

Gets the latest version of the {@link KeyVaultKey key}, changes its expiry time and * {@link KeyOperation key operations} and the updates the {@link KeyVaultKey key} in the key vault.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.updateKeyPropertiesWithResponse#KeyProperties-Context-KeyOperation} + * + *
+     * KeyVaultKey key = keyClient.getKey("keyName");
+     *
+     * key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(60));
+     *
+     * Response<KeyVaultKey> updateKeyResponse =
+     *     keyClient.updateKeyPropertiesWithResponse(key.getProperties(), new Context("key1", "value1"),
+     *         KeyOperation.ENCRYPT, KeyOperation.DECRYPT);
+     *
+     * System.out.printf("Updated key with name: %s and id: %s%n", updateKeyResponse.getValue().getName(),
+     *     updateKeyResponse.getValue().getId());
+     * 
+ * * * @param keyProperties The {@link KeyProperties key properties} object with updated properties. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service @@ -654,7 +824,22 @@ public Response updateKeyPropertiesWithResponse(KeyProperties keyPr *

Code Samples

*

Deletes the {@link KeyVaultKey key} from the key vault. Prints out the recovery id of the * {@link KeyVaultKey deleted key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.deleteKey#String} + * + *
+     * SyncPoller<DeletedKey, Void> deleteKeyPoller = keyClient.beginDeleteKey("keyName");
+     * PollResponse<DeletedKey> deleteKeyPollResponse = deleteKeyPoller.poll();
+     *
+     * // Deleted date only works for SoftDelete Enabled Key Vault.
+     * DeletedKey deletedKey = deleteKeyPollResponse.getValue();
+     *
+     * System.out.printf("Key delete date: %s%n" + deletedKey.getDeletedOn());
+     * System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId());
+     *
+     * // Key is being deleted on server.
+     * deleteKeyPoller.waitForCompletion();
+     * // Key is deleted
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key} to be deleted. * @@ -675,7 +860,13 @@ public SyncPoller beginDeleteKey(String name) { *

Code Samples

*

Gets the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete. Prints out the details * of the {@link KeyVaultKey deleted key}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.getDeletedKey#String} + * + *
+     * DeletedKey deletedKey = keyClient.getDeletedKey("keyName");
+     *
+     * System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId());
+     * 
+ * * * @param name The name of the deleted {@link KeyVaultKey key}. * @@ -696,7 +887,14 @@ public DeletedKey getDeletedKey(String name) { *

Code Samples

*

Gets the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete. Prints out the details * of the {@link KeyVaultKey deleted key} returned in the {@link Response HTTPresponse}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.getDeletedKeyWithResponse#String-Context} + * + *
+     * Response<DeletedKey> deletedKeyResponse =
+     *     keyClient.getDeletedKeyWithResponse("keyName", new Context("key1", "value1"));
+     *
+     * System.out.printf("Deleted key with recovery id: %s%n", deletedKeyResponse.getValue().getRecoveryId());
+     * 
+ * * * @param name The name of the deleted {@link KeyVaultKey key}. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service @@ -719,7 +917,11 @@ public Response getDeletedKeyWithResponse(String name, Context conte * *

Code Samples

*

Purges the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.purgeDeletedKey#String} + * + *
+     * keyClient.purgeDeletedKey("deletedKeyName");
+     * 
+ * * * @param name The name of the {@link KeyVaultKey deleted key}. * @@ -738,7 +940,14 @@ public void purgeDeletedKey(String name) { * *

Code Samples

*

Purges the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.purgeDeletedKeyWithResponse#String-Context} + * + *
+     * Response<Void> purgeDeletedKeyResponse = keyClient.purgeDeletedKeyWithResponse("deletedKeyName",
+     *     new Context("key1", "value1"));
+     *
+     * System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey deleted key}. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service @@ -762,7 +971,21 @@ public Response purgeDeletedKeyWithResponse(String name, Context context) * *

Code Samples

*

Recovers the {@link KeyVaultKey deleted key} from the key vault enabled for soft-delete.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.recoverDeletedKey#String} + * + *
+     * SyncPoller<KeyVaultKey, Void> recoverKeyPoller = keyClient.beginRecoverDeletedKey("deletedKeyName");
+     *
+     * PollResponse<KeyVaultKey> recoverKeyPollResponse = recoverKeyPoller.poll();
+     *
+     * KeyVaultKey recoveredKey = recoverKeyPollResponse.getValue();
+     * System.out.printf("Recovered key name: %s%n", recoveredKey.getName());
+     * System.out.printf("Recovered key id: %s%n", recoveredKey.getId());
+     *
+     * // Key is being recovered on server.
+     * recoverKeyPoller.waitForCompletion();
+     * // Key is recovered
+     * 
+ * * * @param name The name of the {@link KeyVaultKey deleted key} to be recovered. * @@ -791,7 +1014,13 @@ public SyncPoller beginRecoverDeletedKey(String name) { * *

Code Samples

*

Backs up the {@link KeyVaultKey key} from the key vault.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.backupKey#String} + * + *
+     * byte[] keyBackup = keyClient.backupKey("keyName");
+     *
+     * System.out.printf("Key backup byte array length: %s%n", keyBackup.length);
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @@ -821,7 +1050,13 @@ public byte[] backupKey(String name) { *

Code Samples

*

Backs up the {@link KeyVaultKey key} from the key vault and prints out the length of the key's backup byte * array returned in the {@link Response HTTPresponse}.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.backupKeyWithResponse#String-Context} + * + *
+     * Response<byte[]> backupKeyResponse = keyClient.backupKeyWithResponse("keyName", new Context("key1", "value1"));
+     *
+     * System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length);
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service @@ -853,7 +1088,13 @@ public Response backupKeyWithResponse(String name, Context context) { *

Code Samples

*

Restores the {@link KeyVaultKey key} in the key vault from its backup.

* // Pass the key backup byte array to the restore operation. - * {@codesnippet com.azure.security.keyvault.keys.KeyClient.restoreKeyBackup#byte} + * + *
+     * byte[] keyBackupByteArray = {};
+     * KeyVaultKey keyResponse = keyClient.restoreKeyBackup(keyBackupByteArray);
+     * System.out.printf("Restored key with name: %s and: id %s%n", keyResponse.getName(), keyResponse.getId());
+     * 
+ * * * @param backup The backup blob associated with the {@link KeyVaultKey key}. * @@ -883,7 +1124,15 @@ public KeyVaultKey restoreKeyBackup(byte[] backup) { *

Restores the {@link KeyVaultKey key} in the key vault from its backup. Prints out the details of the * {@link KeyVaultKey restored key} returned in the {@link Response HTTPresponse}.

* // Pass the key backup byte array to the restore operation. - * {@codesnippet com.azure.security.keyvault.keys.KeyClient.restoreKeyBackupWithResponse#byte-Context} + * + *
+     * Response<KeyVaultKey> keyResponse = keyClient.restoreKeyBackupWithResponse(keyBackupByteArray,
+     *     new Context("key1", "value1"));
+     *
+     * System.out.printf("Restored key with name: %s and: id %s%n",
+     *     keyResponse.getValue().getName(), keyResponse.getValue().getId());
+     * 
+ * * * @param backup The backup blob associated with the {@link KeyVaultKey key}. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service @@ -909,13 +1158,34 @@ public Response restoreKeyBackupWithResponse(byte[] backup, Context *

It is possible to get {@link KeyVaultKey full keys} with key material from this information. Loop over the * {@link KeyProperties} and call {@link KeyClient#getKey(String, String)}. This will return the * {@link KeyVaultKey key} with key material included as of its latest version.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys} + * + *
+     * for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) {
+     *     KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion());
+     *
+     *     System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), key.getKeyType());
+     * }
+     * 
+ * * *

Code Samples to iterate keys by page

*

It is possible to get {@link KeyVaultKey full keys} with key material from this information. Iterate over all * the {@link KeyProperties} by page and call {@link KeyClient#getKey(String, String)}. This will return the * {@link KeyVaultKey key} with key material included as of its latest version.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys.iterableByPage} + * + *
+     * keyClient.listPropertiesOfKeys().iterableByPage().forEach(pagedResponse -> {
+     *     System.out.printf("Got response details. Url: %s. Status code: %d.%n",
+     *         pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode());
+     *     pagedResponse.getElements().forEach(keyProperties -> {
+     *         KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion());
+     *
+     *         System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(),
+     *             key.getKeyType());
+     *     });
+     * });
+     * 
+ * * * @return {@link PagedIterable} of {@link KeyProperties key} of all the {@link KeyVaultKey keys} in the vault. */ @@ -935,13 +1205,35 @@ public PagedIterable listPropertiesOfKeys() { *

It is possible to get {@link KeyVaultKey full keys} with key material from this information. Loop over the * {@link KeyProperties} and call {@link KeyClient#getKey(String, String)}. This will return the * {@link KeyVaultKey key} with key material included as of its latest version.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys#Context} + * + *
+     * for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys(new Context("key1", "value1"))) {
+     *     KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion());
+     *
+     *     System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(),
+     *         key.getKeyType());
+     * }
+     * 
+ * * *

Code Samples to iterate keys by page

*

It is possible to get {@link KeyVaultKey full keys} with key material from this information. Iterate over all * the {@link KeyProperties} by page and call {@link KeyClient#getKey(String, String)}. This will return the * {@link KeyVaultKey key} with key material included as of its latest version.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys.iterableByPage} + * + *
+     * keyClient.listPropertiesOfKeys().iterableByPage().forEach(pagedResponse -> {
+     *     System.out.printf("Got response details. Url: %s. Status code: %d.%n",
+     *         pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode());
+     *     pagedResponse.getElements().forEach(keyProperties -> {
+     *         KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion());
+     *
+     *         System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(),
+     *             key.getKeyType());
+     *     });
+     * });
+     * 
+ * * * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service * call. @@ -962,12 +1254,27 @@ public PagedIterable listPropertiesOfKeys(Context context) { *

Code Samples

*

Lists the {@link DeletedKey deleted keys} in the key vault and for each {@link DeletedKey deleted key} prints * out its recovery id.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listDeletedKeys} + * + *
+     * for (DeletedKey deletedKey : keyClient.listDeletedKeys()) {
+     *     System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId());
+     * }
+     * 
+ * * *

Code Samples to iterate over deleted keys by page

*

Iterates over the {@link DeletedKey deleted keys} by page in the key vault and for each deleted key prints out * its recovery id.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listDeletedKeys.iterableByPage} + * + *
+     * keyClient.listDeletedKeys().iterableByPage().forEach(pagedResponse -> {
+     *     System.out.printf("Got response details. Url: %s. Status code: %d.%n",
+     *         pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode());
+     *     pagedResponse.getElements().forEach(deletedKey ->
+     *         System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()));
+     * });
+     * 
+ * * * @return {@link PagedIterable} of all of the {@link DeletedKey deleted keys} in the vault. */ @@ -985,12 +1292,27 @@ public PagedIterable listDeletedKeys() { *

Code Samples

*

Lists the {@link DeletedKey deleted keys} in the key vault and for each {@link DeletedKey deleted key} prints * out its recovery id.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listDeletedKeys#Context} + * + *
+     * for (DeletedKey deletedKey : keyClient.listDeletedKeys(new Context("key1", "value1"))) {
+     *     System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId());
+     * }
+     * 
+ * * *

Code Samples to iterate over deleted keys by page

*

Iterates over the {@link DeletedKey deleted keys} by page in the key vault and for each deleted key prints out * its recovery id.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listDeletedKeys.iterableByPage} + * + *
+     * keyClient.listDeletedKeys().iterableByPage().forEach(pagedResponse -> {
+     *     System.out.printf("Got response details. Url: %s. Status code: %d.%n",
+     *         pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode());
+     *     pagedResponse.getElements().forEach(deletedKey ->
+     *         System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()));
+     * });
+     * 
+ * * * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service * call. @@ -1011,13 +1333,32 @@ public PagedIterable listDeletedKeys(Context context) { *

It is possible to get {@link KeyVaultKey full keys} with key material for each version from this information. * Loop over the {@link KeyProperties key} and call {@link KeyClient#getKey(String, String)}. This will return the * {@link KeyVaultKey keys} with key material included of the specified versions.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String} + * + *
+     * for (KeyProperties keyProperties : keyClient.listPropertiesOfKeyVersions("keyName")) {
+     *     KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion());
+     *
+     *     System.out.printf("Retrieved key version: %s with name: %s and type: %s%n",
+     *         key.getProperties().getVersion(), key.getName(), key.getKeyType());
+     * }
+     * 
+ * * *

Code Samples to iterate over key versions by page

*

It is possible to get {@link KeyVaultKey full keys} with key material for each version from this information. * Iterate over all the {@link KeyProperties key} by page and call {@link KeyClient#getKey(String, String)}. This * will return the {@link KeyVaultKey keys} with key material included of the specified versions.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions.iterableByPage} + * + *
+     * keyClient.listPropertiesOfKeyVersions("keyName").iterableByPage().forEach(pagedResponse -> {
+     *     System.out.printf("Got response details. Url: %s. Status code: %d.%n",
+     *         pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode());
+     *     pagedResponse.getElements().forEach(keyProperties ->
+     *         System.out.printf("Key name: %s. Key version: %s.%n", keyProperties.getName(),
+     *             keyProperties.getVersion()));
+     * });
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @@ -1040,13 +1381,32 @@ public PagedIterable listPropertiesOfKeyVersions(String name) { *

It is possible to get {@link KeyVaultKey full keys} with key material for each version from this information. * Loop over the {@link KeyProperties key} and call {@link KeyClient#getKey(String, String)}. This will return the * {@link KeyVaultKey keys} with key material included of the specified versions.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String-Context} + * + *
+     * for (KeyProperties keyProperties : keyClient.listPropertiesOfKeyVersions("keyName", new Context("key1", "value1"))) {
+     *     KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion());
+     *
+     *     System.out.printf("Retrieved key version: %s with name: %s and type: %s%n",
+     *         key.getProperties().getVersion(), key.getName(), key.getKeyType());
+     * }
+     * 
+ * * *

Code Samples to iterate over key versions by page

*

It is possible to get {@link KeyVaultKey full keys} with key material for each version from this information. * Iterate over all the {@link KeyProperties key} by page and call {@link KeyClient#getKey(String, String)}. This * will return the {@link KeyVaultKey keys} with key material included of the specified versions.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions.iterableByPage} + * + *
+     * keyClient.listPropertiesOfKeyVersions("keyName").iterableByPage().forEach(pagedResponse -> {
+     *     System.out.printf("Got response details. Url: %s. Status code: %d.%n",
+     *         pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode());
+     *     pagedResponse.getElements().forEach(keyProperties ->
+     *         System.out.printf("Key name: %s. Key version: %s.%n", keyProperties.getName(),
+     *             keyProperties.getVersion()));
+     * });
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service @@ -1069,7 +1429,14 @@ public PagedIterable listPropertiesOfKeyVersions(String name, Con *

Code Samples

*

Gets a number of bytes containing random values from a Managed HSM. Prints out the retrieved bytes in * base64Url format.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.getRandomBytes#int} + * + *
+     * int amount = 16;
+     * RandomBytes randomBytes = keyClient.getRandomBytes(amount);
+     *
+     * System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes.getBytes()));
+     * 
+ * * * @param count The requested number of random bytes. * @@ -1085,7 +1452,16 @@ public RandomBytes getRandomBytes(int count) { *

Code Samples

*

Gets a number of bytes containing random values from a Managed HSM. Prints out the * {@link Response HTTP Response} details and the retrieved bytes in base64Url format.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.getRandomBytesWithResponse#int-Context} + * + *
+     * int amountOfBytes = 16;
+     * Response<RandomBytes> response =
+     *     keyClient.getRandomBytesWithResponse(amountOfBytes, new Context("key1", "value1"));
+     *
+     * System.out.printf("Response received successfully with status code: %d. Retrieved %d random bytes: %s%n",
+     *     response.getStatusCode(), amountOfBytes, Arrays.toString(response.getValue().getBytes()));
+     * 
+ * * * @param count The requested number of random bytes. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service @@ -1106,7 +1482,14 @@ public Response getRandomBytesWithResponse(int count, Context conte * *

Code Samples

*

Releases a {@link KeyVaultKey key}. Prints out the signed object that contains the release key.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String} + * + *
+     * String target = "someAttestationToken";
+     * ReleaseKeyResult releaseKeyResult = keyClient.releaseKey("keyName", target);
+     *
+     * System.out.printf("Signed object containing released key: %s%n", releaseKeyResult);
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key} to release. * @param target The attestation assertion for the target of the {@link KeyVaultKey key} release. @@ -1129,7 +1512,15 @@ public ReleaseKeyResult releaseKey(String name, String target) { * *

Code Samples

*

Releases a {@link KeyVaultKey key}. Prints out the signed object that contains the release key.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String-String} + * + *
+     * String myKeyVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * String myTarget = "someAttestationToken";
+     * ReleaseKeyResult releaseKeyVersionResult = keyClient.releaseKey("keyName", myKeyVersion, myTarget);
+     *
+     * System.out.printf("Signed object containing released key: %s%n", releaseKeyVersionResult);
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key} to release. * @param version The version of the key to release. If this is empty or {@code null}, this call is equivalent to @@ -1154,7 +1545,23 @@ public ReleaseKeyResult releaseKey(String name, String version, String target) { *

Code Samples

*

Releases a {@link KeyVaultKey key}. Prints out the * {@link Response HTTP Response} details and the signed object that contains the release key.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions-Context} + * + *
+     * String releaseKeyVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * String releaseTarget = "someAttestationToken";
+     * ReleaseKeyOptions releaseKeyOptions = new ReleaseKeyOptions()
+     *     .setAlgorithm(KeyExportEncryptionAlgorithm.RSA_AES_KEY_WRAP_256)
+     *     .setNonce("someNonce");
+     *
+     * Response<ReleaseKeyResult> releaseKeyResultResponse =
+     *     keyClient.releaseKeyWithResponse("keyName", releaseKeyVersion, releaseTarget, releaseKeyOptions,
+     *         new Context("key1", "value1"));
+     *
+     * System.out.printf("Response received successfully with status code: %d. Signed object containing"
+     *         + "released key: %s%n", releaseKeyResultResponse.getStatusCode(),
+     *     releaseKeyResultResponse.getValue().getValue());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key} to release. * @param version The version of the {@link KeyVaultKey key} to release. If this is empty or {@code null}, this call @@ -1183,7 +1590,14 @@ public Response releaseKeyWithResponse(String name, String ver * *

Code Samples

*

Rotates a {@link KeyVaultKey key}. Prints out {@link KeyVaultKey rotated key} details.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String} + * + *
+     * KeyVaultKey key = keyClient.rotateKey("keyName");
+     *
+     * System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(),
+     *     key.getProperties().getVersion());
+     * 
+ * * * @param name The name of {@link KeyVaultKey key} to be rotated. The system will generate a new version in the * specified {@link KeyVaultKey key}. @@ -1205,7 +1619,15 @@ public KeyVaultKey rotateKey(String name) { *

Code Samples

*

Rotates a {@link KeyVaultKey key}. Prints out the {@link Response HTTP Response} and * {@link KeyVaultKey rotated key} details.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String-Context} + * + *
+     * Response<KeyVaultKey> keyResponse = keyClient.rotateKeyWithResponse("keyName", new Context("key1", "value1"));
+     *
+     * System.out.printf("Response received successfully with status code: %d. Rotated key with name: %s and"
+     *         + "version: %s%n", keyResponse.getStatusCode(), keyResponse.getValue().getName(),
+     *     keyResponse.getValue().getProperties().getVersion());
+     * 
+ * * * @param name The name of {@link KeyVaultKey key} to be rotated. The system will generate a new version in the * specified {@link KeyVaultKey key}. @@ -1230,7 +1652,13 @@ public Response rotateKeyWithResponse(String name, Context context) *

Code Samples

*

Retrieves the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Prints out the * {@link KeyRotationPolicy rotation policy key} details.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicy#String} + * + *
+     * KeyRotationPolicy keyRotationPolicy = keyClient.getKeyRotationPolicy("keyName");
+     *
+     * System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @@ -1251,7 +1679,15 @@ public KeyRotationPolicy getKeyRotationPolicy(String name) { *

Code Samples

*

Retrieves the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Prints out the * {@link Response HTTP Response} and {@link KeyRotationPolicy rotation policy key} details.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicyWithResponse#String-Context} + * + *
+     * Response<KeyRotationPolicy> keyRotationPolicyResponse =
+     *     keyClient.getKeyRotationPolicyWithResponse("keyName", new Context("key1", "value1"));
+     *
+     * System.out.printf("Response received successfully with status code: %d. Retrieved key rotation policy"
+     *     + "with id: %s%n", keyRotationPolicyResponse.getStatusCode(), keyRotationPolicyResponse.getValue().getId());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service @@ -1275,7 +1711,27 @@ public Response getKeyRotationPolicyWithResponse(String name, *

Code Samples

*

Updates the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Prints out the * {@link KeyRotationPolicy rotation policy key} details.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicy#String-KeyRotationPolicyProperties} + * + *
+     * List<KeyRotationLifetimeAction> lifetimeActions = new ArrayList<>();
+     * KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE)
+     *     .setTimeAfterCreate("P90D");
+     * KeyRotationLifetimeAction notifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY)
+     *     .setTimeBeforeExpiry("P45D");
+     *
+     * lifetimeActions.add(rotateLifetimeAction);
+     * lifetimeActions.add(notifyLifetimeAction);
+     *
+     * KeyRotationPolicyProperties policyProperties = new KeyRotationPolicyProperties()
+     *     .setLifetimeActions(lifetimeActions)
+     *     .setExpiryTime("P6M");
+     *
+     * KeyRotationPolicy keyRotationPolicy =
+     *     keyClient.updateKeyRotationPolicy("keyName", policyProperties);
+     *
+     * System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @param keyRotationPolicyProperties The {@link KeyRotationPolicy} for the ke{@link KeyVaultKey key}y. @@ -1297,7 +1753,28 @@ public KeyRotationPolicy updateKeyRotationPolicy(String name, KeyRotationPolicyP *

Code Samples

*

Updates the {@link KeyRotationPolicy rotation policy} of a given {@link KeyVaultKey key}. Prints out the * {@link Response HTTP Response} and {@link KeyRotationPolicy rotation policy key} details.

- * {@codesnippet com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicyProperties-Context} + * + *
+     * List<KeyRotationLifetimeAction> myLifetimeActions = new ArrayList<>();
+     * KeyRotationLifetimeAction myRotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE)
+     *     .setTimeAfterCreate("P90D");
+     * KeyRotationLifetimeAction myNotifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY)
+     *     .setTimeBeforeExpiry("P45D");
+     *
+     * myLifetimeActions.add(myRotateLifetimeAction);
+     * myLifetimeActions.add(myNotifyLifetimeAction);
+     *
+     * KeyRotationPolicyProperties myPolicyProperties = new KeyRotationPolicyProperties()
+     *     .setLifetimeActions(myLifetimeActions)
+     *     .setExpiryTime("P6M");
+     *
+     * Response<KeyRotationPolicy> keyRotationPolicyResponse = keyClient.updateKeyRotationPolicyWithResponse(
+     *     "keyName", myPolicyProperties, new Context("key1", "value1"));
+     *
+     * System.out.printf("Response received successfully with status code: %d. Updated key rotation policy"
+     *     + "with id: %s%n", keyRotationPolicyResponse.getStatusCode(), keyRotationPolicyResponse.getValue().getId());
+     * 
+ * * * @param name The name of the {@link KeyVaultKey key}. * @param keyRotationPolicyProperties The {@link KeyRotationPolicyProperties} for the key. diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java index dfd3ed735b70b..d403f60372a1f 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java @@ -41,23 +41,56 @@ *

The minimal configuration options required by {@link KeyClientBuilder} to build {@link KeyAsyncClient} are * {@link String vaultUrl} and {@link TokenCredential credential}.

* - * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.instantiation} + * + *
+ * KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildAsyncClient();
+ * 
+ * * *

The {@link HttpLogDetailLevel log detail level}, multiple custom {@link HttpLoggingPolicy policies} and custom * {@link HttpClient http client} can be optionally configured in the {@link KeyClientBuilder}.

* - * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.instantiation.withHttpClient} + * + *
+ * KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .httpClient(HttpClient.createDefault())
+ *     .buildAsyncClient();
+ * 
+ * * *

Alternatively, custom {@link HttpPipeline http pipeline} with custom {@link HttpPipelinePolicy} policies and * {@link String vaultUrl} can be specified. It provides finer control over the construction of {@link KeyAsyncClient} * and {@link KeyClient}

* - * {@codesnippet com.azure.security.keyvault.keys.KeyAsyncClient.instantiation.withHttpPipeline} + * + *
+ * HttpPipeline pipeline = new HttpPipelineBuilder()
+ *     .policies(new KeyVaultCredentialPolicy(new DefaultAzureCredentialBuilder().build()), new RetryPolicy())
+ *     .build();
+ * KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
+ *     .pipeline(pipeline)
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .buildAsyncClient();
+ * 
+ * * *

The minimal configuration options required by {@link KeyClientBuilder secretClientBuilder} to build {@link * KeyClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

* - * {@codesnippet com.azure.security.keyvault.keys.KeyClient.instantiation} + * + *
+ * KeyClient keyClient = new KeyClientBuilder()
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildClient();
+ * 
+ * * * @see KeyAsyncClient * @see KeyClient @@ -121,8 +154,8 @@ public KeyClient buildClient() { *

If {@link KeyClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and * {@link KeyClientBuilder#vaultUrl(String) vaultUrl} are used to create the {@link KeyClientBuilder client}. * All other builder settings are ignored. If {@code pipeline} is not set, then {@link - * KeyClientBuilder#credential(TokenCredential) key vault credential and {@link KeyClientBuilder#vaultUrl(String)} - * key vault url are required to build the {@link KeyAsyncClient client}.}

+ * KeyClientBuilder#credential(TokenCredential) key vault credential} and {@link KeyClientBuilder#vaultUrl(String)} + * key vault url are required to build the {@link KeyAsyncClient client}.

* * @return A {@link KeyAsyncClient} with the options set from the builder. * diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyServiceVersion.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyServiceVersion.java index 64eee7e28b7c7..f621d3c271235 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyServiceVersion.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyServiceVersion.java @@ -9,9 +9,24 @@ * The versions of Azure Key Vault Key supported by this client library. */ public enum KeyServiceVersion implements ServiceVersion { + /** + * Service version {@code 7.0}. + */ V7_0("7.0"), + + /** + * Service version {@code 7.1}. + */ V7_1("7.1"), + + /** + * Service version {@code 7.2}. + */ V7_2("7.2"), + + /** + * Service version {@code 7.3-preview}. + */ V7_3_PREVIEW("7.3-preview"); private final String version; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java index a030cc2d14613..38ece066b6c16 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java @@ -51,8 +51,22 @@ * *

Samples to construct the sync client

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.instantiation} - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withJsonWebKey.instantiation} + * + *
+ * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
+ *     .keyIdentifier("<your-key-id>")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildAsyncClient();
+ * 
+ * + * + *
+ * JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey");
+ * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
+ *     .jsonWebKey(jsonWebKey)
+ *     .buildAsyncClient();
+ * 
+ * * * @see CryptographyClientBuilder */ @@ -159,7 +173,14 @@ Mono getKeyId() { *

Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey} + * + *
+     * cryptographyAsyncClient.getKey()
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(key ->
+     *         System.out.printf("Key returned with name: %s, and id: %s.%n", key.getName(), key.getId()));
+     * 
+ * * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * @@ -182,7 +203,15 @@ public Mono getKey() { *

Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse} + * + *
+     * cryptographyAsyncClient.getKeyWithResponse()
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(keyResponse ->
+     *         System.out.printf("Key returned with name: %s, and id: %s.%n", keyResponse.getValue().getName(),
+     *             keyResponse.getValue().getId()));
+     * 
+ * * * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the * requested {@link KeyVaultKey key}. @@ -240,7 +269,18 @@ Mono getSecretKey() { *

Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptionAlgorithm-byte} + * + *
+     * byte[] plaintext = new byte[100];
+     * new Random(0x1234567L).nextBytes(plaintext);
+     *
+     * cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(encryptResult ->
+     *         System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
+     *             encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString()));
+     * 
+ * * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. @@ -284,7 +324,24 @@ public Mono encrypt(EncryptionAlgorithm algorithm, byte[] plainte *

Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptParameters} + * + *
+     * byte[] plaintextBytes = new byte[100];
+     * new Random(0x1234567L).nextBytes(plaintextBytes);
+     * byte[] iv = {
+     *     (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd,
+     *     (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04
+     * };
+     *
+     * EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(plaintextBytes, iv);
+     *
+     * cryptographyAsyncClient.encrypt(encryptParameters)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(encryptResult ->
+     *         System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
+     *             encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString()));
+     * 
+ * * * @param encryptParameters The parameters to use in the encryption operation. * @@ -359,7 +416,17 @@ Mono encrypt(EncryptParameters encryptParameters, Context context *

Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#EncryptionAlgorithm-byte} + * + *
+     * byte[] ciphertext = new byte[100];
+     * new Random(0x1234567L).nextBytes(ciphertext);
+     *
+     * cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(decryptResult ->
+     *         System.out.printf("Received decrypted content of length: %d%n", decryptResult.getPlainText().length));
+     * 
+ * * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. @@ -401,7 +468,23 @@ public Mono decrypt(EncryptionAlgorithm algorithm, byte[] ciphert *

Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#DecryptParameters} + * + *
+     * byte[] ciphertextBytes = new byte[100];
+     * new Random(0x1234567L).nextBytes(ciphertextBytes);
+     * byte[] iv = {
+     *     (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd,
+     *     (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04
+     * };
+     *
+     * DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(ciphertextBytes, iv);
+     *
+     * cryptographyAsyncClient.decrypt(decryptParameters)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(decryptResult ->
+     *         System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length));
+     * 
+ * * * @param decryptParameters The parameters to use in the decryption operation. * @@ -468,7 +551,21 @@ Mono decrypt(DecryptParameters decryptParameters, Context context *

Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign#SignatureAlgorithm-byte} + * + *
+     * byte[] data = new byte[100];
+     * new Random(0x1234567L).nextBytes(data);
+     * MessageDigest md = MessageDigest.getInstance("SHA-256");
+     * md.update(data);
+     * byte[] digest = md.digest();
+     *
+     * cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, digest)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(signResult ->
+     *         System.out.printf("Received signature of length: %d, with algorithm: %s.%n",
+     *             signResult.getSignature().length, signResult.getAlgorithm()));
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. @@ -524,7 +621,21 @@ Mono sign(SignatureAlgorithm algorithm, byte[] digest, Context conte *

Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify#SignatureAlgorithm-byte-byte} + * + *
+     * byte[] myData = new byte[100];
+     * new Random(0x1234567L).nextBytes(myData);
+     * MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
+     * messageDigest.update(myData);
+     * byte[] myDigest = messageDigest.digest();
+     *
+     * // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation.
+     * cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myDigest, signature)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(verifyResult ->
+     *         System.out.printf("Verification status: %s.%n", verifyResult.isValid()));
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. @@ -582,7 +693,18 @@ Mono verify(SignatureAlgorithm algorithm, byte[] digest, byte[] si *

Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey#KeyWrapAlgorithm-byte} + * + *
+     * byte[] key = new byte[100];
+     * new Random(0x1234567L).nextBytes(key);
+     *
+     * cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(wrapResult ->
+     *         System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n",
+     *             wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm().toString()));
+     * 
+ * * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. @@ -638,7 +760,19 @@ Mono wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context *

Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey#KeyWrapAlgorithm-byte} + * + *
+     * byte[] keyToWrap = new byte[100];
+     * new Random(0x1234567L).nextBytes(key);
+     *
+     * cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(wrapResult ->
+     *         cryptographyAsyncClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapResult.getEncryptedKey())
+     *             .subscribe(keyUnwrapResult ->
+     *                 System.out.printf("Received key of length: %d.%n", keyUnwrapResult.getKey().length)));
+     * 
+ * * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. @@ -693,7 +827,18 @@ Mono unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Co *

Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData#SignatureAlgorithm-byte} + * + *
+     * byte[] data = new byte[100];
+     * new Random(0x1234567L).nextBytes(data);
+     *
+     * cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, data)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(signResult ->
+     *         System.out.printf("Received signature of length: %d, with algorithm: %s.%n",
+     *             signResult.getSignature().length, signResult.getAlgorithm()));
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. @@ -749,7 +894,18 @@ Mono signData(SignatureAlgorithm algorithm, byte[] data, Context con *

Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData#SignatureAlgorithm-byte-byte} + * + *
+     * byte[] myData = new byte[100];
+     * new Random(0x1234567L).nextBytes(myData);
+     *
+     * // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation.
+     * cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myData, signature)
+     *     .contextWrite(Context.of("key1", "value1", "key2", "value2"))
+     *     .subscribe(verifyResult ->
+     *         System.out.printf("Verification status: %s.%n", verifyResult.isValid()));
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClient.java index d96c762c4db42..6a07525a13a38 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClient.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClient.java @@ -32,8 +32,22 @@ * *

Samples to construct the sync client

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.instantiation} - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.withJsonWebKey.instantiation} + * + *
+ * CryptographyClient cryptographyClient = new CryptographyClientBuilder()
+ *     .keyIdentifier("<your-key-id>")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildClient();
+ * 
+ * + * + *
+ * JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey");
+ * CryptographyClient cryptographyClient = new CryptographyClientBuilder()
+ *     .jsonWebKey(jsonWebKey)
+ *     .buildClient();
+ * 
+ * * * @see CryptographyClientBuilder */ @@ -58,7 +72,13 @@ public class CryptographyClient { *

Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKey} + * + *
+     * KeyVaultKey key = cryptographyClient.getKey();
+     *
+     * System.out.printf("Key returned with name: %s and id: %s.%n", key.getName(), key.getId());
+     * 
+ * * * @return A {@link Mono} containing the requested {@link KeyVaultKey key}. * @@ -77,7 +97,14 @@ public KeyVaultKey getKey() { *

Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKeyWithResponse#Context} + * + *
+     * KeyVaultKey keyWithVersion = cryptographyClient.getKeyWithResponse(new Context("key1", "value1")).getValue();
+     *
+     * System.out.printf("Key is returned with name: %s and id %s.%n", keyWithVersion.getName(),
+     *     keyWithVersion.getId());
+     * 
+ * * * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. * @@ -115,7 +142,17 @@ public Response getKeyWithResponse(Context context) { *

Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte} + * + *
+     * byte[] plaintext = new byte[100];
+     * new Random(0x1234567L).nextBytes(plaintext);
+     *
+     * EncryptResult encryptResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext);
+     *
+     * System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
+     *     encryptResult.getCipherText().length, encryptResult.getAlgorithm());
+     * 
+ * * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. @@ -156,7 +193,18 @@ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { *

Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte-Context} + * + *
+     * byte[] plaintextToEncrypt = new byte[100];
+     * new Random(0x1234567L).nextBytes(plaintextToEncrypt);
+     *
+     * EncryptResult encryptionResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintextToEncrypt,
+     *     new Context("key1", "value1"));
+     *
+     * System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
+     *     encryptionResult.getCipherText().length, encryptionResult.getAlgorithm());
+     * 
+ * * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. @@ -198,7 +246,22 @@ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Co *

Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptParameters-Context} + * + *
+     * byte[] myPlaintext = new byte[100];
+     * new Random(0x1234567L).nextBytes(myPlaintext);
+     * byte[] iv = {
+     *     (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd,
+     *     (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04
+     * };
+     *
+     * EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(myPlaintext, iv);
+     * EncryptResult encryptedResult = cryptographyClient.encrypt(encryptParameters, new Context("key1", "value1"));
+     *
+     * System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n",
+     *     encryptedResult.getCipherText().length, encryptedResult.getAlgorithm());
+     * 
+ * * * @param encryptParameters The parameters to use in the encryption operation. * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. @@ -238,7 +301,16 @@ public EncryptResult encrypt(EncryptParameters encryptParameters, Context contex *

Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte} + * + *
+     * byte[] ciphertext = new byte[100];
+     * new Random(0x1234567L).nextBytes(ciphertext);
+     *
+     * DecryptResult decryptResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext);
+     *
+     * System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length);
+     * 
+ * * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. @@ -278,7 +350,17 @@ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext) { *

Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte-Context} + * + *
+     * byte[] ciphertextToDecrypt = new byte[100];
+     * new Random(0x1234567L).nextBytes(ciphertextToDecrypt);
+     *
+     * DecryptResult decryptionResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertextToDecrypt,
+     *     new Context("key1", "value1"));
+     *
+     * System.out.printf("Received decrypted content of length: %d.%n", decryptionResult.getPlainText().length);
+     * 
+ * * * @param algorithm The algorithm to be used for decryption. * @param ciphertext The content to be decrypted. @@ -319,7 +401,21 @@ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, C *

Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#DecryptParameters-Context} + * + *
+     * byte[] myCiphertext = new byte[100];
+     * new Random(0x1234567L).nextBytes(myCiphertext);
+     * byte[] iv = {
+     *     (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd,
+     *     (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04
+     * };
+     *
+     * DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(myCiphertext, iv);
+     * DecryptResult decryptedResult = cryptographyClient.decrypt(decryptParameters, new Context("key1", "value1"));
+     *
+     * System.out.printf("Received decrypted content of length: %d.%n", decryptedResult.getPlainText().length);
+     * 
+ * * * @param decryptParameters The parameters to use in the decryption operation. * @param context Additional context that is passed through the {@link HttpPipeline} during the service call. @@ -352,7 +448,20 @@ public DecryptResult decrypt(DecryptParameters decryptParameters, Context contex *

Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte} + * + *
+     * byte[] data = new byte[100];
+     * new Random(0x1234567L).nextBytes(data);
+     * MessageDigest md = MessageDigest.getInstance("SHA-256");
+     * md.update(data);
+     * byte[] digest = md.digest();
+     *
+     * SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, digest);
+     *
+     * System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length,
+     *     signResult.getAlgorithm());
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. @@ -384,7 +493,21 @@ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest) { *

Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte-Context} + * + *
+     * byte[] dataToVerify = new byte[100];
+     * new Random(0x1234567L).nextBytes(dataToVerify);
+     * MessageDigest myMessageDigest = MessageDigest.getInstance("SHA-256");
+     * myMessageDigest.update(dataToVerify);
+     * byte[] digestContent = myMessageDigest.digest();
+     *
+     * SignResult signResponse = cryptographyClient.sign(SignatureAlgorithm.ES256, digestContent,
+     *     new Context("key1", "value1"));
+     *
+     * System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResponse.getSignature().length,
+     *     signResponse.getAlgorithm());
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. @@ -418,7 +541,20 @@ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context cont *

Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte} + * + *
+     * byte[] myData = new byte[100];
+     * new Random(0x1234567L).nextBytes(myData);
+     * MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
+     * messageDigest.update(myData);
+     * byte[] myDigest = messageDigest.digest();
+     *
+     * // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation.
+     * VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myDigest, signature);
+     *
+     * System.out.printf("Verification status: %s.%n", verifyResult.isValid());
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. @@ -452,7 +588,21 @@ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] s *

Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte-Context} + * + *
+     * byte[] dataBytes = new byte[100];
+     * new Random(0x1234567L).nextBytes(dataBytes);
+     * MessageDigest msgDigest = MessageDigest.getInstance("SHA-256");
+     * msgDigest.update(dataBytes);
+     * byte[] digestBytes = msgDigest.digest();
+     *
+     * // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation.
+     * VerifyResult verifyResponse = cryptographyClient.verify(SignatureAlgorithm.ES256, digestBytes, signatureBytes,
+     *     new Context("key1", "value1"));
+     *
+     * System.out.printf("Verification status: %s.%n", verifyResponse.isValid());
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. @@ -487,7 +637,17 @@ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] s *

Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte} + * + *
+     * byte[] key = new byte[100];
+     * new Random(0x1234567L).nextBytes(key);
+     *
+     * WrapResult wrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key);
+     *
+     * System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n",
+     *     wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm());
+     * 
+ * * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. @@ -521,7 +681,18 @@ public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { *

Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte-Context} + * + *
+     * byte[] keyToWrap = new byte[100];
+     * new Random(0x1234567L).nextBytes(keyToWrap);
+     *
+     * WrapResult keyWrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap,
+     *     new Context("key1", "value1"));
+     *
+     * System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n",
+     *     keyWrapResult.getEncryptedKey().length, keyWrapResult.getAlgorithm());
+     * 
+ * * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped. @@ -556,7 +727,19 @@ public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context contex *

Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte} + * + *
+     * byte[] keyContent = new byte[100];
+     * new Random(0x1234567L).nextBytes(keyContent);
+     *
+     * WrapResult wrapKeyResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContent,
+     *     new Context("key1", "value1"));
+     * UnwrapResult unwrapResult = cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP,
+     *     wrapKeyResult.getEncryptedKey());
+     *
+     * System.out.printf("Received key of length %d", unwrapResult.getKey().length);
+     * 
+ * * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. @@ -590,7 +773,20 @@ public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { *

Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when * a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte-Context} + * + *
+     * byte[] keyContentToWrap = new byte[100];
+     * new Random(0x1234567L).nextBytes(keyContentToWrap);
+     * Context context = new Context("key1", "value1");
+     *
+     * WrapResult wrapKeyContentResult =
+     *     cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContentToWrap, context);
+     * UnwrapResult unwrapKeyResponse =
+     *     cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapKeyContentResult.getEncryptedKey(), context);
+     *
+     * System.out.printf("Received key of length %d", unwrapKeyResponse.getKey().length);
+     * 
+ * * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. @@ -624,7 +820,17 @@ public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, C *

Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte} + * + *
+     * byte[] data = new byte[100];
+     * new Random(0x1234567L).nextBytes(data);
+     *
+     * SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, data);
+     *
+     * System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length,
+     *     signResult.getAlgorithm());
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. @@ -656,7 +862,17 @@ public SignResult signData(SignatureAlgorithm algorithm, byte[] data) { *

Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a * response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte-Context} + * + *
+     * byte[] plainTextData = new byte[100];
+     * new Random(0x1234567L).nextBytes(plainTextData);
+     *
+     * SignResult signingResult = cryptographyClient.sign(SignatureAlgorithm.ES256, plainTextData);
+     *
+     * System.out.printf("Received signature of length: %d, with algorithm: %s.%n",
+     *     signingResult.getSignature().length, new Context("key1", "value1"));
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. @@ -690,7 +906,17 @@ public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context co *

Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte} + * + *
+     * byte[] myData = new byte[100];
+     * new Random(0x1234567L).nextBytes(myData);
+     *
+     * // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation.
+     * VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myData, signature);
+     *
+     * System.out.printf("Verification status: %s.%n", verifyResult.isValid());
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. @@ -724,7 +950,18 @@ public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] *

Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte-Context} + * + *
+     * byte[] dataToVerify = new byte[100];
+     * new Random(0x1234567L).nextBytes(dataToVerify);
+     *
+     * // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation.
+     * VerifyResult verificationResult = cryptographyClient.verify(SignatureAlgorithm.ES256, dataToVerify,
+     *     mySignature, new Context("key1", "value1"));
+     *
+     * System.out.printf("Verification status: %s.%n", verificationResult.isValid());
+     * 
+ * * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java index 95a040b4cda18..ec2bbc794c4fc 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java @@ -45,26 +45,73 @@ * for the specific key version that was used for the corresponding inverse operation: {@code Encrypt}, * {@code Wrap}, or {@code Sign}, respectively.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.instantiation} - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withJsonWebKey.instantiation} + * + *
+ * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
+ *     .keyIdentifier("<your-key-id>")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildAsyncClient();
+ * 
+ * + * + *
+ * JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey");
+ * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
+ *     .jsonWebKey(jsonWebKey)
+ *     .buildAsyncClient();
+ * 
+ * * *

The {@link HttpLogDetailLevel log detail level}, multiple custom {@link HttpLoggingPolicy policies} and a custom * {@link HttpClient http client} can be optionally configured in the {@link CryptographyClientBuilder}.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withHttpClient.instantiation} + * + *
+ * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
+ *     .keyIdentifier("<your-key-id>")
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .addPolicy(new KeyVaultCredentialPolicy(new DefaultAzureCredentialBuilder().build()))
+ *     .httpClient(HttpClient.createDefault())
+ *     .buildAsyncClient();
+ * 
+ * * *

Alternatively, a custom {@link HttpPipeline http pipeline} with custom {@link HttpPipelinePolicy} policies * can be specified. It provides finer control over the construction of {@link CryptographyAsyncClient} and * {@link CryptographyClient}

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withPipeline.instantiation} + * + *
+ * HttpPipeline pipeline = new HttpPipelineBuilder()
+ *     .policies(new KeyVaultCredentialPolicy(new DefaultAzureCredentialBuilder().build()), new RetryPolicy())
+ *     .build();
+ * CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder()
+ *     .pipeline(pipeline)
+ *     .keyIdentifier("<your-key-id>")
+ *     .buildAsyncClient();
+ * 
+ * * *

The minimal configuration options required by {@link CryptographyClientBuilder cryptographyClientBuilder} to * build {@link CryptographyClient} are {@link JsonWebKey jsonWebKey} or * {@link String Azure Key Vault key identifier} and {@link TokenCredential credential}.

* - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.instantiation} - * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyClient.withJsonWebKey.instantiation} + * + *
+ * CryptographyClient cryptographyClient = new CryptographyClientBuilder()
+ *     .keyIdentifier("<your-key-id>")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .buildClient();
+ * 
+ * + * + *
+ * JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey");
+ * CryptographyClient cryptographyClient = new CryptographyClientBuilder()
+ *     .jsonWebKey(jsonWebKey)
+ *     .buildClient();
+ * 
+ * * * @see CryptographyAsyncClient * @see CryptographyClient diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyServiceVersion.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyServiceVersion.java index ec1d46e564c38..f3332fab43fd3 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyServiceVersion.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyServiceVersion.java @@ -9,9 +9,24 @@ * The versions of Azure Key Vault Cryptography supported by this client library. */ public enum CryptographyServiceVersion implements ServiceVersion { + /** + * Service version {@code 7.0}. + */ V7_0("7.0"), + + /** + * Service version {@code 7.1}. + */ V7_1("7.1"), + + /** + * Service version {@code 7.2}. + */ V7_2("7.2"), + + /** + * Service version {@code 7.3-preview}. + */ V7_3_PREVIEW("7.3-preview"); private final String version; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java index 837eee0c34927..cb7f4a86780ae 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java @@ -10,7 +10,14 @@ * Defines the types of key rotation policy actions that can be executed. */ public enum KeyRotationPolicyAction { + /** + * Rotate policy action. + */ ROTATE("rotate"), + + /** + * Notify policy action. + */ NOTIFY("notify"); /** diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyProperties.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyProperties.java index 13381f002fa30..78f8954109895 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyProperties.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyProperties.java @@ -17,7 +17,14 @@ */ @Fluent public class KeyRotationPolicyProperties { + /** + * The expiry time in ISO-8601 format. + */ protected String expiryTime; + + /** + * The {@link KeyRotationLifetimeAction}. + */ protected List keyRotationLifetimeActions; /** diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ReadmeSamples.java b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ReadmeSamples.java new file mode 100644 index 0000000000000..c92d3ab28c9b2 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/ReadmeSamples.java @@ -0,0 +1,264 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient; +import com.azure.security.keyvault.keys.cryptography.CryptographyClient; +import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder; +import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.KeyCurveName; +import com.azure.security.keyvault.keys.models.KeyProperties; +import com.azure.security.keyvault.keys.models.KeyVaultKey; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.security.SecureRandom; +import java.time.OffsetDateTime; + +@SuppressWarnings("unused") +public class ReadmeSamples { + private static final byte[] SEED; + + static { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(bos); + byte[] seed; + try { + dos.writeLong(0x1234567L); + dos.flush(); + seed = bos.toByteArray(); + } catch (IOException ex) { + seed = new byte[0]; + } + + SEED = seed; + } + + private final KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + private final CryptographyClient cryptoClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createKeyClient + } + + public void createCryptographyClient() { + // BEGIN: readme-sample-createCryptographyClient + // Create client with key identifier from key vault. + CryptographyClient cryptoClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .buildClient(); + // END: readme-sample-createCryptographyClient + } + + public void createKey() { + // BEGIN: readme-sample-createKey + KeyVaultKey rsaKey = keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)); + System.out.printf("Key created with name \"%s\" and id %s%n", rsaKey.getName(), rsaKey.getId()); + + KeyVaultKey ecKey = keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setCurveName(KeyCurveName.P_256) + .setExpiresOn(OffsetDateTime.now().plusYears(1))); + System.out.printf("Key created with name \"%s\" and id %s%n", ecKey.getName(), ecKey.getId()); + // END: readme-sample-createKey + } + + public void retrieveKey() { + // BEGIN: readme-sample-retrieveKey + KeyVaultKey key = keyClient.getKey(""); + System.out.printf("A key was returned with name \"%s\" and id %s%n", key.getName(), key.getId()); + // END: readme-sample-retrieveKey + } + + public void updateKey() { + // BEGIN: readme-sample-updateKey + // Get the key to update. + KeyVaultKey key = keyClient.getKey(""); + // Update the expiry time of the key. + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); + KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties()); + System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn()); + // END: readme-sample-updateKey + } + + public void deleteKey() { + // BEGIN: readme-sample-deleteKey + SyncPoller deletedKeyPoller = keyClient.beginDeleteKey(""); + + PollResponse deletedKeyPollResponse = deletedKeyPoller.poll(); + + // Deleted key is accessible as soon as polling begins. + DeletedKey deletedKey = deletedKeyPollResponse.getValue(); + // Deletion date only works for a SoftDelete-enabled Key Vault. + System.out.printf("Deletion date: %s%n", deletedKey.getDeletedOn()); + + // Key is being deleted on server. + deletedKeyPoller.waitForCompletion(); + // END: readme-sample-deleteKey + } + + public void listKeys() { + // BEGIN: readme-sample-listKeys + // List operations don't return the keys with key material information. So, for each returned key we call getKey to + // get the key with its key material information. + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { + KeyVaultKey keyWithMaterial = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + System.out.printf("Received key with name \"%s\" and type \"%s\"%n", keyWithMaterial.getName(), + keyWithMaterial.getKey().getKeyType()); + } + // END: readme-sample-listKeys + } + + public void encrypt() { + // BEGIN: readme-sample-encrypt + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); + System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); + // END: readme-sample-encrypt + } + + public void decrypt() { + // BEGIN: readme-sample-decrypt + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); + + //Let's decrypt the encrypted result. + DecryptResult decryptionResult = cryptoClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); + System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length); + // END: readme-sample-decrypt + } + + public void createKeyAsync() { + // BEGIN: readme-sample-createKeyAsync + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)) + .subscribe(key -> + System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); + + keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(key -> + System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); + // END: readme-sample-createKeyAsync + } + + public void retrieveKeyAsync() { + // BEGIN: readme-sample-retrieveKeyAsync + keyAsyncClient.getKey("") + .subscribe(key -> + System.out.printf("Key was returned with name \"%s\" and id %s%n", key.getName(), key.getId())); + // END: readme-sample-retrieveKeyAsync + } + + public void updateKeyAsync() { + // BEGIN: readme-sample-updateKeyAsync + keyAsyncClient.getKey("") + .flatMap(key -> { + // Update the expiry time of the key. + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); + return keyAsyncClient.updateKeyProperties(key.getProperties()); + }).subscribe(updatedKey -> + System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn())); + // END: readme-sample-updateKeyAsync + } + + public void deleteKeyAsync() { + // BEGIN: readme-sample-deleteKeyAsync + keyAsyncClient.beginDeleteKey("") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deleted key name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Key deletion date: %s%n", pollResponse.getValue().getDeletedOn()); + }); + // END: readme-sample-deleteKeyAsync + } + + public void listKeysAsync() { + // BEGIN: readme-sample-listKeysAsync + // The List Keys operation returns keys without their value, so for each key returned we call `getKey` to get its value + // as well. + keyAsyncClient.listPropertiesOfKeys() + .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) + .subscribe(key -> + System.out.printf("Received key with name \"%s\" and type \"%s\"", key.getName(), key.getKeyType())); + // END: readme-sample-listKeysAsync + } + + public void encryptAsync() { + // BEGIN: readme-sample-encryptAsync + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .subscribe(encryptionResult -> System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm())); + // END: readme-sample-encryptAsync + } + + public void decryptAsync() { + // BEGIN: readme-sample-decryptAsync + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .flatMap(encryptionResult -> { + System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); + //Let's decrypt the encrypted response. + return cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); + }).subscribe(decryptionResult -> + System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length)); + // END: readme-sample-decryptAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + keyClient.getKey(""); + } catch (ResourceNotFoundException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } +} diff --git a/sdk/keyvault/azure-security-keyvault-perf/pom.xml b/sdk/keyvault/azure-security-keyvault-perf/pom.xml index 0fb11a6447df2..666c8164db72e 100644 --- a/sdk/keyvault/azure-security-keyvault-perf/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-perf/pom.xml @@ -21,6 +21,9 @@ UTF-8 1.8 1.8 + false + + diff --git a/sdk/keyvault/azure-security-keyvault-secrets/README.md b/sdk/keyvault/azure-security-keyvault-secrets/README.md index 5165d485ce4ef..0530c6cfaa0cf 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/README.md +++ b/sdk/keyvault/azure-security-keyvault-secrets/README.md @@ -27,9 +27,9 @@ Maven dependency for the Azure Key Vault Secrets client library. Add it to your - [Azure Subscription][azure_subscription] - An existing [Azure Key Vault][azure_keyvault]. If you need to create a Key Vault, you can use the [Azure Cloud Shell][azure_cloud_shell] to create one with this Azure CLI command. Replace `` and `` with your own, unique names: - ```Bash - az keyvault create --resource-group --name - ``` +```bash +az keyvault create --resource-group --name +``` ### Authenticate the client In order to interact with the Key Vault service, you'll need to create an instance of the [SecretClient](#create-secret-client) class. You would need a **vault url** and **client secret credentials (client id, client secret, tenant id)** to instantiate a client object using the `DefaultAzureCredential` examples shown in this document. @@ -43,55 +43,51 @@ Here is an [Azure Cloud Shell][azure_cloud_shell] snippet below to * Create a service principal and configure its access to Azure resources: - ```Bash - az ad sp create-for-rbac -n --skip-assignment - ``` +```bash +az ad sp create-for-rbac -n --skip-assignment +``` - Output: +Output: - ```json - { - "appId": "generated-app-ID", - "displayName": "dummy-app-name", - "name": "http://dummy-app-name", - "password": "random-password", - "tenant": "tenant-ID" - } - ``` +```json +{ + "appId": "generated-app-ID", + "displayName": "dummy-app-name", + "name": "http://dummy-app-name", + "password": "random-password", + "tenant": "tenant-ID" +} +``` * Use the above returned credentials information to set **AZURE_CLIENT_ID** (appId), **AZURE_CLIENT_SECRET** (password), and **AZURE_TENANT_ID** (tenant) environment variables. The following example shows a way to do this in Bash: - ```Bash - export AZURE_CLIENT_ID="generated-app-ID" - export AZURE_CLIENT_SECRET="random-password" - export AZURE_TENANT_ID="tenant-ID" - ``` +```bash +export AZURE_CLIENT_ID="generated-app-ID" +export AZURE_CLIENT_SECRET="random-password" +export AZURE_TENANT_ID="tenant-ID" +```` * Grant the aforementioned application authorization to perform secret operations on the Key Vault: - ```Bash - az keyvault set-policy --name --spn $AZURE_CLIENT_ID --secret-permissions backup delete get list set - ``` +```bash +az keyvault set-policy --name --spn $AZURE_CLIENT_ID --secret-permissions backup delete get list set +``` - > --secret-permissions: - > Accepted values: backup, delete, get, list, purge, recover, restore, set +> --secret-permissions: +> Accepted values: backup, delete, get, list, purge, recover, restore, set - If you have enabled role-based access control (RBAC) for Key Vault instead, you can find roles like "Key Vault Secrets Officer" in our [RBAC guide][rbac_guide]. +If you have enabled role-based access control (RBAC) for Key Vault instead, you can find roles like "Key Vault Secrets Officer" in our [RBAC guide][rbac_guide]. * Use the aforementioned Key Vault name to retrieve details of your Vault, which also contain your Key Vault URL: - ```Bash - az keyvault show --name - ``` +```bash +az keyvault show --name +``` #### Create secret client Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET**, and **AZURE_TENANT_ID** environment variables and replaced **your-key-vault-url** with the URI returned above, you can create the SecretClient: -```Java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.SecretClient; -import com.azure.security.keyvault.secrets.SecretClientBuilder; - +```java readme-sample-createSecretClient SecretClient secretClient = new SecretClientBuilder() .vaultUrl("") .credential(new DefaultAzureCredentialBuilder().build()) @@ -125,17 +121,7 @@ The following sections provide several code snippets covering some of the most c Create a secret to be stored in the Azure Key Vault. - `setSecret` creates a new secret in the Azure Key Vault. If a secret with the given name already exists then a new version of the secret is created. -```Java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.SecretClient; -import com.azure.security.keyvault.secrets.SecretClientBuilder; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; - -SecretClient secretClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - +```java readme-sample-createSecret KeyVaultSecret secret = secretClient.setSecret("", ""); System.out.printf("Secret created with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); ``` @@ -143,7 +129,7 @@ System.out.printf("Secret created with name \"%s\" and value \"%s\"%n", secret.g ### Retrieve a secret Retrieve a previously stored secret by calling `getSecret`. -```Java +```java readme-sample-retrieveSecret KeyVaultSecret secret = secretClient.getSecret(""); System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); ``` @@ -151,7 +137,7 @@ System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secret ### Update an existing secret Update an existing secret by calling `updateSecretProperties`. -```Java +```java readme-sample-updateSecret // Get the secret to update. KeyVaultSecret secret = secretClient.getSecret(""); // Update the expiry time of the secret. @@ -163,7 +149,7 @@ System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties. ### Delete a secret Delete an existing secret by calling `beginDeleteSecret`. -```Java +```java readme-sample-deleteSecret SyncPoller deletedSecretPoller = secretClient.beginDeleteSecret(""); // Deleted secret is accessible as soon as polling begins. @@ -179,7 +165,7 @@ deletedSecretPoller.waitForCompletion(); ### List secrets List the secrets in the Azure Key Vault by calling `listPropertiesOfSecrets`. -```Java +```java readme-sample-listSecrets // List operations don't return the secrets with value information. So, for each returned secret we call getSecret to // get the secret with its value information. for (SecretProperties secretProperties : secretClient.listPropertiesOfSecrets()) { @@ -203,48 +189,38 @@ The following sections provide several code snippets covering some of the most c Create a secret to be stored in the Azure Key Vault. - `setSecret` creates a new secret in the Azure Key Vault. If a secret with the given name already exists then a new version of the secret is created. -```Java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.SecretAsyncClient; -import com.azure.security.keyvault.secrets.models.Secret; - -SecretAsyncClient secretAsyncClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - +```java readme-sample-createSecretAsync secretAsyncClient.setSecret("", "") - .subscribe(secret -> - System.out.printf("Created secret with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue())); + .subscribe(secret -> System.out.printf("Created secret with name \"%s\" and value \"%s\"%n", + secret.getName(), secret.getValue())); ``` ### Retrieve a secret asynchronously Retrieve a previously stored secret by calling `getSecret`. -```Java +```java readme-sample-retrieveSecretAsync secretAsyncClient.getSecret("") - .subscribe(secret -> - System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue())); + .subscribe(secret -> System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", + secret.getName(), secret.getValue())); ``` ### Update an existing secret asynchronously Update an existing secret by calling `updateSecretProperties`. -```Java +```java readme-sample-updateSecretAsync secretAsyncClient.getSecret("") - .subscribe(secret -> { + .flatMap(secret -> { // Update the expiry time of the secret. secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); - secretAsyncClient.updateSecretProperties(secret.getProperties()) - .subscribe(updatedSecretProperties -> - System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn())); - }); + return secretAsyncClient.updateSecretProperties(secret.getProperties()); + }).subscribe(updatedSecretProperties -> + System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn())); ``` ### Delete a secret asynchronously Delete an existing secret by calling `beginDeleteSecret`. -```Java +```java readme-sample-deleteSecretAsync secretAsyncClient.beginDeleteSecret("") .subscribe(pollResponse -> { System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); @@ -256,24 +232,24 @@ secretAsyncClient.beginDeleteSecret("") ### List secrets asynchronously List the secrets in the Azure Key Vault by calling `listPropertiesOfSecrets`. -```Java +```java readme-sample-listSecretsAsync // The List secrets operation returns secrets without their value, so for each secret returned we call `getSecret` // to get its value as well. secretAsyncClient.listPropertiesOfSecrets() - .subscribe(secretProperties -> - secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion()) - .subscribe(secretResponse -> - System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretResponse.getName(), - secretResponse.getValue()))); + .flatMap(secretProperties -> + secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion())) + .subscribe(secretResponse -> + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretResponse.getName(), + secretResponse.getValue())); ``` ## Troubleshooting ### General Azure Key Vault Secret clients raise exceptions. For example, if you try to retrieve a secret after it is deleted a `404` error is returned, indicating the resource was not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error. -```java +```java readme-sample-troubleshooting try { - secretClient.getSecret("") + secretClient.getSecret(""); } catch (ResourceNotFoundException e) { System.out.println(e.getMessage()); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml b/sdk/keyvault/azure-security-keyvault-secrets/pom.xml index b565e918a6b20..b7f37dddd2df4 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-secrets/pom.xml @@ -51,6 +51,9 @@ --add-opens com.azure.security.keyvault.secrets/com.azure.security.keyvault.secrets=ALL-UNNAMED --add-opens com.azure.security.keyvault.secrets/com.azure.security.keyvault.secrets.models=ALL-UNNAMED + false + + diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java index 7c705151dac8e..7a3edf59f85c8 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java @@ -47,7 +47,15 @@ * Azure Key Vault. * *

Construct the async client

- * {@codesnippet com.azure.security.keyvault.secrets.async.secretclient.construct} + * + *
+ * SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .vaultUrl("https://myvault.vault.azure.net/")
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .buildAsyncClient();
+ * 
+ * * * @see SecretClientBuilder * @see PagedFlux @@ -118,7 +126,19 @@ Duration getDefaultPollingInterval() { *

Creates a new secret which activates in one day and expires in one year. Subscribes to the call asynchronously * and prints out the newly created secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.setSecret#secret} + * + *
+     * SecretProperties properties = new SecretProperties()
+     *     .setExpiresOn(OffsetDateTime.now().plusDays(60));
+     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue")
+     *     .setProperties(properties);
+     *
+     * secretAsyncClient.setSecret(newSecret)
+     *     .subscribe(secretResponse ->
+     *     System.out.printf("Secret is created with name %s and value %s %n",
+     *         secretResponse.getName(), secretResponse.getValue()));
+     * 
+ * * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret#getName() secret.name} and {@link KeyVaultSecret#getValue() secret.value} cannot be @@ -150,7 +170,16 @@ public Mono setSecret(KeyVaultSecret secret) { *

Creates a new secret which activates in one day and expires in one year. Subscribes to the call asynchronously * and prints out the newly created secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.setSecretWithResponse#secret} + * + *
+     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue").
+     *     setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)));
+     * secretAsyncClient.setSecretWithResponse(newSecret)
+     *     .subscribe(secretResponse ->
+     *         System.out.printf("Secret is created with name %s and value %s %n",
+     *             secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
+     * 
+ * * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret#getName() secret.name} and {@link KeyVaultSecret#getValue() secret.value} cannot be @@ -194,7 +223,14 @@ Mono> setSecretWithResponse(KeyVaultSecret secret, Cont *

Code sample

*

Creates a new secret in the key vault. Subscribes to the call asynchronously and prints out * the newly created secret details when a response is received.

- * {@codesnippet com.azure.keyvault.secrets.secretclient.setSecret#string-string} + * + *
+     * secretAsyncClient.setSecret("secretName", "secretValue")
+     *     .subscribe(secretResponse ->
+     *         System.out.printf("Secret is created with name %s and value %s%n",
+     *             secretResponse.getName(), secretResponse.getValue()));
+     * 
+ * * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. @@ -229,7 +265,18 @@ Mono> setSecretWithResponse(String name, String value, *

Gets a specific version of the secret in the key vault. Subscribes to the call * asynchronously and prints out the returned secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.getSecret#string-string} + * + *
+     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * secretAsyncClient.getSecret("secretName", secretVersion)
+     *     // Passing a Context is optional and useful if you want a set of data to flow through the request.
+     *     // Otherwise, the line below can be removed.
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(secretWithVersion ->
+     *         System.out.printf("Secret is returned with name %s and value %s %n",
+     *             secretWithVersion.getName(), secretWithVersion.getValue()));
+     * 
+ * * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this @@ -257,7 +304,18 @@ public Mono getSecret(String name, String version) { *

Code sample

*

Gets a specific version of the secret in the key vault. Subscribes to the call asynchronously and prints out * the returned secret details when a response is received.

- * {@codesnippet com.azure.keyvault.secrets.secretclient.getSecretWithResponse#string-string} + * + *
+     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * secretAsyncClient.getSecretWithResponse("secretName", secretVersion)
+     *     // Passing a Context is optional and useful if you want a set of data to flow through the request.
+     *     // Otherwise, the line below can be removed.
+     *     .subscriberContext(Context.of(key1, value1, key2, value2))
+     *     .subscribe(secretWithVersion ->
+     *         System.out.printf("Secret is returned with name %s and value %s %n",
+     *             secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue()));
+     * 
+ * * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent @@ -293,7 +351,14 @@ Mono> getSecretWithResponse(String name, String version *

Code sample

*

Gets latest version of the secret in the key vault. Subscribes to the call asynchronously and prints out the * returned secret details when a response is received.

- * {@codesnippet com.azure.keyvault.secrets.secretclient.getSecret#string} + * + *
+     * secretAsyncClient.getSecret("secretName")
+     *     .subscribe(secretWithVersion ->
+     *         System.out.printf("Secret is returned with name %s and value %s %n",
+     *             secretWithVersion.getName(), secretWithVersion.getValue()));
+     * 
+ * * * @param name The name of the secret. * @return A {@link Mono} containing the requested {@link KeyVaultSecret secret}. @@ -322,7 +387,20 @@ public Mono getSecret(String name) { * time, and then updates it in the Azure Key Vault. Subscribes to the call asynchronously and prints out the * returned secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.updateSecretProperties#secretProperties} + * + *
+     * secretAsyncClient.getSecret("secretName")
+     *     .subscribe(secretResponseValue -> {
+     *         SecretProperties secretProperties = secretResponseValue.getProperties();
+     *         //Update the not before time of the secret.
+     *         secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50));
+     *         secretAsyncClient.updateSecretProperties(secretProperties)
+     *             .subscribe(secretResponse ->
+     *                 System.out.printf("Secret's updated not before time %s %n",
+     *                     secretResponse.getNotBefore().toString()));
+     *     });
+     * 
+ * * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @return A {@link Mono} containing the {@link SecretProperties updated secret}. @@ -351,7 +429,20 @@ public Mono updateSecretProperties(SecretProperties secretProp * time, and then updates it in the Azure Key Vault. Subscribes to the call asynchronously and prints out the * returned secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.updateSecretPropertiesWithResponse#secretProperties} + * + *
+     * secretAsyncClient.getSecret("secretName")
+     *     .subscribe(secretResponseValue -> {
+     *         SecretProperties secretProperties = secretResponseValue.getProperties();
+     *         //Update the not before time of the secret.
+     *         secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50));
+     *         secretAsyncClient.updateSecretPropertiesWithResponse(secretProperties)
+     *             .subscribe(secretResponse ->
+     *                 System.out.printf("Secret's updated not before time %s %n",
+     *                     secretResponse.getValue().getNotBefore().toString()));
+     *     });
+     * 
+ * * *

The {@code secret} is required and its fields {@link SecretProperties#getName() name} and * {@link SecretProperties#getVersion() version} cannot be null.

@@ -398,7 +489,16 @@ Mono> updateSecretPropertiesWithResponse(SecretProper *

Code sample

*

Deletes the secret in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted * secret details when a response is received.

- * {@codesnippet com.azure.keyvault.secrets.secretclient.deleteSecret#String} + * + *
+     * secretAsyncClient.beginDeleteSecret("secretName")
+     *     .subscribe(pollResponse -> {
+     *         System.out.println("Delete Status: " + pollResponse.getStatus().toString());
+     *         System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName());
+     *         System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue());
+     *     });
+     * 
+ * * * @param name The name of the secret to be deleted. * @return A {@link PollerFlux} to poll on and retrieve {@link DeletedSecret deleted secret}. @@ -455,7 +555,13 @@ Mono> deleteSecretWithResponse(String name, Context cont *

Gets the deleted secret from the key vault enabled for soft-delete. Subscribes to the call * asynchronously and prints out the deleted secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.getDeletedSecret#string} + * + *
+     * secretAsyncClient.getDeletedSecret("secretName")
+     *     .subscribe(deletedSecretResponse ->
+     *         System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
+     * 
+ * * * @param name The name of the deleted secret. * @return A {@link Mono} containing the {@link DeletedSecret deleted secret}. @@ -479,7 +585,14 @@ public Mono getDeletedSecret(String name) { *

Gets the deleted secret from the key vault enabled for soft-delete. Subscribes to the call * asynchronously and prints out the deleted secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.getDeletedSecretWithResponse#string} + * + *
+     * secretAsyncClient.getDeletedSecretWithResponse("secretName")
+     *     .subscribe(deletedSecretResponse ->
+     *         System.out.printf("Deleted Secret's Recovery Id %s %n",
+     *             deletedSecretResponse.getValue().getRecoveryId()));
+     * 
+ * * * @param name The name of the deleted secret. * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the @@ -513,7 +626,14 @@ Mono> getDeletedSecretWithResponse(String name, Context *

Purges the deleted secret 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 is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.purgeDeletedSecret#string} + * + *
+     * secretAsyncClient.purgeDeletedSecret("deletedSecretName")
+     *     .doOnSuccess(purgeResponse ->
+     *         System.out.println("Successfully Purged deleted Secret"))
+     *     .subscribe();
+     * 
+ * * * @param name The name of the secret. * @return An empty {@link Mono}. @@ -537,7 +657,13 @@ public Mono purgeDeletedSecret(String name) { *

Purges the deleted secret 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 is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.purgeDeletedSecretWithResponse#string} + * + *
+     * secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName")
+     *     .subscribe(purgeResponse ->
+     *         System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
+     * 
+ * * * @param name The name of the secret. * @return A {@link Mono} containing a Response containing status code and HTTP headers. @@ -570,7 +696,16 @@ Mono> purgeDeletedSecretWithResponse(String name, Context context *

Recovers the deleted secret from the key vault enabled for soft-delete. Subscribes to the call * asynchronously and prints out the recovered secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.recoverDeletedSecret#String} + * + *
+     * secretAsyncClient.beginRecoverDeletedSecret("deletedSecretName")
+     *     .subscribe(pollResponse -> {
+     *         System.out.println("Recovery Status: " + pollResponse.getStatus().toString());
+     *         System.out.println("Recovered Secret Name: " + pollResponse.getValue().getName());
+     *         System.out.println("Recovered Secret Value: " + pollResponse.getValue().getValue());
+     *     });
+     * 
+ * * * @param name The name of the deleted secret to be recovered. * @return A {@link PollerFlux} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. @@ -626,7 +761,13 @@ Mono> recoverDeletedSecretWithResponse(String name, Con *

Backs up the secret from the key vault. Subscribes to the call asynchronously and prints out * the length of the secret's backup byte array returned in the response.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.backupSecret#string} + * + *
+     * secretAsyncClient.backupSecret("secretName")
+     *     .subscribe(secretBackupResponse ->
+     *         System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.length));
+     * 
+ * * * @param name The name of the secret. * @return A {@link Mono} containing the backed up secret blob. @@ -650,7 +791,13 @@ public Mono backupSecret(String name) { *

Backs up the secret from the key vault. Subscribes to the call asynchronously and prints out * the length of the secret's backup byte array returned in the response.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.backupSecretWithResponse#string} + * + *
+     * secretAsyncClient.backupSecretWithResponse("secretName")
+     *     .subscribe(secretBackupResponse ->
+     *         System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.getValue().length));
+     * 
+ * * * @param name The name of the secret. * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} @@ -687,7 +834,15 @@ Mono> backupSecretWithResponse(String name, Context context) { *

Restores the secret in the key vault from its backup. Subscribes to the call asynchronously * and prints out the restored secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.restoreSecret#byte} + * + *
+     * // Pass the secret backup byte array to the restore operation.
+     * byte[] secretBackupByteArray = {};
+     * secretAsyncClient.restoreSecretBackup(secretBackupByteArray)
+     *     .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
+     *         secretResponse.getName(), secretResponse.getValue()));
+     * 
+ * * * @param backup The backup blob associated with the secret. * @return A {@link Mono} containing the {@link KeyVaultSecret restored secret}. @@ -710,7 +865,15 @@ public Mono restoreSecretBackup(byte[] backup) { *

Restores the secret in the key vault from its backup. Subscribes to the call asynchronously * and prints out the restored secret details when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.restoreSecretWithResponse#byte} + * + *
+     * // Pass the secret backup byte array to the restore operation.
+     * byte[] secretBackupByteArray = {};
+     * secretAsyncClient.restoreSecretBackupWithResponse(secretBackupByteArray)
+     *     .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
+     *         secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
+     * 
+ * * * @param backup The backup blob associated with the secret. * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} @@ -745,7 +908,20 @@ Mono> restoreSecretBackupWithResponse(byte[] backup, Co *

The sample below fetches the all the secret properties in the vault. For each secret retrieved, makes a call * to {@link #getSecret(String, String) getSecret(String, String)} to get its value, and then prints it out.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.listSecrets} + * + *
+     * secretAsyncClient.listPropertiesOfSecrets()
+     *     .flatMap(secretProperties -> {
+     *         String name = secretProperties.getName();
+     *         String version = secretProperties.getVersion();
+     *
+     *         System.out.printf("Getting secret name: '%s', version: %s%n", name, version);
+     *         return secretAsyncClient.getSecret(name, version);
+     *     })
+     *     .subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
+     *         secretResponse.getName(), secretResponse.getValue()));
+     * 
+ * * * @return A {@link PagedFlux} containing {@link SecretProperties properties} of all the secrets in the vault. */ @@ -811,7 +987,13 @@ private Mono> listSecretsFirstPage(Context conte *

Lists the deleted secrets in the key vault. Subscribes to the call asynchronously and prints out the * recovery id of each deleted secret when a response is received.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.listDeletedSecrets} + * + *
+     * secretAsyncClient.listDeletedSecrets()
+     *     .subscribe(deletedSecretResponse ->  System.out.printf("Deleted Secret's Recovery Id %s %n",
+     *         deletedSecretResponse.getRecoveryId()));
+     * 
+ * * * @return A {@link Flux} containing all of the {@link DeletedSecret deleted secrets} in the vault. */ @@ -881,7 +1063,17 @@ private Mono> listDeletedSecretsFirstPage(Context c *

The sample below fetches the all the versions of the given secret. For each version retrieved, makes a call * to {@link #getSecret(String, String) getSecret(String, String)} to get the version's value, and then prints it out.

* - * {@codesnippet com.azure.keyvault.secrets.secretclient.listSecretVersions#string} + * + *
+     * secretAsyncClient.listPropertiesOfSecretVersions("secretName")
+     *     .flatMap(secretProperties -> {
+     *         System.out.println("Get secret value for version: " + secretProperties.getVersion());
+     *         return secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion());
+     *     })
+     *     .subscribe(secret -> System.out.printf("Received secret with name %s and type %s%n",
+     *         secret.getName(), secret.getValue()));
+     * 
+ * * * @param name The name of the secret. * @return A {@link PagedFlux} containing {@link SecretProperties properties} of all the versions of the specified diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java index e63f80b3ec13c..c2fab281c3a30 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java @@ -24,7 +24,15 @@ * Vault. * *

Construct the sync client

- * {@codesnippet com.azure.security.keyvault.secretclient.sync.construct} + * + *
+ * SecretClient secretClient = new SecretClientBuilder()
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .vaultUrl("https://myvault.vault.azure.net/")
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .buildClient();
+ * 
+ * * * @see SecretClientBuilder * @see PagedIterable @@ -61,7 +69,15 @@ public String getVaultUrl() { *

Code sample

*

Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.

- * {@codesnippet com.azure.security.keyvault.secretclient.setSecret#secret} + * + *
+     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue")
+     *     .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)));
+     * KeyVaultSecret returnedSecret = secretClient.setSecret(newSecret);
+     * System.out.printf("Secret is created with name %s and value %s%n", returnedSecret.getName(),
+     *     returnedSecret.getValue());
+     * 
+ * * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret#getName() secret.name} and {@link KeyVaultSecret#getValue() secret.value} cannot be @@ -84,7 +100,12 @@ public KeyVaultSecret setSecret(KeyVaultSecret secret) { *

Code sample

*

Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.

- * {@codesnippet com.azure.security.keyvault.secretclient.setSecret#string-string} + * + *
+     * KeyVaultSecret secret = secretClient.setSecret("secretName", "secretValue");
+     * System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue());
+     * 
+ * * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. @@ -104,7 +125,14 @@ public KeyVaultSecret setSecret(String name, String value) { *

Code sample

*

Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.

- * {@codesnippet com.azure.security.keyvault.secretclient.setSecretWithResponse#secret-Context} + * + *
+     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue")
+     *          .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)));
+     * KeyVaultSecret secret = secretClient.setSecretWithResponse(newSecret, new Context(key1, value1)).getValue();
+     * System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue());
+     * 
+ * * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. @@ -124,7 +152,14 @@ public Response setSecretWithResponse(KeyVaultSecret secret, Con * *

Code sample

*

Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.

- * {@codesnippet com.azure.security.keyvault.secretclient.getSecret#string-string} + * + *
+     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * KeyVaultSecret secretWithVersion = secretClient.getSecret("secretName", secretVersion);
+     * System.out.printf("Secret is returned with name %s and value %s%n",
+     *     secretWithVersion.getName(), secretWithVersion.getValue());
+     * 
+ * * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this call is @@ -145,7 +180,13 @@ public KeyVaultSecret getSecret(String name, String version) { * *

Code sample

*

Gets the latest version of the secret in the key vault. Prints out the details of the returned secret.

- * {@codesnippet com.azure.security.keyvault.secretclient.getSecret#string} + * + *
+     * KeyVaultSecret secretWithoutVersion = secretClient.getSecret("secretName", secretVersion);
+     * System.out.printf("Secret is returned with name %s and value %s%n",
+     *     secretWithoutVersion.getName(), secretWithoutVersion.getValue());
+     * 
+ * * * @param name The name of the secret. * @return The requested {@link KeyVaultSecret}. @@ -163,7 +204,15 @@ public KeyVaultSecret getSecret(String name) { * *

Code sample

*

Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.

- * {@codesnippet com.azure.security.keyvault.secretclient.getSecretWithResponse#string-string-Context} + * + *
+     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
+     * KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse("secretName", secretVersion,
+     *     new Context(key2, value2)).getValue();
+     * System.out.printf("Secret is returned with name %s and value %s%n",
+     *     secretWithVersion.getName(), secretWithVersion.getValue());
+     * 
+ * * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent @@ -190,7 +239,17 @@ public Response getSecretWithResponse(String name, String versio *

Code sample

*

Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key vault. *

- * {@codesnippet com.azure.security.keyvault.secretclient.updateSecretPropertiesWithResponse#secretProperties-Context} + * + *
+     * SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties();
+     * secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60));
+     * SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse(secretProperties,
+     *     new Context(key2, value2)).getValue();
+     * KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretBase.getName());
+     * System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n",
+     *     updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn());
+     * 
+ * * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @param context Additional context that is passed through the HTTP pipeline during the service call. @@ -217,7 +276,16 @@ public Response updateSecretPropertiesWithResponse(SecretPrope *

Code sample

*

Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key * vault.

- * {@codesnippet com.azure.security.keyvault.secretclient.updateSecretProperties#secretProperties} + * + *
+     * SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties();
+     * secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60));
+     * SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secretProperties);
+     * KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretProperties.getName());
+     * System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n",
+     *     updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn());
+     * 
+ * * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @return The {@link SecretProperties updated secret}. @@ -241,7 +309,23 @@ public SecretProperties updateSecretProperties(SecretProperties secretProperties *

Code sample

*

Deletes the secret from a soft-delete enabled key vault. Prints out the recovery id of the deleted secret * returned in the response.

- * {@codesnippet com.azure.security.keyvault.secretclient.deleteSecret#String} + * + *
+     * SyncPoller<DeletedSecret, Void> deleteSecretPoller = secretClient.beginDeleteSecret("secretName");
+     *
+     * // Deleted Secret is accessible as soon as polling begins.
+     * PollResponse<DeletedSecret> deleteSecretPollResponse = deleteSecretPoller.poll();
+     *
+     * // Deletion date only works for a SoftDelete-enabled Key Vault.
+     * System.out.println("Deleted Date  %s" + deleteSecretPollResponse.getValue()
+     *     .getDeletedOn().toString());
+     * System.out.printf("Deleted Secret's Recovery Id %s", deleteSecretPollResponse.getValue()
+     *     .getRecoveryId());
+     *
+     * // Secret is being deleted on server.
+     * deleteSecretPoller.waitForCompletion();
+     * 
+ * * * @param name The name of the secret to be deleted. * @return A {@link SyncPoller} to poll on and retrieve the {@link DeletedSecret deleted secret}. @@ -260,7 +344,12 @@ public SyncPoller beginDeleteSecret(String name) { *

Code sample

*

Gets the deleted secret from the key vault enabled for soft-delete. Prints out the details of the * deleted secret returned in the response.

- * {@codesnippet com.azure.security.keyvault.secretclient.getDeletedSecret#string} + * + *
+     * DeletedSecret deletedSecret = secretClient.getDeletedSecret("secretName");
+     * System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId());
+     * 
+ * * * @param name The name of the deleted secret. * @return The {@link DeletedSecret deleted secret}. @@ -279,7 +368,13 @@ public DeletedSecret getDeletedSecret(String name) { *

Code sample

*

Gets the deleted secret from the key vault enabled for soft-delete. Prints out the details of the * deleted secret returned in the response.

- * {@codesnippet com.azure.security.keyvault.secretclient.getDeletedSecretWithResponse#string-Context} + * + *
+     * DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse("secretName",
+     *     new Context(key2, value2)).getValue();
+     * System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId());
+     * 
+ * * * @param name The name of the deleted secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. @@ -301,7 +396,11 @@ public Response getDeletedSecretWithResponse(String name, Context *

Purges the deleted secret from the key vault enabled for soft-delete. Prints out the status code from * the server response.

* - * {@codesnippet com.azure.security.keyvault.secretclient.purgeDeletedSecret#string} + * + *
+     * secretClient.purgeDeletedSecret("secretName");
+     * 
+ * * * @param name The name of the secret. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. @@ -319,7 +418,13 @@ public void purgeDeletedSecret(String name) { *

Code sample

*

Purges the deleted secret from the key vault enabled for soft-delete. Prints out the status code from * the server response.

- * {@codesnippet com.azure.security.keyvault.secretclient.purgeDeletedSecretWithResponse#string-Context} + * + *
+     * Response<Void> purgeResponse = secretClient.purgeDeletedSecretWithResponse("secretName",
+     *     new Context(key1, value1));
+     * System.out.printf("Purge Status Code: %d", purgeResponse.getStatusCode());
+     * 
+ * * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. @@ -339,7 +444,20 @@ public Response purgeDeletedSecretWithResponse(String name, Context contex *

Code sample

*

Recovers the deleted secret from the key vault enabled for soft-delete. Prints out the details of the * recovered secret returned in the response.

- * {@codesnippet com.azure.security.keyvault.secretclient.recoverDeletedSecret#String} + * + *
+     * SyncPoller<KeyVaultSecret, Void> recoverSecretPoller =
+     *     secretClient.beginRecoverDeletedSecret("deletedSecretName");
+     *
+     * // Deleted Secret can be accessed as soon as polling is in progress.
+     * PollResponse<KeyVaultSecret> recoveredSecretPollResponse = recoverSecretPoller.poll();
+     * System.out.println("Recovered Key Name %s" + recoveredSecretPollResponse.getValue().getName());
+     * System.out.printf("Recovered Key's Id %s", recoveredSecretPollResponse.getValue().getId());
+     *
+     * // Key is being recovered on server.
+     * recoverSecretPoller.waitForCompletion();
+     * 
+ * * * @param name The name of the deleted secret to be recovered. * @return A {@link SyncPoller} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. @@ -358,7 +476,12 @@ public SyncPoller beginRecoverDeletedSecret(String name) { *

Code sample

*

Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response

- * {@codesnippet com.azure.security.keyvault.secretclient.backupSecret#string} + * + *
+     * byte[] secretBackup = secretClient.backupSecret("secretName");
+     * System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length);
+     * 
+ * * * @param name The name of the secret. * @return A {@link Response} whose {@link Response#getValue() value} contains the backed up secret blob. @@ -378,7 +501,13 @@ public byte[] backupSecret(String name) { *

Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response

* - * {@codesnippet com.azure.security.keyvault.secretclient.backupSecretWithResponse#string-Context} + * + *
+     * byte[] secretBackup = secretClient.backupSecretWithResponse("secretName",
+     *     new Context(key1, value1)).getValue();
+     * System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length);
+     * 
+ * * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. @@ -399,7 +528,15 @@ public Response backupSecretWithResponse(String name, Context context) { *

Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.

* - * {@codesnippet com.azure.security.keyvault.secretclient.restoreSecret#byte} + * + *
+     * // Pass the secret backup byte array of the secret to be restored.
+     * byte[] secretBackupByteArray = {};
+     * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup(secretBackupByteArray);
+     * System.out
+     *     .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue());
+     * 
+ * * * @param backup The backup blob associated with the secret. * @return A {@link Response} whose {@link Response#getValue() value} contains the {@link KeyVaultSecret restored secret}. @@ -418,7 +555,16 @@ public KeyVaultSecret restoreSecretBackup(byte[] backup) { *

Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.

* - * {@codesnippet com.azure.security.keyvault.secretclient.restoreSecretWithResponse#byte-Context} + * + *
+     * // Pass the secret backup byte array of the secret to be restored.
+     * byte[] secretBackupByteArray = {};
+     * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse(secretBackupByteArray,
+     *     new Context(key2, value2)).getValue();
+     * System.out
+     *     .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue());
+     * 
+ * * * @param backup The backup blob associated with the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. @@ -440,14 +586,34 @@ public Response restoreSecretBackupWithResponse(byte[] backup, C * {@link #getSecret(String, String) getSecret(String, String)}. This gets the {@link KeyVaultSecret secret} and the * value of its latest version.

* - * {@codesnippet com.azure.security.keyvault.secretclient.listSecrets} + * + *
+     * for (SecretProperties secret : secretClient.listPropertiesOfSecrets()) {
+     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
+     *     System.out.printf("Received secret with name %s and value %s",
+     *         secretWithValue.getName(), secretWithValue.getValue());
+     * }
+     * 
+ * * *

Iterate over secrets by page

*

The snippet below loops over each {@link SecretProperties secret} by page and calls * {@link #getSecret(String, String) getSecret(String, String)}. This gets the {@link KeyVaultSecret secret} and the * value of its latest version.

* - * {@codesnippet com.azure.security.keyvault.secretclient.listSecrets.iterableByPage} + * + *
+     * secretClient.listPropertiesOfSecrets().iterableByPage().forEach(resp -> {
+     *     System.out.printf("Response headers are %s. Url %s  and status code %d %n", resp.getHeaders(),
+     *         resp.getRequest().getUrl(), resp.getStatusCode());
+     *     resp.getItems().forEach(value -> {
+     *         KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion());
+     *         System.out.printf("Received secret with name %s and value %s",
+     *             secretWithValue.getName(), secretWithValue.getValue());
+     *     });
+     * });
+     * 
+ * * * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. The * {@link SecretProperties} contains all the information about the secret, except its value. @@ -466,7 +632,15 @@ public PagedIterable listPropertiesOfSecrets() { *

The snippet below loops over each {@link SecretProperties secret} and calls * {@link #getSecret(String, String) getSecret(String, String)}. This gets the {@link KeyVaultSecret secret} and the * value of its latest version.

- * {@codesnippet com.azure.security.keyvault.secretclient.listSecrets#Context} + * + *
+     * for (SecretProperties secret : secretClient.listPropertiesOfSecrets(new Context(key1, value2))) {
+     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
+     *     System.out.printf("Received secret with name %s and value %s",
+     *         secretWithValue.getName(), secretWithValue.getValue());
+     * }
+     * 
+ * * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. {@link SecretProperties} @@ -483,7 +657,13 @@ public PagedIterable listPropertiesOfSecrets(Context context) * *

Code sample

*

Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.

- * {@codesnippet com.azure.security.keyvault.secretclient.listDeletedSecrets#Context} + * + *
+     * for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets(new Context(key1, value2))) {
+     *     System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId());
+     * }
+     * 
+ * * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. @@ -499,12 +679,28 @@ public PagedIterable listDeletedSecrets(Context context) { * *

Iterate over secrets

*

Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.

- * {@codesnippet com.azure.security.keyvault.secretclient.listDeletedSecrets} + * + *
+     * for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets()) {
+     *     System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId());
+     * }
+     * 
+ * * *

Iterate over secrets by page

*

Iterate over Lists the deleted secrets by page in the key vault and for each deleted secret prints out its * recovery id.

- * {@codesnippet com.azure.security.keyvault.secretclient.listDeletedSecrets.iterableByPage} + * + *
+     * secretClient.listDeletedSecrets().iterableByPage().forEach(resp -> {
+     *     System.out.printf("Got response headers . Url: %s, Status code: %d %n",
+     *         resp.getRequest().getUrl(), resp.getStatusCode());
+     *     resp.getItems().forEach(value -> {
+     *         System.out.printf("Deleted secret's recovery Id %s", value.getRecoveryId());
+     *     });
+     * });
+     * 
+ * * * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @@ -521,7 +717,15 @@ public PagedIterable listDeletedSecrets() { *

Code sample

*

The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link #getSecret(String, String) getSecret(String, String)} to get the version's value, and then prints it out.

- * {@codesnippet com.azure.security.keyvault.secretclient.listSecretVersions#string} + * + *
+     * for (SecretProperties secret : secretClient.listPropertiesOfSecretVersions("secretName")) {
+     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
+     *     System.out.printf("Received secret's version with name %s and value %s",
+     *         secretWithValue.getName(), secretWithValue.getValue());
+     * }
+     * 
+ * * * @param name The name of the secret. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the vault. @@ -542,14 +746,36 @@ public PagedIterable listPropertiesOfSecretVersions(String nam *

Code sample

*

The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link #getSecret(String, String) getSecret(String, String)} to get the version's value, and then prints it out.

- * {@codesnippet com.azure.security.keyvault.secretclient.listSecretVersions#string-Context} + * + *
+     * for (SecretProperties secret : secretClient
+     *     .listPropertiesOfSecretVersions("secretName", new Context(key1, value2))) {
+     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
+     *     System.out.printf("Received secret's version with name %s and value %s",
+     *         secretWithValue.getName(), secretWithValue.getValue());
+     * }
+     * 
+ * * *

Iterate over secret versions by page

*

The sample below iterates over each {@link SecretProperties secret} by each page and calls * {@link SecretClient#getSecret(String, String)}. This will return the {@link KeyVaultSecret secret} with the * corresponding version's value.

* - * {@codesnippet com.azure.security.keyvault.secretclient.listSecretVersions#string-Context-iterableByPage} + * + *
+     * secretClient.listPropertiesOfSecretVersions("secretName", new Context(key1, value2))
+     *             .iterableByPage().forEach(resp -> {
+     *                 System.out.printf("Got response headers . Url: %s, Status code: %d %n",
+     *                     resp.getRequest().getUrl(), resp.getStatusCode());
+     *                 resp.getItems().forEach(value -> {
+     *                     KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion());
+     *                     System.out.printf("Received secret's version with name %s and value %s",
+     *                         secretWithValue.getName(), secretWithValue.getValue());
+     *                 });
+     *             });
+     * 
+ * * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java index dff09bd24870c..b25c735b9bde7 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java @@ -42,21 +42,56 @@ *

The minimal configuration options required by {@link SecretClientBuilder secretClientBuilder} to build * {@link SecretAsyncClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

* - * {@codesnippet com.azure.security.keyvault.secrets.async.secretclient.construct} + * + *
+ * SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .vaultUrl("https://myvault.vault.azure.net/")
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .buildAsyncClient();
+ * 
+ * * *

Samples to construct the sync client

- * {@codesnippet com.azure.security.keyvault.secretclient.sync.construct} + * + *
+ * SecretClient secretClient = new SecretClientBuilder()
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .vaultUrl("https://myvault.vault.azure.net/")
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .buildClient();
+ * 
+ * * *

The {@link HttpLogDetailLevel log detail level}, multiple custom {@link HttpLoggingPolicy policies} and custom * {@link HttpClient http client} can be optionally configured in the {@link SecretClientBuilder}.

* - * {@codesnippet com.azure.security.keyvault.secrets.async.secretclient.withhttpclient.instantiation} + * + *
+ * SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
+ *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .credential(new DefaultAzureCredentialBuilder().build())
+ *     .httpClient(HttpClient.createDefault())
+ *     .buildAsyncClient();
+ * 
+ * * *

Alternatively, custom {@link HttpPipeline http pipeline} with custom {@link HttpPipelinePolicy} policies and * {@link String vaultUrl} * can be specified. It provides finer control over the construction of {@link SecretAsyncClient client}

* - * {@codesnippet com.azure.security.keyvault.secrets.async.secretclient.pipeline.instantiation} + * + *
+ * HttpPipeline pipeline = new HttpPipelineBuilder()
+ *     .policies(new KeyVaultCredentialPolicy(credential), new RetryPolicy())
+ *     .build();
+ * SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
+ *     .pipeline(pipeline)
+ *     .vaultUrl("https://myvault.azure.net/")
+ *     .buildAsyncClient();
+ * 
+ * * * @see SecretClient * @see SecretAsyncClient diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretServiceVersion.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretServiceVersion.java index 3e95d7e96a13b..ee46d3198a984 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretServiceVersion.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretServiceVersion.java @@ -9,9 +9,24 @@ * The versions of Azure Key Vault Secret supported by this client library. */ public enum SecretServiceVersion implements ServiceVersion { + /** + * Service version {@code 7.0}. + */ V7_0("7.0"), + + /** + * Service version {@code 7.1}. + */ V7_1("7.1"), + + /** + * Service version {@code 7.2}. + */ V7_2("7.2"), + + /** + * Service version {@code 7.3-preview}. + */ V7_3_PREVIEW("7.3-preview"); private final String version; diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ReadmeSamples.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ReadmeSamples.java new file mode 100644 index 0000000000000..0926105b75545 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ReadmeSamples.java @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +@SuppressWarnings("unused") +public class ReadmeSamples { + private final SecretClient secretClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + public void createSecretClient() { + // BEGIN: readme-sample-createSecretClient + SecretClient secretClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createSecretClient + } + + public void createSecret() { + // BEGIN: readme-sample-createSecret + KeyVaultSecret secret = secretClient.setSecret("", ""); + System.out.printf("Secret created with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); + // END: readme-sample-createSecret + } + + public void retrieveSecret() { + // BEGIN: readme-sample-retrieveSecret + KeyVaultSecret secret = secretClient.getSecret(""); + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); + // END: readme-sample-retrieveSecret + } + + public void updateSecret() { + // BEGIN: readme-sample-updateSecret + // Get the secret to update. + KeyVaultSecret secret = secretClient.getSecret(""); + // Update the expiry time of the secret. + secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); + SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secret.getProperties()); + System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn()); + // END: readme-sample-updateSecret + } + + public void deleteSecret() { + // BEGIN: readme-sample-deleteSecret + SyncPoller deletedSecretPoller = secretClient.beginDeleteSecret(""); + + // Deleted secret is accessible as soon as polling begins. + PollResponse deletedSecretPollResponse = deletedSecretPoller.poll(); + + // Deletion date only works for a SoftDelete-enabled Key Vault. + System.out.printf("Deletion date: %s%n", deletedSecretPollResponse.getValue().getDeletedOn()); + + // Secret is being deleted on server. + deletedSecretPoller.waitForCompletion(); + // END: readme-sample-deleteSecret + } + + public void listSecrets() { + // BEGIN: readme-sample-listSecrets + // List operations don't return the secrets with value information. So, for each returned secret we call getSecret to + // get the secret with its value information. + for (SecretProperties secretProperties : secretClient.listPropertiesOfSecrets()) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secretProperties.getName(), secretProperties.getVersion()); + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretWithValue.getName(), + secretWithValue.getValue()); + } + // END: readme-sample-listSecrets + } + + public void createSecretAsync() { + // BEGIN: readme-sample-createSecretAsync + secretAsyncClient.setSecret("", "") + .subscribe(secret -> System.out.printf("Created secret with name \"%s\" and value \"%s\"%n", + secret.getName(), secret.getValue())); + // END: readme-sample-createSecretAsync + } + + public void retrieveSecretAsync() { + // BEGIN: readme-sample-retrieveSecretAsync + secretAsyncClient.getSecret("") + .subscribe(secret -> System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", + secret.getName(), secret.getValue())); + // END: readme-sample-retrieveSecretAsync + } + + public void updateSecretAsync() { + // BEGIN: readme-sample-updateSecretAsync + secretAsyncClient.getSecret("") + .flatMap(secret -> { + // Update the expiry time of the secret. + secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); + return secretAsyncClient.updateSecretProperties(secret.getProperties()); + }).subscribe(updatedSecretProperties -> + System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn())); + // END: readme-sample-updateSecretAsync + } + + public void deleteSecretAsync() { + // BEGIN: readme-sample-deleteSecretAsync + secretAsyncClient.beginDeleteSecret("") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deleted secret name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Deleted secret value: %s%n", pollResponse.getValue().getValue()); + }); + // END: readme-sample-deleteSecretAsync + } + + public void listSecretsAsync() { + // BEGIN: readme-sample-listSecretsAsync + // The List secrets operation returns secrets without their value, so for each secret returned we call `getSecret` + // to get its value as well. + secretAsyncClient.listPropertiesOfSecrets() + .flatMap(secretProperties -> + secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion())) + .subscribe(secretResponse -> + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretResponse.getName(), + secretResponse.getValue())); + // END: readme-sample-listSecretsAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + secretClient.getSecret(""); + } catch (ResourceNotFoundException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } +} diff --git a/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml b/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml index d6777e47c4f91..0730479c5e1c5 100644 --- a/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml +++ b/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml @@ -17,6 +17,12 @@ JCA Provider for Azure Key Vault Test The Java Crypto Architecture (JCA) Provider for Azure Key Vault Test + + false + + + + com.azure