diff --git a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md deleted file mode 100644 index faf45f9669fb..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md +++ /dev/null @@ -1,610 +0,0 @@ -# Release History - -## 4.7.0-beta.1 (Unreleased) - -### Features Added -- Added support for pre-backup and pre-restore operations in `KeyVaultBackupClient` and `KeyVaultBackupAsyncClient`. These are long-running operations that check whether it is possible to perform a full key backup or a full key restore from a backup. - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 4.6.4 (2025-03-24) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-json` from `1.4.0` to version `1.5.0`. -- Upgraded `azure-core-http-netty` from `1.15.10` to version `1.15.11`. -- Upgraded `azure-core` from `1.55.2` to version `1.55.3`. - - -## 4.6.3 (2025-03-04) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. -- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. -- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. - -## 4.6.2 (2025-01-14) - -### Bugs Fixed -- Fixed issue where certain `toString()` calls could cause a `NullPointerException`. ([#43776](https://github.com/Azure/azure-sdk-for-java/pull/43776)) - -## 4.6.1 (2024-12-04) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.53.0` to version `1.54.1`. -- Upgraded `azure-core-http-netty` from `1.15.5` to version `1.15.7`. - -## 4.6.0 (2024-10-15) - -## Features Added -- Added support for Continuous Access Evaluation (CAE). ([#41814](https://github.com/Azure/azure-sdk-for-java/pull/41814)) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.52.0` to version `1.53.0`. -- Upgraded `azure-core-http-netty` from `1.15.4` to version `1.15.5`. - -## 4.5.8 (2024-09-27) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-json` from `1.2.0` to version `1.3.0`. -- Upgraded `azure-core-http-netty` from `1.15.3` to version `1.15.4`. -- Upgraded `azure-core` from `1.51.0` to version `1.52.0`. - -## 4.5.7 (2024-08-24) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.50.0` to version `1.51.0`. -- Upgraded `azure-core-http-netty` from `1.15.2` to version `1.15.3`. - -## 4.5.6 (2024-07-29) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.49.1` to version `1.50.0`. -- Upgraded `azure-json` from `1.1.0` to version `1.2.0`. -- Upgraded `azure-core-http-netty` from `1.15.1` to version `1.15.2`. - -## 4.5.5 (2024-06-27) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.49.0` to version `1.49.1`. -- Upgraded `azure-core-http-netty` from `1.15.0` to version `1.15.1`. - -## 4.5.4 (2024-05-13) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.48.0` to version `1.49.0`. -- Upgraded `azure-core-http-netty` from `1.14.2` to version `1.15.0`. - -## 4.5.3 (2024-04-30) - -### Other Changes - -- No changes but only upgrade version to fix Microsoft Doc. - -## 4.5.2 (2024-04-23) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.47.0` to version `1.48.0`. -- Upgraded `azure-core-http-netty` from `1.14.1` to version `1.14.2`. - -## 4.5.1 (2024-03-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.46.0` to version `1.47.0`. -- Upgraded `azure-core-http-netty` from `1.14.0` to version `1.14.1`. - -## 4.5.0 (2024-02-22) -Changes when compared to the last stable release (`4.4.3`) include: - -### Features Added -- Added support for service version `7.5`. -- Managed Identity can now be used in place of a SAS token to access the blob storage resource when performing backup and restore operations using a `KeyVaultBackupClient` or `KeyVaultBackupAsyncClient`. This is now the default behavior if a `null` SAS token is provided to the `beginBackup()`, `beginRestore()` or `beginSelectiveRestore()` methods. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.45.1` to version `1.46.0`. -- Upgraded `azure-core-http-netty` from `1.13.11` to version `1.14.0`. - -## 4.4.3 (2023-12-04) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.10` to version `1.13.11`. -- Upgraded `azure-core` from `1.45.0` to version `1.45.1`. - -## 4.4.2 (2023-11-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.44.1` to version `1.45.0`. -- Upgraded `azure-core-http-netty` from `1.13.9` to version `1.13.10`. - -## 4.5.0-beta.1 (2023-11-09) - -### Features Added -- Added support for service version `7.5-preview.1`. -- Managed Identity can now be used in place of a SAS token to access the blob storage resource when performing backup and restore operations using a `KeyVaultBackupClient` or `KeyVaultBackupAsyncClient`. This is now the default behavior if a `null` SAS token is provided to the `beginBackup()`, `beginRestore()` or `beginSelectiveRestore()` methods. - -#### Dependency Updates -- Upgraded `azure-core` from `1.44.1` to version `1.45.0`. -- Upgraded `azure-core-http-netty` from `1.13.9` to version `1.13.10`. - -## 4.4.1 (2023-10-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.7` to version `1.13.9`. -- Upgraded `azure-core` from `1.43.0` to version `1.44.1`. - -## 4.4.0 (2023-09-25) - -### Other Changes -- Explicitly added a `values()` method to all `ExpandableStringEnum` models: - - `KeyVaultDataAction` - - `KeyVaultRoleDefinitionType` - - `KeyVaultRoleScope` - - `KeyVaultRoleType` - - `KeyVaultSettingType` - Functionality remains the same as the aforementioned method simply calls the implementation in the parent class. -- Migrate test recordings to assets repo. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.42.0` to version `1.43.0`. -- Upgraded `azure-core-http-netty` from `1.13.6` to version `1.13.7`. -- Upgraded `azure-json` from `1.0.1` to version `1.1.0`. - -## 4.3.5 (2023-08-21) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.41.0` to version `1.42.0`. -- Upgraded `azure-core-http-netty` from `1.13.5` to version `1.13.6`. - -## 4.3.4 (2023-07-25) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.40.0` to version `1.41.0`. -- Upgraded `azure-core-http-netty` from `1.13.4` to version `1.13.5`. - -## 4.3.3 (2023-06-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.39.0` to version `1.40.0`. -- Upgraded `azure-core-http-netty` from `1.13.3` to version `1.13.4`. - -## 4.3.2 (2023-05-23) - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.2` to version `1.13.3`. -- Upgraded `azure-core` from `1.38.0` to version `1.39.0`. - -## 4.3.1 (2023-04-20) - -### Other Changes - -- Test proxy server migration. -- Made all logger instances static. - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.1` to version `1.13.2`. -- Upgraded `azure-core` from `1.37.0` to version `1.38.0`. - -## 4.3.0 (2023-03-18) - -### Features Added -- Added support for service version `7.4`. -- Added `KeyVaultSettingsClient` and `KeyVaultSettingsAsyncClient` to get and update Managed HSM settings. - -### Breaking Changes -> These changes do not impact the API of stable versions such as `4.2.4`. Only code written against a beta version such as `4.3.0-beta.1` may be affected. -- Removed support for service version `7.4-preview.1`. -- Removed `KeyVaultSetting.asString()`, as well as the `KeyVaultSetting(String, String, KeyVaultSettingType)` constructor. - -### Other Changes -- Upgraded `azure-core-http-netty` from `1.13.0` to version `1.13.1`. -- Upgraded `azure-core` from `1.36.0` to version `1.37.0`. - -## 4.2.4 (2023-02-16) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.12.8` to version `1.13.0`. -- Upgraded `azure-core` from `1.35.0` to version `1.36.0`. - -## 4.2.3 (2023-01-09) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.34.0` to version `1.35.0`. -- Upgraded `azure-core-http-netty` from `1.12.7` to version `1.12.8`. - -## 4.3.0-beta.1 (2022-11-11) - -### Features Added -- Added `KeyVaultSettingsClient` and `KeyVaultSettingsAsyncClient` to get and update Managed HSM settings. -- Added support for service version `7.4-preview.1`. - -## 4.2.2 (2022-11-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.33.0` to version `1.34.0`. -- Upgraded `azure-core-http-netty` from `1.12.6` to version `1.12.7`. - -## 4.2.1 (2022-10-17) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.32.0` to version `1.33.0`. -- Upgraded `azure-core-http-netty` from `1.12.5` to version `1.12.6`. - -## 4.2.0 (2022-09-20) - -### Breaking Changes -- Made it so that we verify that the challenge resource matches the vault domain by default. This should affect few customers who can use the `disableChallengeResourceVerification()` method in client builders to disable this functionality. See https://aka.ms/azsdk/blog/vault-uri for more information. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.31.0` to version `1.32.0`. -- Upgraded `azure-core-http-netty` from `1.12.4` to version `1.12.5`. - -## 4.1.5 (2022-08-15) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.31.0`. -- Upgraded `azure-core-http-netty` dependency to `1.12.4`. - -## 4.1.4 (2022-07-06) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.30.0`. -- Upgraded `azure-core-http-netty` dependency to `1.12.3`. - -## 4.1.3 (2022-06-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.29.1`. -- Upgraded `azure-core-http-netty` dependency to `1.12.2`. - -## 4.1.2 (2022-05-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.28.0`. -- Upgraded `azure-core-http-netty` dependency to `1.12.0`. - -## 4.1.1 (2022-04-08) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.27.0`. -- Upgraded `azure-core-http-netty` dependency to `1.11.9`. - -## 4.1.0 (2022-03-31) - -### Features Added -- Added support for service version `7.3`. -- Added the following values to `KeyVaultDataAction`: - - `WRITE_ROLE_DEFINITION` - - `DELETE_ROLE_DEFINITION` - - `RELEASE_KEY` - - `DOWNLOAD_HSM_SECURITY_DOMAIN_STATUS` - - `RANDOM_NUMBERS_GENERATE` -- Implemented new traits (micro-interfaces) in `KeyVaultAccessControlClientBuilder` and `KeyVaultBackupClientBuilder`. This makes the experience of using client builders more consistent across libraries in the Azure SDK for Java. - -## 4.0.8 (2022-03-17) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.26.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.8` - -## 4.1.0-beta.5 (2022-02-11) - -### Features added -- Implemented new traits (micro-interfaces) in `KeyVaultAccessControlClientBuilder` and `KeyVaultBackupClientBuilder`. This makes the experience of using client builders more consistent across libraries in the Azure SDK for Java. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.25.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.7` - -## 4.0.7 (2022-02-11) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.25.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.7` - -## 4.1.0-beta.4 (2022-01-13) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.24.1` -- Upgraded `azure-core-http-netty` dependency to `1.11.6` - -## 4.0.6 (2022-01-12) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.24.1` -- Upgraded `azure-core-http-netty` dependency to `1.11.6` - -## 4.1.0-beta.3 (2021-11-12) - -### Features Added - -- Added support for multi-tenant authentication in clients. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.22.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.2` - -## 4.0.5 (2021-11-12) - -### Features Added - -- Added support for multi-tenant authentication in clients. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.22.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.2` - -## 4.1.0-beta.2 (2021-10-07) - -### Bugs Fixed -- Fixed an issue that made clients send unnecessary unauthorized requests to obtain a bearer challenge from the service even when already possessing a valid bearer token. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.21.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.1` - -## 4.0.4 (2021-10-06) - -### Bugs Fixed -- Fixed an issue that made clients send unnecessary unauthorized requests to obtain a bearer challenge from the service even when already possessing a valid bearer token. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.21.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.1` - -## 4.1.0-beta.1 (2021-09-10) - -### Features Added -- Added support for service version `7.3-preview`. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.20.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.0` - -## 4.0.3 (2021-09-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.20.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.0` - -## 4.0.2 (2021-08-12) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.19.0` -- Upgraded `azure-core-http-netty` dependency to `1.10.2` - -## 4.0.1 (2021-07-08) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.18.0` -- Upgraded `azure-core-http-netty` dependency to `1.10.1` - -## 4.0.0 (2021-06-17) -- Initial release of `KeyVaultAccessControlClient` and `KeyVaultAccessControlAsyncClient` to manage role assignments and definitions for Managed HSM. -- Initial release of `KeyVaultBackupClient` and `KeyVaultBackupAsyncClient` to backup and restore Managed HSM. - -### Features Added -- Changed default service version to `7.2`. -- Added `KeyVaultKeyIdentifier` to parse key URLs. -- Added local-only support for `CryptographyClient` and `CryptographyAsyncClient` by providing a `JsonWebKey` during client creation. -- Added `KeyType.OCT-HSM` to support oct-HSM key operations to support Managed HSM. -- Added the `CreateOctKeyOptions` class and associated `createOctKey()` methods. -- Added AES-GCM and AES-CBC support for encrypting and decrypting, including new `Encrypt` and `Decrypt` overloads. -- Added the ability to set a public exponent on RSA keys during creation. -- Made all getters for properties of a `JsonWebKey` public. - -### Changes since 4.0.0-beta.7 - -#### Bug Fixes -- Ensured that `RetryPolicy` and `HttpLogOptions` use a default implementation when creating Key Vault clients if not set or set to `null`. - -#### Breaking Changes -- Renamed `beginSelectiveRestore()` to `beginSelectiveKeyRestore()` in `KeyVaultBackupClient` and `KeyVaultBackupAsyncClient`. Made the aforementioned operation return the new `KeyVaultSelectiveKeyRestoreOperation` instead of a `KeyVaultRestoreOperation`. -- Changed the final return type of `beginRestore()` and `beginSelectiveKeyRestore()`'s poller types from `Void` to the new `KeyVaultRestoreResult` and `KeyVaultSelectiveKeyRestoreResult`, respectively. -- `KeyVaultBackupClient` and `KeyVaultBackupAsyncClient`'s long-running operations now throw a `RuntimeException` when cancellation is attempted, as it is not currently supported. -- Made `KeyVaultRoleDefinition` flat, as opposed to it having a `KeyVaultRoleDefinitionProperties` member with more properties inside of it. -- Moved `roleScope` from `KeyVaultRoleAssignment` to `KeyVaultRoleAssignmentProperties` and renamed it to `scope`. -- Moved `SetRoleDefinitionOptions` from the `options` package to the `models` package. -- Removed `roleType` from `SetRoleDefinitionOptions`. -- Removed service method overloads that take a `pollingInterval`, since `PollerFlux` and `SyncPoller` objects allow for setting this value directly on them. -- Delete methods on the `KeyVaultAccessControlClient` now return a `void` or `Mono` and ignore HTTP `404`s. -- Renamed `jobId` and `getJobId()` to `operationId` and `getOperationId()` in `KeyVaultLongRunningOperation` and its children classes. -- Made the following classes `final`: - - `KeyVaultDataAction` - - `KeyVaultRoleDefinitionType` - - `KeyVaultRoleType` - - `SetRoleDefinitionOptions` - -## 4.0.0-beta.7 (2021-05-15) - -### New features - -- Added support for creating, retrieving, updating and deleting custom role definitions. - -### Breaking Changes - -- Added the public `KeyVaultAdministrationException`, which will be thrown in place of an exception with the same name in the `implementation` package. - -#### Behavioral Changes - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.16.0` -- Upgraded `azure-core-http-netty` dependency to `1.9.2` -- Upgraded `azure-core-http-okhttp` dependency to `1.6.2` -- Upgraded `azure-identity` dependency to `1.3.0` - -## 4.0.0-beta.6 (2021-04-09) - -### New features -- Added support for service version `7.2`. -- Added support to specify whether or not a pipeline policy should be added per call or per retry. - -## 4.0.0-beta.5 (2021-03-12) - -### Changed -- Changed logging level in `onRequest` and `onSuccess` calls for service operations from `INFO` to `VERBOSE`. - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.14.0` -- Upgraded `azure-core-http-netty` dependency to `1.9.0` -- Upgraded `azure-core-http-okhttp` dependency to `1.6.0` -- Upgraded `azure-identity` dependency to `1.2.4` - -## 4.0.0-beta.4 (2021-02-11) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.13.0` -- Upgraded `azure-core-http-netty` dependency to `1.8.0` -- Upgraded `azure-core-http-okhttp` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.2.3` - -## 4.0.0-beta.3 (2020-11-12) - -### New Features -- Added support for passing a `ServiceVersion` in clients and their builders. - -### Breaking Changes -- Removed exposure of `implementation` (internal) package types via `module-info.java` -- Renamed `KeyVaultRoleAssignmentScope` to `KeyVaultRoleScope` to be in line with other languages. -- Changed the `KeyVaultRoleScope` enum from using `URI` to `URL` and added an overload that accepts a `String` representation of a `URL` too. -- Renamed the `scope` property of `KeyVaultRoleAssignment` to `roleScope` to align with the access client APIs. -- Renamed the `name` parameter to `roleAssignmentName` in role assignment-related APIs, as well as its type from `UUID` to `String`. -- Removed APIs for re-hydrating long-running operations as the guidelines regarding such methods are a still a work in progress -- Annotated read-only classes with `@Immutable`. -- Renamed `actions` and `dataActions` to `allowedActions` and `allowedDataActions` in `KeyVaultPermission`. -- Changed the type of `startTime` and `endTime` from `Long` to `OffsetDateTime` in `KeyVaultLongRunningOperation` and its sub-types. -- Renamed `azureStorageBlobContainerUri` to `azureStorageBlobContainerUrl` in `KeyVaultBackupOperation`, as well as its getter method. -- Removed the use of `KeyVaultRoleAssignmentProperties` in clients' public APIs in favor of using the `roleDefinitionId` and `servicePrincipalId` values directly. - -## 4.0.0-beta.2 (2020-10-09) - -### New Features -- Added the new public APIs `getBackupOperation` and `getRestoreOperation` for querying the status of long-running operations in `KeyVaultBackupClient` and `KeyVaultBackupAsyncClient`. -- Added API overloads that allow for passing specific polling intervals for long-running operations: - - `KeyVaultBackupAsyncClient` - - `beginBackup(String, String, Duration)` - - `beginRestore(String, String, String, Duration)` - - `beginSelectiveRestore(String, String, String, String, Duration)` - - `KeyVaultBackupClient` - - `beginBackup(String, String, Duration)` - - `beginRestore(String, String, String, Duration)` - - `beginSelectiveRestore(String, String, String, String, Duration)` -- Added support for `com.azure.core.util.ClientOptions` in client builders. - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.9.0` -- Upgraded `azure-core-http-netty` dependency to `1.6.2` -- Upgraded `azure-core-http-okhttp` dependency to `1.3.2` -- Upgraded `azure-core-test` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.1.3` - -## 4.0.0-beta.1 (2020-09-11) -- Added `KeyVaultBackupClient` and `KeyVaultBackupAsyncClient`. -- Added `KeyVaultAccessControlClient` and `KeyVaultAccessControlAsyncClient`. diff --git a/sdk/keyvault/azure-security-keyvault-administration/README.md b/sdk/keyvault/azure-security-keyvault-administration/README.md deleted file mode 100644 index f77ff8ab65c8..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/README.md +++ /dev/null @@ -1,714 +0,0 @@ -# Azure Key Vault Administration library for Java -Azure Key Vault Managed HSM is a fully-managed, highly-available, single-tenant, standards-compliant cloud service that enables you to safeguard cryptographic keys for your cloud applications using FIPS 140-2 Level 3 validated HSMs. - -The Azure Key Vault Administration library clients support administrative tasks such as full backup/restore and key-level role-based access control (RBAC). - -[Source code][source_code] | [API reference documentation][api_documentation] | [Product documentation][azkeyvault_docs] | [Samples][administration_samples] - -## Getting started -### Include the package -#### Include the BOM file -Please include the `azure-sdk-bom` to your project to take dependency on the General Availability (GA) version of the library. In the following snippet, replace the {bom_version_to_target} placeholder with the version number. To learn more about the BOM, see the [AZURE SDK BOM README](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/boms/azure-sdk-bom/README.md). - -```xml - - - - com.azure - azure-sdk-bom - {bom_version_to_target} - pom - import - - - -``` - -and then include the direct dependency in the dependencies section without the version tag as shown below. - -```xml - - - com.azure - azure-security-keyvault-administration - - -``` - -#### Include direct dependency -If you want to take dependency on a particular version of the library that is not present in the BOM, add the direct dependency to your project as follows. - -[//]: # ({x-version-update-start;com.azure:azure-security-keyvault-administration;current}) -```xml - - com.azure - azure-security-keyvault-administration - 4.7.0-beta.1 - -``` -[//]: # ({x-version-update-end}) - -### Prerequisites -- A [Java Development Kit (JDK)][jdk_link], version 8 or later. - - Here are details about [Java 8 client compatibility with Azure Certificate Authority](https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis). -- An [Azure Subscription][azure_subscription]. -- An existing [Azure Key Vault Managed HSM][azure_keyvault_mhsm]. If you need to create a Managed HSM, you can do so using the Azure CLI by following the steps in [this document][azure_keyvault_mhsm_cli]. - -### Authenticate the client -In order to interact with the Azure Key Vault service, you will need to create an instance of either the [`KeyVaultAccessControlClient`](#create-an-access-control-client)class or the [`KeyVaultBackupClient`](#create-a-backup-client) class, as well as a **vault url** (which you may see as "DNS Name" in the Azure Portal) and a credential object. The examples shown in this document use a credential object named [`DefaultAzureCredential`][default_azure_credential], which is appropriate for most scenarios, including local development and production environments. Additionally, we recommend using a [managed identity][managed_identity] for authentication in production environments. - -You can find more information on different ways of authenticating and their corresponding credential types in the [Azure Identity documentation][azure_identity]. - -#### Create an access control client -Once you perform [the authentication set up that suits you best][default_azure_credential] and replaced **your-managed-hsm-url** with the URL for your key vault, you can create the `KeyVaultAccessControlClient`: - -```java readme-sample-createAccessControlClient -KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); -``` - -> NOTE: For using an asynchronous client use `KeyVaultAccessControlAsyncClient` instead of `KeyVaultAccessControlClient` and call `buildAsyncClient()`. - -#### Create a backup client -Once you perform [the authentication set up that suits you best][default_azure_credential] and replaced **your-managed-hsm-url** with the URL for your key vault, you can create the `KeyVaultBackupClient`: - -```java readme-sample-createBackupClient -KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); -``` - -> NOTE: For using an asynchronous client use `KeyVaultBackupAsyncClient` instead of `KeyVaultBackupClient` and call `buildAsyncClient()`. - -#### Create a settings client -Once you perform [the authentication set up that suits you best][default_azure_credential] and replaced **your-managed-hsm-url** with the URL for your key vault, you can create the `KeyVaultSettingsClient`: - -```java readme-sample-createBackupClient -KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); -``` - -> NOTE: For using an asynchronous client use `KeyVaultSettingsAsyncClient` instead of `KeyVaultSettingsClient` and call `buildAsyncClient()`. - -## Key concepts -### Key Vault Access Control client -The Key Vault Access Control client performs the interactions with the Azure Key Vault service for getting, setting, deleting, and listing role assignments, as well as listing role definitions. Asynchronous (`KeyVaultAccessControlAsyncClient`) and synchronous (`KeyVaultAccessControlClient`) clients exist in the SDK allowing for the selection of a client based on an application's use case. Once you've initialized a role assignment, you can interact with the primary resource types in Key Vault. - -### Role Definition -A role definition is a collection of permissions. It defines the operations that can be performed, such as read, write, and delete. It can also define the operations that are excluded from allowed operations. - -Role definitions can be listed and specified as part of a role assignment. - -### Role Assignment -A role assignment is the association of a role definition to a service principal. They can be created, listed, fetched individually, and deleted. - -### Key Vault Backup client -The Key Vault Backup Client provides both synchronous and asynchronous operations for performing full key backups, full key restores, and selective key restores. Asynchronous (`KeyVaultBackupAsyncClient`) and synchronous (`KeyVaultBackupClient`) clients exist in the SDK allowing for the selection of a client based on an application's use case. - -> 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]. - -### Pre-Backup Operation -A pre-backup operation represents a long-running operation that checks if it is possible to perform a full key backup. - -### Backup Operation -A backup operation represents a long-running operation for a full key backup. - -### Pre-Restore Operation -A pre-restore operation represents a long-running operation that checks if it is possible to perform a full key restore from a backup. - -### Restore Operation -A restore operation represents a long-running operation for both a full key and selective key restore. - -### Key Vault Settings client -The Key Vault Access Control client allows manipulation of an Azure Key Vault account's settings, with operations such as: getting, updating, and listing. Asynchronous (`KeyVaultSettingsAsyncClient`) and synchronous (`KeyVaultSettingsClient`) clients exist in the SDK allowing for the selection of a client based on an application's use case. - -## Access control operations -### Examples -#### Sync API -The following sections provide several code snippets covering some of the most common Azure Key Vault Access Control service tasks, including: -- [List role definitions](#list-role-definitions) -- [Create or update a role definition](#create-or-update-a-role-definition) -- [Retrieve a role definition](#retrieve-a-role-definition) -- [List role assignments](#list-role-assignments) -- [Create a role assignment](#create-a-role-assignment) -- [Retrieve a role assignment](#retrieve-a-role-assignment) -- [Delete a role assignment](#delete-a-role-assignment) - -##### List role definitions -List the role definitions in the key vault by calling `listRoleDefinitions()`. - -```java readme-sample-listRoleDefinitions -PagedIterable roleDefinitions = - keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL); - -roleDefinitions.forEach(roleDefinition -> - System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); -``` - -##### 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 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()); -``` - -##### 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 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()); -``` - -##### 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 readme-sample-deleteRoleDefinition -String roleDefinitionName = ""; - -keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - -System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName); -``` - -##### List role assignments -List the role assignments in the key vault by calling `listRoleAssignments()`. - -```java readme-sample-listRoleAssignments -PagedIterable roleAssignments = - keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL); - -roleAssignments.forEach(roleAssignment -> - System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); -``` - -##### Create a role assignment -Create a role assignment in the key vault. To do this a role definition ID and a service principal object ID are required. - -A role definition ID can be obtained from the 'id' property of one of the role definitions returned from `listRoleDefinitions()`. - -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 -az ad signed-in-user show --query objectId -``` - -```java readme-sample-createRoleAssignment -String roleDefinitionId = ""; -String servicePrincipalId = ""; -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()); -``` - -##### Retrieve a role assignment -Get an existing role assignment. To do this, the 'name' property from an existing role assignment is required. - -```java readme-sample-getRoleAssignment -String roleAssignmentName = ""; -KeyVaultRoleAssignment roleAssignment = - keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); - -System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()); -``` -##### 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 readme-sample-deleteRoleAssignment -String roleAssignmentName = ""; - -keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); - -System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName); -``` - -#### Async API -The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Access Control service tasks, including: -- [List role definitions asynchronously](#list-role-definitions-asynchronously) -- [Create or update a role definition asynchronously](#create-or-update-a-role-definition-asynchronously) -- [Retrieve a role definition asynchronously](#retrieve-a-role-definition-asynchronously) -- [Delete a role definition asynchronously](#delete-a-role-definition-asynchronously) -- [List role assignments asynchronously](#list-role-assignments-asynchronously) -- [Create a role assignment asynchronously](#create-a-role-assignment-asynchronously) -- [Retrieve a role assignment asynchronously](#retrieve-a-role-assignment-asynchronously) -- [Delete a role assignment asynchronously](#delete-a-role-assignment-asynchronously) - -> Note : You should add `System.in.read()` or `Thread.sleep()` after the function calls in the main class/thread to allow async functions/operations to execute and finish before the main application/thread exits. - -##### List role definitions asynchronously -List the role definitions in the key vault by calling `listRoleDefinitions()`. - -```java readme-sample-listRoleDefinitionsAsync -keyVaultAccessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL) - .subscribe(roleDefinition -> - System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); -``` - -##### 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 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())); -``` - -##### Retrieve a role definition asynchronously -Get an existing role definition. To do this, the 'name' property from an existing role definition is required. - -```java 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())); -``` - -##### Delete a role definition asynchronously -Delete a role definition. To do this, the 'name' property from an existing role definition is required. - -```java readme-sample-deleteRoleDefinitionAsync -String roleDefinitionName = ""; - -keyVaultAccessControlAsyncClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) - .subscribe(unused -> System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName)); -``` - -##### List role assignments asynchronously -List the role assignments in the key vault by calling `listRoleAssignments()`. - -```java readme-sample-listRoleAssignmentsAsync -keyVaultAccessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL) - .subscribe(roleAssignment -> - System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); -``` - -##### Create a role assignment asynchronously -Create a role assignment in the key vault. To do this a role definition ID and a service principal object ID are required. - -A role definition ID can be obtained from the 'id' property of one of the role definitions returned from `listRoleDefinitions()`. - -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 -az ad signed-in-user show --query objectId -``` - -```java readme-sample-createRoleAssignmentAsync -String roleDefinitionId = ""; -String servicePrincipalId = ""; - -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())); -``` - -##### Retrieve a role assignment asynchronously -Get an existing role assignment. To do this, the 'name' property from an existing role assignment is required. - -```java readme-sample-getRoleAssignmentAsync -String roleAssignmentName = ""; - -keyVaultAccessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) - .subscribe(roleAssignment -> - System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); -``` - -##### 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 readme-sample-deleteRoleAssignmentAsync -String roleAssignmentName = ""; - -keyVaultAccessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) - .subscribe(unused -> - System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName)); -``` - -## Backup and restore operations -### Examples -#### Sync API -The following sections provide several code snippets covering some of the most common Azure Key Vault Backup client tasks, including: -- [Pre-backup check for a Key Vault](#run-pre-backup-check-for-a-collection-of-keys) -- [Backup a Key Vault](#backup-a-collection-of-keys) -- [Pre-restore check for a Key Vault](#run-pre-restore-check-for-a-collection-of-keys) -- [Restore a Key Vault](#restore-a-collection-of-keys) -- [Restore a key](#selectively-restore-a-key) - -##### Run pre-backup check for a collection of keys -Check if an entire collection of keys can be backed up by using `beginPreBackup()`. - -```java readme-sample-beginPreBackup -String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; -String sasToken = ""; - -SyncPoller preBackupPoller = - keyVaultBackupClient.beginPreBackup(blobStorageUrl, sasToken); -PollResponse pollResponse = preBackupPoller.poll(); - -System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - -PollResponse finalPollResponse = preBackupPoller.waitForCompletion(); - -if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - String folderUrl = preBackupPoller.getFinalResult(); - - System.out.printf("Pre-backup check completed successfully.%n"); -} else { - KeyVaultBackupOperation operation = preBackupPoller.poll().getValue(); - - System.out.printf("Pre-backup check failed with error: %s.%n", operation.getError().getMessage()); -} -``` - -##### Backup a collection of keys -Back up an entire collection of keys using `beginBackup()`. - -```java readme-sample-beginBackup -String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; -String sasToken = ""; - -SyncPoller backupPoller = - keyVaultBackupClient.beginBackup(blobStorageUrl, sasToken); -PollResponse pollResponse = backupPoller.poll(); - -System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - -PollResponse 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()); -} -``` - -##### Run pre-restore check for a collection of keys -Check if an entire collection of keys can be restored from a backup by using `beginPreRestore()`. - -```java readme-sample-beginPreRestore -String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; -String sasToken = ""; - -SyncPoller preRestorePoller = - keyVaultBackupClient.beginPreRestore(folderUrl, sasToken); -PollResponse pollResponse = preRestorePoller.poll(); - -System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - -PollResponse finalPollResponse = preRestorePoller.waitForCompletion(); - -if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Pre-restore check completed successfully.%n"); -} else { - KeyVaultRestoreOperation operation = preRestorePoller.poll().getValue(); - - System.out.printf("Pre-restore check failed with error: %s.%n", operation.getError().getMessage()); -} -``` - -##### Restore a collection of keys -Restore an entire collection of keys from a backup using `beginRestore()`. - -```java readme-sample-beginRestore -String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; -String sasToken = ""; - -SyncPoller restorePoller = - keyVaultBackupClient.beginRestore(folderUrl, sasToken); -PollResponse pollResponse = restorePoller.poll(); - -System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - -PollResponse finalPollResponse = restorePoller.waitForCompletion(); - -if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Backup restored successfully.%n"); -} else { - KeyVaultRestoreOperation operation = restorePoller.poll().getValue(); - - System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage()); -} -``` - -##### Selectively restore a key -Restore a specific key from a backup using `beginSelectiveRestore()`. - -```java readme-sample-beginSelectiveKeyRestore -String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; -String sasToken = ""; -String keyName = "myKey"; - -SyncPoller restorePoller = - keyVaultBackupClient.beginSelectiveKeyRestore(folderUrl, sasToken, keyName); -PollResponse pollResponse = restorePoller.poll(); - -System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - -PollResponse finalPollResponse = restorePoller.waitForCompletion(); - -if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Key restored successfully.%n"); -} else { - KeyVaultSelectiveKeyRestoreOperation operation = restorePoller.poll().getValue(); - - System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage()); -} -``` - -#### Async API -The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Backup client tasks, including: -- [Run pre-backup check for a collection of keys asynchronously](#run-pre-backup-check-for-a-collection-of-keys-asynchronously) -- [Backup a Key Vault asynchronously](#backup-a-collection-of-keys-asynchronously) -- [Run pre-restore check for a collection of keys asynchronously](#run-pre-restore-check-for-a-collection-of-keys-asynchronously) -- [Restore a Key Vault asynchronously](#restore-a-collection-of-keys-asynchronously) -- [Restore a key asynchronously](#selectively-restore-a-key-asynchronously) - -> Note : You should add `System.in.read()` or `Thread.sleep()` after the function calls in the main class/thread to allow async functions/operations to execute and finish before the main application/thread exits. - -##### Run pre-backup check for a collection of keys asynchronously -Check if an entire collection of keys can be backed up by using `beginPreBackup()`. - -```java readme-sample-beginPreBackupAsync -String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; -String sasToken = ""; - -keyVaultBackupAsyncClient.beginPreBackup(blobStorageUrl, sasToken) - .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. - .doOnError(e -> System.out.printf("Pre-backup check 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("Pre-backup check completed successfully.%n")); -``` - -##### Backup a collection of keys asynchronously -Back up an entire collection of keys using `beginBackup()`. - -```java readme-sample-beginBackupAsync -String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; -String sasToken = ""; - -keyVaultBackupAsyncClient.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)); -``` - -##### Run pre-restore check for a collection of keys asynchronously -Check if an entire collection of keys can be restored from a backup by using `beginPreRestore()`. - -```java readme-sample-beginPreRestoreAsync -String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; -String sasToken = ""; - -keyVaultBackupAsyncClient.beginPreRestore(folderUrl, sasToken) - .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. - .doOnError(e -> System.out.printf("Pre-restore check 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("Pre-restore check completed successfully.%n")); -``` - -##### Restore a collection of keys asynchronously -Restore an entire collection of keys from a backup using `beginRestore()`. - -```java readme-sample-beginRestoreAsync -String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; -String sasToken = ""; - -keyVaultBackupAsyncClient.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")); -``` - -##### Selectively restore a key asynchronously -Restore an entire collection of keys from a backup using `beginSelectiveRestore()`. - -```java readme-sample-beginSelectiveKeyRestoreAsync -String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; -String sasToken = ""; -String keyName = "myKey"; - -keyVaultBackupAsyncClient.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")); -``` - -## Settings operations -### Examples -#### Sync API -The following sections provide several code snippets covering some of the most common Azure Key Vault Settings client tasks, including: -- [Listing settings](#get-all-settings) -- [Retrieving a setting](#retrieve-a-specific-setting) -- [Updating a setting](#update-a-specific-setting) - -##### Get all settings -List all the settings for an Azure Key Vault account. - -```java readme-sample-getSettings -KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings(); - -for (KeyVaultSetting setting : getSettingsResult.getSettings()) { - System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean()); -} -``` - -##### Retrieve a specific setting -Retrieve a specific setting. - -```java readme-sample-getSetting -String settingName = ""; -KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName); - -System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), - setting.asBoolean()); -``` - -##### Update a specific setting -Update a specific setting. -```java readme-sample-updateSetting -String settingName = ""; -KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); -KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate); - -System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean()); -``` - -#### Async API -The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Settings client tasks, including: -- [Listing settings](#get-all-settings-asynchronously) -- [Retrieving a setting](#retrieve-a-specific-setting-asynchronously) -- [Updating a setting](#update-a-specific-setting-asynchronously) - -##### Get all settings asynchronously -List all the settings for a Key Vault account. - -```java readme-sample-getSettingsAsync -keyVaultSettingsAsyncClient.getSettings() - .subscribe(settingsResult -> - settingsResult.getSettings().forEach(setting -> - System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), - setting.asBoolean()))); -``` - -##### Retrieve a specific setting asynchronously -Retrieve a specific setting. - -```java readme-sample-getSettingAsync -String settingName = ""; - -keyVaultSettingsAsyncClient.getSetting(settingName) - .subscribe(setting -> - System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), - setting.asBoolean())); -``` - -##### Update a specific setting asynchronously -Update a specific setting. - -```java readme-sample-updateSettingAsync -String settingName = ""; -KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); - -keyVaultSettingsAsyncClient.updateSetting(settingToUpdate) - .subscribe(updatedSetting -> - System.out.printf("Updated setting with name '%s' and value '%s'.%n", updatedSetting.getName(), - updatedSetting.asBoolean())); -``` - -## Troubleshooting -See our [troubleshooting guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/TROUBLESHOOTING.md) for details on how to diagnose various failure scenarios. - -### 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 readme-sample-troubleshooting -try { - keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, ""); -} catch (HttpResponseException e) { - System.out.println(e.getMessage()); -} -``` - -### Default HTTP client -All client libraries by default use the Netty HTTP client. Adding the above dependency will automatically configure the client library to use the Netty HTTP client. Configuring or changing the HTTP client is detailed in the [HTTP clients wiki][http_clients_wiki]. - -### Default SSL library -All client libraries, by default, use the Tomcat-native Boring SSL library to enable native-level performance for SSL operations. The Boring SSL library is an Uber JAR containing native libraries for Linux / macOS / Windows, and provides better performance compared to the default SSL implementation within the JDK. For more information, including how to reduce the dependency size, refer to the [performance tuning][performance_tuning] section of the wiki. - -## Next steps -Several Key Vault Java SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Azure Key Vault. - -### Additional documentation -For more extensive documentation on Azure Key Vault, see the [API reference documentation][azkeyvault_rest]. - -## Contributing -This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. - -When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. - -This project has adopted the [Microsoft Open Source Code of Conduct][microsoft_code_of_conduct]. For more information see the Code of Conduct FAQ or contact with any additional questions or comments. - - -[source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/src -[api_documentation]: https://azure.github.io/azure-sdk-for-java -[azkeyvault_docs]: https://learn.microsoft.com/azure/key-vault/ -[azure_identity]: https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable -[azure_subscription]: https://azure.microsoft.com/ -[azure_keyvault]: https://learn.microsoft.com/azure/key-vault/quick-create-portal -[azure_keyvault_mhsm]: https://learn.microsoft.com/azure/key-vault/managed-hsm/overview -[azure_keyvault_mhsm_cli]: https://learn.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli -[default_azure_credential]: https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#defaultazurecredential -[managed_identity]: https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview -[azkeyvault_rest]: https://learn.microsoft.com/rest/api/keyvault/ -[administration_samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration -[storage_readme_sas_token]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/storage/azure-storage-blob#get-credentials -[portal_sas_token]: https://learn.microsoft.com/azure/vs-azure-tools-storage-manage-with-storage-explorer?tabs=windows#generate-a-shared-access-signature-in-storage-explorer -[performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -[jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable -[http_clients_wiki]: https://learn.microsoft.com/azure/developer/java/sdk/http-client-pipeline#http-clients -[microsoft_code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ - - diff --git a/sdk/keyvault/azure-security-keyvault-administration/TROUBLESHOOTING.md b/sdk/keyvault/azure-security-keyvault-administration/TROUBLESHOOTING.md deleted file mode 100644 index d5f5c8c7eacd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/TROUBLESHOOTING.md +++ /dev/null @@ -1,2 +0,0 @@ -# Troubleshooting Azure Key Vault Administration SDK Issues -See our general [Azure Key Vault SDK Troubleshooting Guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/TROUBLESHOOTING.md) to troubleshoot issues common to the Azure Key Vault SDKs for Java. diff --git a/sdk/keyvault/azure-security-keyvault-administration/assets.json b/sdk/keyvault/azure-security-keyvault-administration/assets.json deleted file mode 100644 index 16819beda18c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "java", - "TagPrefix": "java/keyvault/azure-security-keyvault-administration", - "Tag": "java/keyvault/azure-security-keyvault-administration_18fc6d4e27" -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/checkstyle-suppressions.xml b/sdk/keyvault/azure-security-keyvault-administration/checkstyle-suppressions.xml deleted file mode 100644 index da8b5dca4da3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/checkstyle-suppressions.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/sdk/keyvault/azure-security-keyvault-administration/pom.xml b/sdk/keyvault/azure-security-keyvault-administration/pom.xml deleted file mode 100644 index e9272937d4a5..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/pom.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - - com.azure - azure-client-sdk-parent - 1.7.0 - ../../parents/azure-client-sdk-parent - - - 4.0.0 - - com.azure - azure-security-keyvault-administration - 4.7.0-beta.1 - - Microsoft Azure client library for KeyVault Administration - This module contains client library for Microsoft Azure KeyVault Administration. - https://github.com/Azure/azure-sdk-for-java - - - - azure-java-build-docs - ${site.url}/site/${project.artifactId} - - - - - scm:git:https://github.com/Azure/azure-sdk-for-java - scm:git:git@github.com:Azure/azure-sdk-for-java.git - HEAD - - - - - - --add-exports com.azure.core/com.azure.core.implementation.http=ALL-UNNAMED - --add-exports com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - - --add-opens com.azure.security.keyvault.administration/com.azure.security.keyvault.administration=ALL-UNNAMED - --add-opens com.azure.security.keyvault.administration/com.azure.security.keyvault.administration.implementation=ALL-UNNAMED - --add-opens com.azure.security.keyvault.administration/com.azure.security.keyvault.administration.models=ALL-UNNAMED - - - checkstyle-suppressions.xml - false - spotbugs-exclude.xml - - - - - com.azure - azure-core - 1.55.3 - - - com.azure - azure-json - 1.5.0 - - - com.azure - azure-core-http-netty - 1.15.11 - - - - org.hamcrest - hamcrest-library - 2.2 - test - - - com.azure - azure-core-test - 1.27.0-beta.8 - test - - - com.azure - azure-security-keyvault-keys - 4.10.0-beta.1 - test - - - com.azure - azure-storage-blob - 12.30.0 - test - - - com.azure - azure-identity - 1.15.4 - test - - - diff --git a/sdk/keyvault/azure-security-keyvault-administration/spotbugs-exclude.xml b/sdk/keyvault/azure-security-keyvault-administration/spotbugs-exclude.xml deleted file mode 100644 index 5ebeb59e2c88..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/spotbugs-exclude.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 deleted file mode 100644 index 2170aa64d7be..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClient.java +++ /dev/null @@ -1,1053 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.RequestOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignment; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignmentCreateParameters; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinition; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinitionCreateParameters; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.SetRoleDefinitionOptions; -import reactor.core.publisher.Mono; - -import java.net.URL; -import java.util.Objects; -import java.util.UUID; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.core.util.FluxUtil.pagedFluxError; -import static com.azure.core.util.FluxUtil.withContext; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.mapPagedResponse; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.swallowExceptionForStatusCodeAsync; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateAndGetRoleAssignmentCreateParameters; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateAndGetRoleDefinitionCreateParameters; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateRoleAssignmentParameters; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateRoleDefinitionParameters; - -/** - * The {@link KeyVaultAccessControlAsyncClient} provides asynchronous methods to view and manage Role Based Access - * for a key vault. The client supports creating, listing, updating, and deleting - * {@link KeyVaultRoleDefinition role definitions} and {@link KeyVaultRoleAssignment role assignments}. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link KeyVaultAccessControlAsyncClient} class, a vault url and a credential object.

- * - *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, - * which is appropriate for most scenarios, including local development and production environments. Additionally, - * we recommend using a - * - * managed identity for authentication in production environments. - * You can find more information on different ways of authenticating and their corresponding credential types in the - * - * Azure Identity documentation".

- * - *

Sample: Construct Asynchronous Access Control Client

- * - *

The following code sample demonstrates the creation of a {@link KeyVaultAccessControlAsyncClient}, using the - * {@link KeyVaultAccessControlClientBuilder} to configure it.

- * - * - *
- * KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildAsyncClient();
- * 
- * - * - *
- * - *
- * - *

Set a Role Definition

- * The {@link KeyVaultAccessControlAsyncClient} can be used to set a role definition in the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously create a role definition in the key vault, using the - * {@link KeyVaultAccessControlAsyncClient#setRoleDefinition(KeyVaultRoleScope)} API.

- * - * - *
- * 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());
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultAccessControlClient}.

- * - *
- * - *
- * - *

Get a Role Definition

- * The {@link KeyVaultAccessControlClient} can be used to retrieve a role definition from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using - * the {@link KeyVaultAccessControlClient#getRoleDefinition(KeyVaultRoleScope, String)} API.

- * - * - *
- * 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());
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultAccessControlClient}.

- * - *
- * - *
- * - *

Delete a Role Definition

- * The {@link KeyVaultAccessControlAsyncClient} can be used to delete a role definition from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using - * the {@link KeyVaultAccessControlAsyncClient#deleteRoleDefinition(KeyVaultRoleScope, String)} API.

- * - * - *
- * String roleDefinitionName = "6a709e6e-8964-4012-a99b-6b0131e8ce40";
- *
- * keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);
- *
- * System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName);
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultAccessControlClient}.

- * - *
- * - *
- * - *

Create a Role Assignment

- * The {@link KeyVaultAccessControlAsyncClient} can be used to set a role assignment in the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously create a role assignment in the key vault, using the - * {@link KeyVaultAccessControlAsyncClient#createRoleAssignment(KeyVaultRoleScope, String, String)} API.

- * - * - *
- * 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());
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultAccessControlClient}.

- * - *
- * - *
- * - *

Get a Role Definition

- * The {@link KeyVaultAccessControlClient} can be used to retrieve a role assignment from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously retrieve a role assignment from the key vault, using - * the {@link KeyVaultAccessControlClient#getRoleDefinition(KeyVaultRoleScope, String)} API.

- * - * - *
- * 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());
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultAccessControlClient}.

- * - *
- * - *
- * - *

Delete a Role Definition

- * The {@link KeyVaultAccessControlAsyncClient} can be used to delete a role assignment from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously delete a role assignment from the key vault, using - * the {@link KeyVaultAccessControlAsyncClient#deleteRoleDefinition(KeyVaultRoleScope, String)} API.

- * - * - *
- * String roleAssignmentName = "c3ed874a-64a9-4a87-8581-2a1ad84b9ddb";
- *
- * keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);
- *
- * System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName);
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultAccessControlClient}.

- * - * @see com.azure.security.keyvault.administration - * @see KeyVaultAccessControlClientBuilder - */ -@ServiceClient(builder = KeyVaultAccessControlClientBuilder.class, isAsync = true) -public final class KeyVaultAccessControlAsyncClient { - /** - * The logger to be used. - */ - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultAccessControlAsyncClient.class); - - /** - * The underlying AutoRest client used to interact with the Key Vault service. - */ - private final KeyVaultAdministrationClientImpl clientImpl; - - /** - * The Key Vault URL this client is associated to. - */ - private final String vaultUrl; - - /** - * The {@link HttpPipeline} powering this client. - */ - private final HttpPipeline pipeline; - - /** - * Package private constructor to be used by {@link KeyVaultAccessControlClientBuilder}. - */ - KeyVaultAccessControlAsyncClient(URL vaultUrl, HttpPipeline httpPipeline, - KeyVaultAdministrationServiceVersion serviceVersion) { - - Objects.requireNonNull(vaultUrl, KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED); - - this.vaultUrl = vaultUrl.toString(); - this.pipeline = httpPipeline; - - clientImpl = new KeyVaultAdministrationClientImpl(httpPipeline, this.vaultUrl, serviceVersion); - } - - /** - * Gets the URL for the Key Vault this client is associated with. - * - * @return The Key Vault URL. - */ - public String getVaultUrl() { - return vaultUrl; - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.pipeline; - } - - /** - * Lists all {@link KeyVaultRoleDefinition role definitions} that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return A {@link PagedFlux} containing the {@link KeyVaultRoleDefinition role definitions} for the given - * {@link KeyVaultRoleScope role scope}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listRoleDefinitions(KeyVaultRoleScope roleScope) { - try { - Objects.requireNonNull(roleScope, - String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'roleScope'")); - - return new PagedFlux<>( - () -> withContext(context -> clientImpl.getRoleDefinitions() - .listSinglePageAsync(roleScope.toString(), new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(pagedResponse -> mapPagedResponse(pagedResponse, - binaryData -> KeyVaultAdministrationUtil - .roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class))))), - nextLink -> withContext(context -> clientImpl.getRoleDefinitions() - .listNextSinglePageAsync(nextLink, new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(pagedResponse -> mapPagedResponse(pagedResponse, binaryData -> KeyVaultAdministrationUtil - .roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class)))))); - } catch (RuntimeException e) { - return pagedFluxError(LOGGER, e); - } - } - - /** - * Creates or updates a {@link KeyVaultRoleDefinition role definition} with a randomly generated name. - * - *

Code Samples

- *

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

- * - *
-     * 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 '/'. - * - * @return A {@link Mono} containing the created {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setRoleDefinition(KeyVaultRoleScope roleScope) { - return setRoleDefinition(roleScope, UUID.randomUUID().toString()); - } - - /** - * Creates or updates a {@link KeyVaultRoleDefinition role definition}. If no name is provided, then a - * {@link KeyVaultRoleDefinition role definition} will be created with a randomly generated name. - * - *

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}.

- * - *
-     * 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 '/'. - * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. It can be any valid\ - * UUID. If {@code null} is provided, a name will be randomly generated. - * - * @return A {@link Mono} containing the created {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} - * are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setRoleDefinition(KeyVaultRoleScope roleScope, String roleDefinitionName) { - return setRoleDefinitionWithResponse(new SetRoleDefinitionOptions(roleScope, roleDefinitionName)) - .flatMap(FluxUtil::toMono); - } - - /** - * Creates or updates a {@link KeyVaultRoleDefinition role definition}. - * - *

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}.

- * - *
-     * 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}. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * created or updated {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If any parameter in {@code options} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} - * in the {@link SetRoleDefinitionOptions options} object are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setRoleDefinitionWithResponse(SetRoleDefinitionOptions options) { - return withContext(context -> setRoleDefinitionWithResponse(options, context)); - } - - /** - * Creates or updates a {@link KeyVaultRoleDefinition role definition}. - * - * @param options Object representing the configurable options to create or update a - * {@link KeyVaultRoleDefinition role definition}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * created or updated {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If any parameter in {@code options} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} - * in the {@link SetRoleDefinitionOptions options} object are {@code null}. - */ - Mono> setRoleDefinitionWithResponse(SetRoleDefinitionOptions options, - Context context) { - - try { - RoleDefinitionCreateParameters parameters = validateAndGetRoleDefinitionCreateParameters(options); - - return clientImpl.getRoleDefinitions() - .createOrUpdateWithResponseAsync(options.getRoleScope().toString(), options.getRoleDefinitionName(), - BinaryData.fromObject(parameters), new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> KeyVaultAdministrationUtil.transformBinaryDataResponse(response, - binaryData -> KeyVaultAdministrationUtil - .roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Gets a {@link KeyVaultRoleDefinition role definition}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return A {@link Mono} containing the {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleDefinition role definition} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getRoleDefinition(KeyVaultRoleScope roleScope, String roleDefinitionName) { - return getRoleDefinitionWithResponse(roleScope, roleDefinitionName).flatMap(FluxUtil::toMono); - } - - /** - * Gets a {@link KeyVaultRoleDefinition role definition}. - * - *

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}.

- * - *
-     * 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}. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleDefinition role definition} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, - String roleDefinitionName) { - return withContext(context -> getRoleDefinitionWithResponse(roleScope, roleDefinitionName, context)); - } - - /** - * Gets a {@link KeyVaultRoleDefinition role definition}. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. - * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleDefinition role definition} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - Mono> getRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, - String roleDefinitionName, Context context) { - - try { - validateRoleDefinitionParameters(roleScope, roleDefinitionName); - - return clientImpl.getRoleDefinitions() - .getWithResponseAsync(roleScope.toString(), roleDefinitionName, - new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> KeyVaultAdministrationUtil.transformBinaryDataResponse(response, - binaryData -> KeyVaultAdministrationUtil - .roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Deletes a {@link KeyVaultRoleDefinition role definition}. - * - *

Code Samples

- *

Deletes a {@link KeyVaultRoleDefinition role definition}.

- * - *
-     * 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 '/'. - * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. - * - * @return A {@link Mono} of a {@link Void}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteRoleDefinition(KeyVaultRoleScope roleScope, String roleDefinitionName) { - return deleteRoleDefinitionWithResponse(roleScope, roleDefinitionName).flatMap(FluxUtil::toMono); - } - - /** - * Deletes a {@link KeyVaultRoleDefinition role definition}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return A {@link Mono} containing a {@link Response} with a {@link Void} value. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, - String roleDefinitionName) { - - return withContext(context -> deleteRoleDefinitionWithResponse(roleScope, roleDefinitionName, context)); - } - - /** - * Deletes a {@link KeyVaultRoleDefinition role definition}. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. - * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link Response} with a {@link Void} value. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - Mono> deleteRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionName, - Context context) { - - try { - validateRoleDefinitionParameters(roleScope, roleDefinitionName); - - return clientImpl.getRoleDefinitions() - .deleteWithResponseAsync(roleScope.toString(), roleDefinitionName, - new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> (Response) new SimpleResponse(response, null)) - .onErrorResume(KeyVaultAdministrationException.class, - e -> swallowExceptionForStatusCodeAsync(404, e, LOGGER)); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Lists all {@link KeyVaultRoleAssignment role assignments} that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. - * - * @return A {@link PagedFlux} containing the {@link KeyVaultRoleAssignment role assignments} for the given - * {@link KeyVaultRoleScope role scope}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listRoleAssignments(KeyVaultRoleScope roleScope) { - try { - Objects.requireNonNull(roleScope, - String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'roleScope'")); - - return new PagedFlux<>( - () -> withContext(context -> clientImpl.getRoleAssignments() - .listForScopeSinglePageAsync(roleScope.toString(), new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(pagedResponse -> mapPagedResponse(pagedResponse, - binaryData -> KeyVaultAdministrationUtil - .roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class))))), - nextLink -> withContext(context -> clientImpl.getRoleAssignments() - .listForScopeNextSinglePageAsync(nextLink, new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(pagedResponse -> mapPagedResponse(pagedResponse, binaryData -> KeyVaultAdministrationUtil - .roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class)))))); - } catch (RuntimeException e) { - return pagedFluxError(LOGGER, e); - } - } - - /** - * Creates a {@link KeyVaultRoleAssignment role assignment} with a randomly generated name. - * - *

Code Samples

- *

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

- * - *
-     * 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. - * @param roleDefinitionId The {@link KeyVaultRoleDefinition role definition} ID for the role assignment. - * @param principalId The principal ID assigned to the role. This maps to the ID inside the Active Directory. - * - * @return A {@link Mono} containing the created {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope}, {@code roleDefinitionId} or - * {@code principalId} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope}, {@link String roleAssignmentName}, - * {@link String roleDefinitionId} or {@link String principalId} are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createRoleAssignment(KeyVaultRoleScope roleScope, String roleDefinitionId, - String principalId) { - - return createRoleAssignment(roleScope, roleDefinitionId, principalId, UUID.randomUUID().toString()); - } - - /** - * Creates a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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. - * @param roleDefinitionId The {@link KeyVaultRoleDefinition role definition} ID for the role assignment. - * @param principalId The principal ID assigned to the role. This maps to the ID inside the Active Directory. - * @param roleAssignmentName The name used to create the {@link KeyVaultRoleAssignment role assignment}. It can be - * any valid UUID. - * - * @return A {@link Mono} containing the created {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given name - * already or if the given {@code roleScope}, {@code roleDefinitionId} or {@code principalId} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope}, {@link String roleAssignmentName}, - * {@link String roleDefinitionId} or {@link String principalId} are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createRoleAssignment(KeyVaultRoleScope roleScope, String roleDefinitionId, - String principalId, String roleAssignmentName) { - - return createRoleAssignmentWithResponse(roleScope, roleDefinitionId, principalId, roleAssignmentName) - .flatMap(FluxUtil::toMono); - } - - /** - * Creates a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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. - * @param roleAssignmentName The name used to create the {@link KeyVaultRoleAssignment role assignment}. It can be - * any valid UUID. - * @param roleDefinitionId The {@link KeyVaultRoleDefinition role definition} ID for the role assignment. - * @param principalId The principal ID assigned to the role. This maps to the ID inside the Active Directory. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the created - * {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given name - * already exists or if the given {@code roleScope}, {@code roleDefinitionId} or {@code principalId} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope}, {@link String roleAssignmentName}, - * {@link String roleDefinitionId} or {@link String principalId} are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, - String roleDefinitionId, String principalId, String roleAssignmentName) { - - return withContext(context -> createRoleAssignmentWithResponse(roleScope, roleDefinitionId, principalId, - roleAssignmentName, context)); - } - - /** - * Creates a {@link KeyVaultRoleAssignment role assignment}. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment} - * to create. - * @param roleAssignmentName The name used to create the {@link KeyVaultRoleAssignment role assignment}. It can be - * any valid UUID. - * @param roleDefinitionId The {@link KeyVaultRoleDefinition role definition} ID for the role assignment. - * @param principalId The principal ID assigned to the role. This maps to the ID inside the Active Directory. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the created - * {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given name - * already exists or if the given {@code roleScope}, {@code roleDefinitionId} or {@code principalId} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope}, {@link String roleAssignmentName}, - * {@link String roleDefinitionId} or {@link String principalId} are {@code null}. - */ - Mono> createRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, - String roleDefinitionId, String principalId, String roleAssignmentName, Context context) { - - try { - RoleAssignmentCreateParameters parameters = validateAndGetRoleAssignmentCreateParameters(roleScope, - roleDefinitionId, principalId, roleAssignmentName); - - return clientImpl.getRoleAssignments() - .createWithResponseAsync(roleScope.toString(), roleAssignmentName, BinaryData.fromObject(parameters), - new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> KeyVaultAdministrationUtil.transformBinaryDataResponse(response, - binaryData -> KeyVaultAdministrationUtil - .roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Gets a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return A {@link Mono} containing the {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleAssignmentName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getRoleAssignment(KeyVaultRoleScope roleScope, String roleAssignmentName) { - return getRoleAssignmentWithResponse(roleScope, roleAssignmentName).flatMap(FluxUtil::toMono); - } - - /** - * Gets a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleAssignmentName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, - String roleAssignmentName) { - - return withContext(context -> getRoleAssignmentWithResponse(roleScope, roleAssignmentName, context)); - } - - /** - * Gets a {@link KeyVaultRoleAssignment role assignment}. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. - * @param roleAssignmentName The name of the {@link KeyVaultRoleAssignment role assignment}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleAssignmentName} are - * {@code null}. - */ - Mono> getRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, - String roleAssignmentName, Context context) { - - try { - validateRoleAssignmentParameters(roleScope, roleAssignmentName); - - return clientImpl.getRoleAssignments() - .getWithResponseAsync(roleScope.toString(), roleAssignmentName, - new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> KeyVaultAdministrationUtil.transformBinaryDataResponse(response, - binaryData -> KeyVaultAdministrationUtil - .roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Deletes a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

Deletes a {@link KeyVaultRoleAssignment role assignment}.

- * - *
-     * 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}. - * - * @return A {@link Mono} of a {@link Void}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleAssignmentName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteRoleAssignment(KeyVaultRoleScope roleScope, String roleAssignmentName) { - return deleteRoleAssignmentWithResponse(roleScope, roleAssignmentName).flatMap(FluxUtil::toMono); - } - - /** - * Deletes a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return A {@link Mono} containing a {@link Response} with a {@link Void} value. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleAssignmentName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, - String roleAssignmentName) { - - return withContext(context -> deleteRoleAssignmentWithResponse(roleScope, roleAssignmentName, context)); - } - - /** - * Deletes a {@link KeyVaultRoleAssignment role assignment}. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. - * @param roleAssignmentName The name of the {@link KeyVaultRoleAssignment role assignment}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link Response} with a {@link Void} value. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleAssignmentName} are - * {@code null}. - */ - Mono> deleteRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleAssignmentName, - Context context) { - - try { - validateRoleAssignmentParameters(roleScope, roleAssignmentName); - - return clientImpl.getRoleAssignments() - .deleteWithResponseAsync(roleScope.toString(), roleAssignmentName, - new RequestOptions().setContext(context)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> (Response) new SimpleResponse(response, null)) - .onErrorResume(KeyVaultAdministrationException.class, - e -> swallowExceptionForStatusCodeAsync(404, e, LOGGER)); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } -} 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 deleted file mode 100644 index 372b8a627a7d..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClient.java +++ /dev/null @@ -1,988 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.RequestOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignment; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignmentCreateParameters; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinition; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinitionCreateParameters; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.SetRoleDefinitionOptions; -import reactor.core.publisher.Mono; - -import java.net.URL; -import java.util.Objects; -import java.util.UUID; - -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.roleAssignmentToKeyVaultRoleAssignment; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.roleDefinitionToKeyVaultRoleDefinition; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.swallowExceptionForStatusCodeSync; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.transformBinaryDataResponse; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateAndGetRoleAssignmentCreateParameters; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateAndGetRoleDefinitionCreateParameters; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateRoleAssignmentParameters; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateRoleDefinitionParameters; -import static com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils.toKeyVaultAdministrationException; - -/** - * The {@link KeyVaultAccessControlClient} provides synchronous methods to view and manage Role Based Access for a - * key vault. The client supports creating, listing, updating, and deleting - * {@link KeyVaultRoleDefinition role definitions} and {@link KeyVaultRoleAssignment role assignments}. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link KeyVaultAccessControlClient} class, a vault url and a credential object.

- * - *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, - * which is appropriate for most scenarios, including local development and production environments. Additionally, - * we recommend using a - * - * managed identity for authentication in production environments. - * You can find more information on different ways of authenticating and their corresponding credential types in the - * - * Azure Identity documentation".

- * - *

Sample: Construct Synchronous Access Control Client

- * - *

The following code sample demonstrates the creation of a {@link KeyVaultAccessControlClient}, using the - * {@link KeyVaultAccessControlClientBuilder} to configure it.

- * - * - *
- * KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - *
- * - *
- * - *

Set a Role Definition

- * The {@link KeyVaultAccessControlClient} can be used to set a role definition in the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously create a role definition in the key vault, using the - * {@link KeyVaultAccessControlClient#setRoleDefinition(KeyVaultRoleScope)} API.

- * - * - *
- * 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());
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultAccessControlAsyncClient}.

- * - *
- * - *
- * - *

Get a Role Definition

- * The {@link KeyVaultAccessControlClient} can be used to retrieve a role definition from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using - * the {@link KeyVaultAccessControlClient#getRoleDefinition(KeyVaultRoleScope, String)} API.

- * - * - *
- * 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());
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultAccessControlAsyncClient}.

- * - *
- * - *
- * - *

Delete a Role Definition

- * The {@link KeyVaultAccessControlClient} can be used to delete a role definition from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using - * the {@link KeyVaultAccessControlClient#deleteRoleDefinition(KeyVaultRoleScope, String)} API.

- * - * - *
- * String roleDefinitionName = "6a709e6e-8964-4012-a99b-6b0131e8ce40";
- *
- * keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);
- *
- * System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName);
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultAccessControlAsyncClient}.

- * - *
- * - *
- * - *

Create a Role Assignment

- * The {@link KeyVaultAccessControlClient} can be used to set a role assignment in the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously create a role assignment in the key vault, using the - * {@link KeyVaultAccessControlClient#createRoleAssignment(KeyVaultRoleScope, String, String)} API.

- * - * - *
- * 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());
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultAccessControlAsyncClient}.

- * - *
- * - *
- * - *

Get a Role Definition

- * The {@link KeyVaultAccessControlClient} can be used to retrieve a role assignment from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously retrieve a role assignment from the key vault, using - * the {@link KeyVaultAccessControlClient#getRoleDefinition(KeyVaultRoleScope, String)} API.

- * - * - *
- * 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());
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultAccessControlAsyncClient}.

- * - *
- * - *
- * - *

Delete a Role Definition

- * The {@link KeyVaultAccessControlClient} can be used to delete a role assignment from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously delete a role assignment from the key vault, using - * the {@link KeyVaultAccessControlClient#deleteRoleDefinition(KeyVaultRoleScope, String)} API.

- * - * - *
- * String roleAssignmentName = "c3ed874a-64a9-4a87-8581-2a1ad84b9ddb";
- *
- * keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);
- *
- * System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName);
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultAccessControlAsyncClient}.

- * - * @see com.azure.security.keyvault.administration - * @see KeyVaultAccessControlClientBuilder - */ -@ServiceClient(builder = KeyVaultAccessControlClientBuilder.class) -public final class KeyVaultAccessControlClient { - /** - * The logger to be used. - */ - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultAccessControlClient.class); - - /** - * The underlying AutoRest client used to interact with the Key Vault service. - */ - private final KeyVaultAdministrationClientImpl implClient; - - /** - * The Key Vault URL this client is associated to. - */ - private final String vaultUrl; - - /** - * Package private constructor to be used by {@link KeyVaultAccessControlClientBuilder}. - */ - KeyVaultAccessControlClient(URL vaultUrl, HttpPipeline httpPipeline, - KeyVaultAdministrationServiceVersion serviceVersion) { - - Objects.requireNonNull(vaultUrl, KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED); - - this.vaultUrl = vaultUrl.toString(); - implClient = new KeyVaultAdministrationClientImpl(httpPipeline, this.vaultUrl, serviceVersion); - } - - /** - * Gets the URL for the Key Vault this client is associated with. - * - * @return The Key Vault URL. - */ - public String getVaultUrl() { - return this.vaultUrl; - } - - /** - * Get all {@link KeyVaultRoleDefinition role definitions} that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return A {@link PagedIterable} containing the {@link KeyVaultRoleDefinition role definitions} for the given - * {@link KeyVaultRoleScope roleScope}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope roleScope} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listRoleDefinitions(KeyVaultRoleScope roleScope) { - return listRoleDefinitions(roleScope, Context.NONE); - } - - /** - * Get all {@link KeyVaultRoleDefinition role definitions} that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - *

Code Samples

- *

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

- * - *
-     * 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. - * - * @return A {@link PagedIterable} containing the {@link KeyVaultRoleDefinition role definitions} for the given - * {@link KeyVaultRoleScope roleScope}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope roleScope} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listRoleDefinitions(KeyVaultRoleScope roleScope, Context context) { - Objects.requireNonNull(roleScope, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'roleScope'")); - - try { - return implClient.getRoleDefinitions() - .list(roleScope.toString(), new RequestOptions().setContext(context)) - .mapPage( - binaryData -> roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class))); - } catch (HttpResponseException e) { - throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Creates a {@link KeyVaultRoleDefinition role definition} with a randomly generated name. - * - *

Code Samples

- *

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

- * - *
-     * 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 '/'. - * - * @return The created {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultRoleDefinition setRoleDefinition(KeyVaultRoleScope roleScope) { - return setRoleDefinition(roleScope, UUID.randomUUID().toString()); - } - - /** - * Creates or updates a {@link KeyVaultRoleDefinition role definition} with a given name. If no name is provided, - * then a {@link KeyVaultRoleDefinition role definition} will be created with a randomly generated name. - * - *

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}.

- * - *
-     * 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 '/'. - * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. It can be any valid - * UUID. If {@code null} is provided, a name will be randomly generated. - * - * @return The created or updated {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} - * are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultRoleDefinition setRoleDefinition(KeyVaultRoleScope roleScope, String roleDefinitionName) { - return setRoleDefinitionWithResponse(new SetRoleDefinitionOptions(roleScope, roleDefinitionName), Context.NONE) - .getValue(); - } - - /** - * Creates or updates a {@link KeyVaultRoleDefinition role definition}. - * - *

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}.

- * - *
-     * 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}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} whose {@link Response#getValue() value} contains the created or updated - * {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If any parameter in {@code options} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} - * in the {@link SetRoleDefinitionOptions options} object are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response setRoleDefinitionWithResponse(SetRoleDefinitionOptions options, - Context context) { - - RoleDefinitionCreateParameters parameters = validateAndGetRoleDefinitionCreateParameters(options); - - try { - Response roleDefinitionResponse = implClient.getRoleDefinitions() - .createOrUpdateWithResponse(options.getRoleScope().toString(), options.getRoleDefinitionName(), - BinaryData.fromObject(parameters), new RequestOptions().setContext(context)); - - return transformBinaryDataResponse(roleDefinitionResponse, - binaryData -> roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class))); - } catch (HttpResponseException e) { - throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Gets a {@link KeyVaultRoleDefinition role definition}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return The retrieved {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleDefinition role definition} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultRoleDefinition getRoleDefinition(KeyVaultRoleScope roleScope, String roleDefinitionName) { - return getRoleDefinitionWithResponse(roleScope, roleDefinitionName, Context.NONE).getValue(); - } - - /** - * Gets a {@link KeyVaultRoleDefinition role definition}. - * - *

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}.

- * - *
-     * 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}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} whose {@link Response#getValue() value} contains the - * retrieved {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleDefinition role definition} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, - String roleDefinitionName, Context context) { - - validateRoleDefinitionParameters(roleScope, roleDefinitionName); - - try { - Response roleDefinitionResponse = implClient.getRoleDefinitions() - .getWithResponse(roleScope.toString(), roleDefinitionName, new RequestOptions().setContext(context)); - - return transformBinaryDataResponse(roleDefinitionResponse, - binaryData -> roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class))); - } catch (HttpResponseException e) { - throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Deletes a {@link KeyVaultRoleDefinition role definition}. - * - *

Code Samples

- *

Deletes a {@link KeyVaultRoleDefinition role definition}.

- * - *
-     * 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 '/'. - * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition role definition}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteRoleDefinition(KeyVaultRoleScope roleScope, String roleDefinitionName) { - deleteRoleDefinitionWithResponse(roleScope, roleDefinitionName, Context.NONE); - } - - /** - * Deletes a {@link KeyVaultRoleDefinition role definition}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} with a {@link Void} value. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} or {@link String roleDefinitionName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionName, - Context context) { - - validateRoleDefinitionParameters(roleScope, roleDefinitionName); - - try { - Response roleDefinitionResponse = implClient.getRoleDefinitions() - .deleteWithResponse(roleScope.toString(), roleDefinitionName, new RequestOptions().setContext(context)); - - return new SimpleResponse<>(roleDefinitionResponse, null); - } catch (HttpResponseException e) { - KeyVaultAdministrationException mappedException = toKeyVaultAdministrationException(e); - return swallowExceptionForStatusCodeSync(404, mappedException, LOGGER); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Get all {@link KeyVaultRoleAssignment role assignments} that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return A {@link PagedIterable} containing the {@link KeyVaultRoleAssignment role assignments} for the given - * {@link KeyVaultRoleScope roleScope}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope roleScope} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listRoleAssignments(KeyVaultRoleScope roleScope) { - return listRoleAssignments(roleScope, Context.NONE); - } - - /** - * Get all {@link KeyVaultRoleAssignment role assignments} that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - *

Code Samples

- *

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

- * - *
-     * 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. - * - * @return A {@link PagedIterable} containing the {@link KeyVaultRoleAssignment role assignments} for the given - * {@link KeyVaultRoleScope roleScope}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope roleScope} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listRoleAssignments(KeyVaultRoleScope roleScope, Context context) { - Objects.requireNonNull(roleScope, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'roleScope'")); - - try { - return implClient.getRoleAssignments() - .listForScope(roleScope.toString(), new RequestOptions().setContext(context)) - .mapPage( - binaryData -> roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class))); - } catch (HttpResponseException e) { - throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Creates a {@link KeyVaultRoleAssignment role assignment} with a randomly generated name. - * - *

Code Samples

- *

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

- * - *
-     * 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. - * @param roleDefinitionId The {@link KeyVaultRoleDefinition role definition} ID for the role assignment. - * @param principalId The principal ID assigned to the role. This maps to the ID inside the Active Directory. - * - * @return A {@link Mono} containing the created {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope}, {@code roleDefinitionId} or - * {@code principalId} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope roleScope}, {@link String roleDefinitionId} or - * {@link String principalId} are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultRoleAssignment createRoleAssignment(KeyVaultRoleScope roleScope, String roleDefinitionId, - String principalId) { - - return createRoleAssignmentWithResponse(roleScope, roleDefinitionId, principalId, UUID.randomUUID().toString(), - Context.NONE).getValue(); - } - - /** - * Creates a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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. - * @param roleAssignmentName The name used to create the {@link KeyVaultRoleAssignment role assignment}. It can be - * any valid UUID. - * @param roleDefinitionId The {@link KeyVaultRoleDefinition role definition} ID for the role assignment. - * @param principalId The principal ID assigned to the role. This maps to the ID inside the Active Directory. - * - * @return The created {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given name - * already exists or if the given {@code roleScope}, {@code roleDefinitionId} or {@code principalId} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope}, {@link String roleAssignmentName}, - * {@link String roleDefinitionId} or {@link String principalId} are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultRoleAssignment createRoleAssignment(KeyVaultRoleScope roleScope, String roleDefinitionId, - String principalId, String roleAssignmentName) { - - return createRoleAssignmentWithResponse(roleScope, roleDefinitionId, principalId, roleAssignmentName, - Context.NONE).getValue(); - } - - /** - * Creates a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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. - * @param roleAssignmentName The name used to create the {@link KeyVaultRoleAssignment role assignment}. It can be - * any valid UUID. - * @param roleDefinitionId The {@link KeyVaultRoleDefinition role definition} ID for the role assignment. - * @param principalId The principal ID assigned to the role. This maps to the ID inside the Active Directory. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the created - * {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given - * name already exists or if the given {@code roleScope}, {@code roleDefinitionId} or {@code principalId} are - * invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope}, {@link String roleAssignmentName}, - * {@link String roleDefinitionId} or {@link String principalId} are {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, - String roleDefinitionId, String principalId, String roleAssignmentName, Context context) { - - RoleAssignmentCreateParameters parameters = validateAndGetRoleAssignmentCreateParameters(roleScope, - roleDefinitionId, principalId, roleAssignmentName); - - try { - Response roleAssignmentResponse = implClient.getRoleAssignments() - .createWithResponse(roleScope.toString(), roleAssignmentName, BinaryData.fromObject(parameters), - new RequestOptions().setContext(context)); - - return transformBinaryDataResponse(roleAssignmentResponse, - binaryData -> roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class))); - } catch (HttpResponseException e) { - throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Gets a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * - * @return The {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope roleScope} or {@link String roleAssignmentName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultRoleAssignment getRoleAssignment(KeyVaultRoleScope roleScope, String roleAssignmentName) { - return getRoleAssignmentWithResponse(roleScope, roleAssignmentName, Context.NONE).getValue(); - } - - /** - * Gets a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return The {@link KeyVaultRoleAssignment role assignment}. - * - * @throws KeyVaultAdministrationException If a {@link KeyVaultRoleAssignment role assignment} with the given name - * cannot be found or if the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope roleScope} or {@link String roleAssignmentName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, - String roleAssignmentName, Context context) { - - validateRoleAssignmentParameters(roleScope, roleAssignmentName); - - try { - Response roleAssignmentResponse = implClient.getRoleAssignments() - .getWithResponse(roleScope.toString(), roleAssignmentName, new RequestOptions().setContext(context)); - - return transformBinaryDataResponse(roleAssignmentResponse, - binaryData -> roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class))); - } catch (HttpResponseException e) { - throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Deletes a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

Deletes a {@link KeyVaultRoleAssignment role assignment}.

- * - *
-     * 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}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope roleScope} or {@link String roleAssignmentName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteRoleAssignment(KeyVaultRoleScope roleScope, String roleAssignmentName) { - deleteRoleAssignmentWithResponse(roleScope, roleAssignmentName, Context.NONE); - } - - /** - * Deletes a {@link KeyVaultRoleAssignment role assignment}. - * - *

Code Samples

- *

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

- * - *
-     * 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}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} with a {@link Void} value. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope roleScope} or {@link String roleAssignmentName} are - * {@code null}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleAssignmentName, - Context context) { - - validateRoleAssignmentParameters(roleScope, roleAssignmentName); - - try { - Response roleAssignmentResponse = implClient.getRoleAssignments() - .deleteWithResponse(roleScope.toString(), roleAssignmentName, new RequestOptions().setContext(context)); - - return new SimpleResponse<>(roleAssignmentResponse, null); - } catch (HttpResponseException e) { - KeyVaultAdministrationException mappedException = toKeyVaultAdministrationException(e); - return swallowExceptionForStatusCodeSync(404, mappedException, LOGGER); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } -} 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 deleted file mode 100644 index 679067a67aaf..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilder.java +++ /dev/null @@ -1,522 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeader; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.policy.AddHeadersPolicy; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.HttpPolicyProviders; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.ServiceVersion; -import com.azure.core.util.TracingOptions; -import com.azure.core.util.builder.ClientBuilderUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.tracing.Tracer; -import com.azure.core.util.tracing.TracerProvider; -import com.azure.security.keyvault.administration.implementation.KeyVaultCredentialPolicy; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * This class provides a fluent builder API to help aid the configuration and instantiation of the - * {@link KeyVaultAccessControlAsyncClient access control async client} and - * {@link KeyVaultAccessControlClient access control sync client}, by calling - * {@link KeyVaultAccessControlClientBuilder#buildAsyncClient() buildAsyncClient} and - * {@link KeyVaultAccessControlClientBuilder#buildClient() buildClient} respectively. It constructs an instance of the - * desired client. - * - *

The minimal configuration options required by {@link KeyVaultAccessControlClientBuilder} to build a - * {@link KeyVaultAccessControlAsyncClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

- * - * - *
- * KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .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 KeyVaultAccessControlClientBuilder}.

- * - * - *
- * KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder()
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- *     .httpClient(HttpClient.createDefault())
- *     .buildAsyncClient();
- * 
- * - * - *

The minimal configuration options required by {@link KeyVaultAccessControlClientBuilder} to build a - * {@link KeyVaultAccessControlClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

- * - * - *
- * KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - * @see KeyVaultAccessControlAsyncClient - * @see KeyVaultAccessControlClient - */ -@ServiceClientBuilder(serviceClients = { KeyVaultAccessControlClient.class, KeyVaultAccessControlAsyncClient.class }) -public final class KeyVaultAccessControlClientBuilder - implements TokenCredentialTrait, HttpTrait, - ConfigurationTrait { - - // This is the properties file name. - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultAccessControlClientBuilder.class); - private static final String AZURE_KEY_VAULT_RBAC = "azure-security-keyvault-administration.properties"; - private static final String SDK_NAME = "name"; - private static final String SDK_VERSION = "version"; - private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); - - private final List perCallPolicies; - private final List perRetryPolicies; - private final Map properties; - - // Please see here - // for more information on Azure resource provider namespaces. - private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; - - private TokenCredential credential; - private HttpPipeline pipeline; - private URL vaultUrl; - private HttpClient httpClient; - private HttpLogOptions httpLogOptions; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - private Configuration configuration; - private ClientOptions clientOptions; - private KeyVaultAdministrationServiceVersion serviceVersion; - private boolean disableChallengeResourceVerification = false; - - /** - * Creates a {@link KeyVaultAccessControlClientBuilder} instance that is able to configure and construct - * instances of {@link KeyVaultAccessControlClient} and {@link KeyVaultAccessControlAsyncClient}. - */ - public KeyVaultAccessControlClientBuilder() { - httpLogOptions = new HttpLogOptions(); - perCallPolicies = new ArrayList<>(); - perRetryPolicies = new ArrayList<>(); - properties = CoreUtils.getProperties(AZURE_KEY_VAULT_RBAC); - } - - /** - * Creates an {@link KeyVaultAccessControlClient} based on options set in the Builder. Every time {@code - * buildClient()} is called a new instance of {@link KeyVaultAccessControlClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline} and - * {@link #vaultUrl(String) vaultUrl} are used to create the {@link KeyVaultAccessControlClient client}. All other - * builder settings are ignored. - * - * @return An {@link KeyVaultAccessControlClient} with the options set from the builder. - * - * @throws NullPointerException If {@code vaultUrl} is {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public KeyVaultAccessControlClient buildClient() { - Configuration buildConfiguration = validateEndpointAndGetConfiguration(); - serviceVersion = getServiceVersion(); - - if (pipeline != null) { - return new KeyVaultAccessControlClient(vaultUrl, pipeline, serviceVersion); - } - - HttpPipeline builtPipeline = getPipeline(buildConfiguration, serviceVersion); - - return new KeyVaultAccessControlClient(vaultUrl, builtPipeline, serviceVersion); - } - - /** - * Creates a {@link KeyVaultAccessControlAsyncClient} based on options set in the Builder. Every time {@code - * buildAsyncClient()} is called a new instance of {@link KeyVaultAccessControlAsyncClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline} and - * {@link #vaultUrl(String) endpoint} are used to create the {@link KeyVaultAccessControlAsyncClient client}. All - * other builder settings are ignored. - * - * @return An {@link KeyVaultAccessControlAsyncClient} with the options set from the builder. - * - * @throws NullPointerException If {@code vaultUrl} is {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public KeyVaultAccessControlAsyncClient buildAsyncClient() { - Configuration buildConfiguration = validateEndpointAndGetConfiguration(); - serviceVersion = getServiceVersion(); - - if (pipeline != null) { - return new KeyVaultAccessControlAsyncClient(vaultUrl, pipeline, serviceVersion); - } - - HttpPipeline builtPipeline = getPipeline(buildConfiguration, serviceVersion); - - return new KeyVaultAccessControlAsyncClient(vaultUrl, builtPipeline, serviceVersion); - } - - private Configuration validateEndpointAndGetConfiguration() { - Configuration buildConfiguration - = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; - URL buildEndpoint = getBuildEndpoint(buildConfiguration); - - if (buildEndpoint == null) { - throw LOGGER - .logExceptionAsError(new IllegalStateException(KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED)); - } - - return buildConfiguration; - } - - private KeyVaultAdministrationServiceVersion getServiceVersion() { - return serviceVersion != null ? serviceVersion : KeyVaultAdministrationServiceVersion.getLatest(); - } - - private HttpPipeline getPipeline(Configuration buildConfiguration, ServiceVersion serviceVersion) { - // Closest to API goes first, closest to wire goes last. - final List policies = new ArrayList<>(); - - String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); - String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); - - httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; - - ClientOptions localClientOptions = clientOptions != null ? clientOptions : DEFAULT_CLIENT_OPTIONS; - - policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, - clientVersion, buildConfiguration)); - - List httpHeaderList = new ArrayList<>(); - localClientOptions.getHeaders() - .forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); - policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); - - // Add per call additional policies. - policies.addAll(perCallPolicies); - HttpPolicyProviders.addBeforeRetryPolicies(policies); - - // Add retry policy. - policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); - - policies.add(new KeyVaultCredentialPolicy(credential, disableChallengeResourceVerification)); - - // Add per retry additional policies. - policies.addAll(perRetryPolicies); - - HttpPolicyProviders.addAfterRetryPolicies(policies); - policies.add(new HttpLoggingPolicy(httpLogOptions)); - - TracingOptions tracingOptions = localClientOptions.getTracingOptions(); - Tracer tracer = TracerProvider.getDefaultProvider() - .createTracer(clientName, clientVersion, KEYVAULT_TRACING_NAMESPACE_VALUE, tracingOptions); - - return new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) - .httpClient(httpClient) - .tracer(tracer) - .clientOptions(localClientOptions) - .build(); - } - - /** - * Sets the URL to the Key Vault on which the client operates. Appears as "DNS Name" in the Azure portal. You should - * validate that this URL references a valid Key Vault or Managed HSM resource. - * Refer to the following documentation for details. - * - * @param vaultUrl The vault URL is used as destination on Azure to send requests to. - * - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - * - * @throws IllegalArgumentException If {@code vaultUrl} cannot be parsed into a valid URL. - * @throws NullPointerException If {@code credential} is {@code null}. - */ - public KeyVaultAccessControlClientBuilder vaultUrl(String vaultUrl) { - if (vaultUrl == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); - } - - try { - this.vaultUrl = new URL(vaultUrl); - } catch (MalformedURLException e) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("The Azure Key Vault URL is malformed.", e)); - } - - return this; - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - * - * @throws NullPointerException If {@code credential} is {@code null}. - */ - @Override - public KeyVaultAccessControlClientBuilder credential(TokenCredential credential) { - if (credential == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); - } - - this.credential = credential; - - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - */ - @Override - public KeyVaultAccessControlClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; - - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - * - * @throws NullPointerException If {@code policy} is {@code null}. - */ - @Override - public KeyVaultAccessControlClientBuilder addPolicy(HttpPipelinePolicy policy) { - if (policy == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); - } - - if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { - perCallPolicies.add(policy); - } else { - perRetryPolicies.add(policy); - } - - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - */ - @Override - public KeyVaultAccessControlClientBuilder httpClient(HttpClient client) { - this.httpClient = client; - - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * The {@link #vaultUrl(String) vaultUrl} is not ignored when - * {@code pipeline} is set. - * - * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - */ - @Override - public KeyVaultAccessControlClientBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - - return this; - } - - /** - * Sets the configuration store that is used during construction of the service client. - *

- * The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global - * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. - * - * @param configuration The configuration store used to get configuration details. - * - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - */ - @Override - public KeyVaultAccessControlClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - - return this; - } - - /** - * Sets the {@link RetryPolicy} that is used when each request is sent. - *

- * The default retry policy will be used in the pipeline, if not provided. - *

- * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy User's retry policy applied to each request. - * - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - */ - public KeyVaultAccessControlClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - */ - @Override - public KeyVaultAccessControlClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - - return this; - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * @see HttpClientOptions - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - */ - @Override - public KeyVaultAccessControlClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - - return this; - } - - /** - * Sets the {@link KeyVaultAdministrationServiceVersion} that is used when making API requests. - * - * If a service version is not provided, the service version that will be used will be the latest known service - * version based on the version of the client library being used. If no service version is specified, updating to a - * newer version the client library will have the result of potentially moving to a newer service version. - * - * @param serviceVersion {@link KeyVaultAdministrationServiceVersion} of the service API used when making requests. - * - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - */ - public KeyVaultAccessControlClientBuilder serviceVersion(KeyVaultAdministrationServiceVersion serviceVersion) { - this.serviceVersion = serviceVersion; - - return this; - } - - /** - * Disables verifying if the authentication challenge resource matches the Key Vault or Managed HSM domain. This - * verification is performed by default. - * - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - */ - public KeyVaultAccessControlClientBuilder disableChallengeResourceVerification() { - this.disableChallengeResourceVerification = true; - - return this; - } - - private URL getBuildEndpoint(Configuration configuration) { - if (vaultUrl != null) { - return vaultUrl; - } - - String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); - - if (CoreUtils.isNullOrEmpty(configEndpoint)) { - return null; - } - - try { - return new URL(configEndpoint); - } catch (MalformedURLException ex) { - return null; - } - } -} 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 deleted file mode 100644 index f816b886c8cb..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationServiceVersion.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.util.ServiceVersion; - -/** - * 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}. - */ - V7_3("7.3"), - - /** - * Service version {@code 7.4}. - */ - V7_4("7.4"), - - /** - * Service version {@code 7.5}. - */ - V7_5("7.5"), - - /** - * Service version {@code 7.6-preview.1}. - */ - V7_6_PREVIEW_1("7.6-preview.1"); - - private final String version; - - KeyVaultAdministrationServiceVersion(String version) { - this.version = version; - } - - @Override - public String getVersion() { - return this.version; - } - - /** - * Gets the latest service version supported by this client library. - * - * @return The latest {@link KeyVaultAdministrationServiceVersion}. - */ - public static KeyVaultAdministrationServiceVersion getLatest() { - return V7_6_PREVIEW_1; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationUtil.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationUtil.java deleted file mode 100644 index 3677431898f1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationUtil.java +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.RequestOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.BinaryData; -import com.azure.core.util.IterableStream; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.security.keyvault.administration.implementation.models.FullBackupOperation; -import com.azure.security.keyvault.administration.implementation.models.Permission; -import com.azure.security.keyvault.administration.implementation.models.RestoreOperation; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignment; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignmentCreateParameters; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignmentProperties; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignmentPropertiesWithScope; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinition; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinitionCreateParameters; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinitionProperties; -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; -import com.azure.security.keyvault.administration.models.KeyVaultDataAction; -import com.azure.security.keyvault.administration.models.KeyVaultLongRunningOperation; -import com.azure.security.keyvault.administration.models.KeyVaultPermission; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignmentProperties; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinitionType; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.KeyVaultRoleType; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.models.SetRoleDefinitionOptions; -import reactor.core.publisher.Mono; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils.toKeyVaultAdministrationError; - -/** - * Internal utility class for KeyVault Administration clients. - */ -class KeyVaultAdministrationUtil { - private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable"; - - static final String VAULT_END_POINT_REQUIRED = "Azure Key Vault endpoint url is required."; - static final String PARAMETER_REQUIRED = "%s cannot be null."; - - public static final RequestOptions EMPTY_OPTIONS = new RequestOptions(); - - /** - * Deserializes a given {@link Response HTTP response} including headers to a given class. - * - * @param statusCode The status code which will trigger exception swallowing. - * @param httpResponseException The {@link HttpResponseException} to be swallowed. - * @param logger {@link ClientLogger} that will be used to record the exception. - * @param The class of the exception to swallow. - * - * @return A {@link Mono} that contains the deserialized response. - */ - static Mono> swallowExceptionForStatusCodeAsync(int statusCode, - E httpResponseException, ClientLogger logger) { - try { - return Mono.just(swallowExceptionForStatusCodeSync(statusCode, httpResponseException, logger)); - } catch (RuntimeException e) { - return Mono.error(e); - } - } - - /** - * Synchronously deserializes a given {@link Response HTTP response} including headers to a given class. - * - * @param statusCode The status code which will trigger exception swallowing. - * @param httpResponseException The {@link HttpResponseException} to be swallowed. - * @param logger {@link ClientLogger} that will be used to record the exception. - * @param The class of the exception to swallow. - * - * @return the deserialized response. - */ - static Response swallowExceptionForStatusCodeSync(int statusCode, - E httpResponseException, ClientLogger logger) { - - HttpResponse httpResponse = httpResponseException.getResponse(); - - if (httpResponse.getStatusCode() == statusCode) { - return new SimpleResponse<>(httpResponse.getRequest(), httpResponse.getStatusCode(), - httpResponse.getHeaders(), null); - } - - throw logger.logExceptionAsError(httpResponseException); - } - - static RoleAssignmentCreateParameters validateAndGetRoleAssignmentCreateParameters(KeyVaultRoleScope roleScope, - String roleDefinitionId, String principalId, String roleAssignmentName) { - validateRoleAssignmentParameters(roleScope, roleAssignmentName); - Objects.requireNonNull(principalId, String.format(PARAMETER_REQUIRED, "'principalId'")); - Objects.requireNonNull(roleDefinitionId, String.format(PARAMETER_REQUIRED, "'roleDefinitionId'")); - - RoleAssignmentProperties roleAssignmentProperties = new RoleAssignmentProperties(roleDefinitionId, principalId); - return new RoleAssignmentCreateParameters(roleAssignmentProperties); - } - - static RoleDefinitionCreateParameters - validateAndGetRoleDefinitionCreateParameters(SetRoleDefinitionOptions options) { - Objects.requireNonNull(options, String.format(PARAMETER_REQUIRED, "'options'")); - Objects.requireNonNull(options.getRoleScope(), String.format(PARAMETER_REQUIRED, "'options.getRoleScope()'")); - Objects.requireNonNull(options.getRoleDefinitionName(), - String.format(PARAMETER_REQUIRED, "'options.getRoleDefinitionName()'")); - - List permissions = null; - - if (options.getPermissions() != null) { - permissions = options.getPermissions() - .stream() - .map(keyVaultPermission -> new Permission().setActions(keyVaultPermission.getActions()) - .setNotActions(keyVaultPermission.getNotActions()) - .setDataActions(keyVaultPermission.getDataActions()) - .setNotDataActions(keyVaultPermission.getNotDataActions())) - .collect(Collectors.toList()); - } - - RoleDefinitionProperties roleDefinitionProperties - = new RoleDefinitionProperties().setRoleName(options.getRoleDefinitionName()) - .setAssignableScopes(options.getAssignableScopes()) - .setDescription(options.getDescription()) - .setPermissions(permissions); - return new RoleDefinitionCreateParameters(roleDefinitionProperties); - } - - static void validateRoleAssignmentParameters(KeyVaultRoleScope roleScope, String roleAssignmentName) { - Objects.requireNonNull(roleScope, String.format(PARAMETER_REQUIRED, "'roleScope'")); - Objects.requireNonNull(roleAssignmentName, String.format(PARAMETER_REQUIRED, "'roleAssignmentName'")); - } - - static void validateRoleDefinitionParameters(KeyVaultRoleScope roleScope, String roleDefinitionName) { - Objects.requireNonNull(roleScope, String.format(PARAMETER_REQUIRED, "'roleScope'")); - Objects.requireNonNull(roleDefinitionName, String.format(PARAMETER_REQUIRED, "'roleDefinitionName'")); - } - - @SuppressWarnings("BoundedWildcard") - static PagedResponse - transformRoleDefinitionsPagedResponse(PagedResponse pagedResponse) { - - List keyVaultRoleDefinitions = new ArrayList<>(); - - for (RoleDefinition roleDefinition : pagedResponse.getValue()) { - keyVaultRoleDefinitions.add(roleDefinitionToKeyVaultRoleDefinition(roleDefinition)); - } - - return new TransformedPagedResponse<>(keyVaultRoleDefinitions, pagedResponse); - } - - static Response transformBinaryDataResponse(Response response, Class clazz) { - if (response == null) { - return null; - } - - BinaryData binaryData = response.getValue(); - - if (binaryData == null) { - return new SimpleResponse<>(response, null); - } - - return new SimpleResponse<>(response, BinaryData.fromObject(response.getValue()).toObject(clazz)); - } - - static Response transformBinaryDataResponse(Response response, - Function transformationFunction) { - if (response == null) { - return null; - } - - BinaryData binaryData = response.getValue(); - - if (binaryData == null) { - return new SimpleResponse<>(response, null); - } - - return new SimpleResponse<>(response, transformationFunction.apply(binaryData)); - } - - static KeyVaultRoleDefinition roleDefinitionToKeyVaultRoleDefinition(RoleDefinition roleDefinition) { - List keyVaultPermissions = new ArrayList<>(); - - for (Permission permission : roleDefinition.getProperties().getPermissions()) { - keyVaultPermissions.add(new KeyVaultPermission(permission.getActions(), permission.getNotActions(), - permission.getDataActions() - .stream() - .map(dataAction -> KeyVaultDataAction.fromString(dataAction.toString())) - .collect(Collectors.toList()), - permission.getNotDataActions() - .stream() - .map(notDataAction -> KeyVaultDataAction.fromString(notDataAction.toString())) - .collect(Collectors.toList()))); - } - - return new KeyVaultRoleDefinition(roleDefinition.getId(), roleDefinition.getName(), - KeyVaultRoleDefinitionType.fromString(roleDefinition.getType().toString()), - roleDefinition.getProperties().getRoleName(), roleDefinition.getProperties().getDescription(), - KeyVaultRoleType.fromString(roleDefinition.getProperties().getRoleType().toString()), keyVaultPermissions, - roleDefinition.getProperties() - .getAssignableScopes() - .stream() - .map(roleScope -> KeyVaultRoleScope.fromString(roleScope.toString())) - .collect(Collectors.toList())); - } - - static KeyVaultRoleAssignment roleAssignmentToKeyVaultRoleAssignment(RoleAssignment roleAssignment) { - RoleAssignmentPropertiesWithScope propertiesWithScope = roleAssignment.getProperties(); - - return new KeyVaultRoleAssignment(roleAssignment.getId(), roleAssignment.getName(), roleAssignment.getType(), - new KeyVaultRoleAssignmentProperties(propertiesWithScope.getRoleDefinitionId(), - propertiesWithScope.getPrincipalId(), - KeyVaultRoleScope.fromString(propertiesWithScope.getScope().toString()))); - } - - private static final class TransformedPagedResponse, T, U> implements PagedResponse { - private final L output; - private final PagedResponse pagedResponse; - - TransformedPagedResponse(L output, PagedResponse inputPagedResponse) { - this.output = output; - this.pagedResponse = inputPagedResponse; - } - - @Override - public void close() throws IOException { - } - - @Override - public IterableStream getElements() { - return new IterableStream<>(output); - } - - @Override - public String getContinuationToken() { - return pagedResponse.getContinuationToken(); - } - - @Override - public int getStatusCode() { - return pagedResponse.getStatusCode(); - } - - @Override - public HttpHeaders getHeaders() { - return pagedResponse.getHeaders(); - } - - @Override - public HttpRequest getRequest() { - return pagedResponse.getRequest(); - } - - @Override - public List getValue() { - return output; - } - } - - static LongRunningOperationStatus toLongRunningOperationStatus(String operationStatus) { - switch (operationStatus) { - case "inprogress": - return LongRunningOperationStatus.IN_PROGRESS; - - case "succeeded": - return LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; - - case "failed": - return LongRunningOperationStatus.FAILED; - - default: - // Should not reach here - return LongRunningOperationStatus.fromString("POLLING_FAILED", true); - } - } - - static KeyVaultLongRunningOperation transformToLongRunningOperation(O operation) { - if (operation instanceof RestoreOperation) { - RestoreOperation restoreOperation = (RestoreOperation) operation; - - return new KeyVaultRestoreOperation(restoreOperation.getStatus().getValue(), - restoreOperation.getStatusDetails(), toKeyVaultAdministrationError(restoreOperation.getError()), - restoreOperation.getJobId(), restoreOperation.getStartTime(), restoreOperation.getEndTime()); - } else if (operation instanceof SelectiveKeyRestoreOperation) { - SelectiveKeyRestoreOperation selectiveKeyRestoreOperation = (SelectiveKeyRestoreOperation) operation; - - return new KeyVaultSelectiveKeyRestoreOperation(selectiveKeyRestoreOperation.getStatus().getValue(), - selectiveKeyRestoreOperation.getStatusDetails(), - toKeyVaultAdministrationError(selectiveKeyRestoreOperation.getError()), - selectiveKeyRestoreOperation.getJobId(), selectiveKeyRestoreOperation.getStartTime(), - selectiveKeyRestoreOperation.getEndTime()); - } else if (operation instanceof FullBackupOperation) { - FullBackupOperation fullBackupOperation = (FullBackupOperation) operation; - - return new KeyVaultBackupOperation(fullBackupOperation.getStatus().getValue(), - fullBackupOperation.getStatusDetails(), toKeyVaultAdministrationError(fullBackupOperation.getError()), - fullBackupOperation.getJobId(), fullBackupOperation.getStartTime(), fullBackupOperation.getEndTime(), - fullBackupOperation.getAzureStorageBlobContainerUri()); - } else { - throw new UnsupportedOperationException(); - } - } - - static PagedResponse mapPagedResponse(PagedResponse page, Function itemMapper) { - List mappedValues = new ArrayList<>(page.getValue().size()); - - for (T item : page.getValue()) { - mappedValues.add(itemMapper.apply(item)); - } - - return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), mappedValues, - page.getContinuationToken(), null); - } -} 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 deleted file mode 100644 index eda835557883..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClient.java +++ /dev/null @@ -1,908 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.RequestOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.PollerFlux; -import com.azure.core.util.polling.PollingContext; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; -import com.azure.security.keyvault.administration.implementation.models.FullBackupOperation; -import com.azure.security.keyvault.administration.implementation.models.PreBackupOperationParameters; -import com.azure.security.keyvault.administration.implementation.models.PreRestoreOperationParameters; -import com.azure.security.keyvault.administration.implementation.models.RestoreOperation; -import com.azure.security.keyvault.administration.implementation.models.RestoreOperationParameters; -import com.azure.security.keyvault.administration.implementation.models.SASTokenParameter; -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperationParameters; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; -import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; -import reactor.core.publisher.Mono; - -import java.net.URL; -import java.time.Duration; -import java.util.Locale; -import java.util.Objects; -import java.util.function.Function; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.core.util.FluxUtil.withContext; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.toLongRunningOperationStatus; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.transformToLongRunningOperation; - -/** - * The {@link KeyVaultBackupAsyncClient} provides asynchronous methods to perform full a backup and restore of a key - * vault, as well as selectively restoring specific keys from a backup. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link KeyVaultBackupAsyncClient} class, a vault url and a credential object.

- * - *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, - * which is appropriate for most scenarios, including local development and production environments. Additionally, - * we recommend using a - * - * managed identity for authentication in production environments. - * You can find more information on different ways of authenticating and their corresponding credential types in the - * - * Azure Identity documentation".

- * - *

Sample: Construct Asynchronous Backup Client

- * - *

The following code sample demonstrates the creation of a {@link KeyVaultBackupAsyncClient}, using the - * {@link KeyVaultBackupClientBuilder} to configure it.

- * - * - *
- * KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildAsyncClient();
- * 
- * - * - *
- * - *
- * - *

Back Up a Collection of Keys

- * The {@link KeyVaultBackupAsyncClient} can be used to back up the entire collection of keys from a key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously back up an entire collection of keys using, using the - * {@link KeyVaultBackupAsyncClient#beginBackup(String, String)} API.

- * - * - *
- * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
- * String sasToken = "<sas-token>";
- *
- * 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));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultBackupClient}.

- * - *
- * - *
- * - *

Restore a Collection of Keys

- * The {@link KeyVaultBackupAsyncClient} can be used to restore an entire collection of keys from a backup. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously restore an entire collection of keys from a backup, - * using the {@link KeyVaultBackupAsyncClient#beginRestore(String, String)} API.

- * - * - *
- * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
- * String sasToken = "<sas-token>";
- *
- * 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"));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultBackupClient}.

- * - *
- * - *
- * - *

Selectively Restore a Key

- * The {@link KeyVaultBackupAsyncClient} can be used to restore a specific key from a backup. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously restore a specific key from a backup, using - * the {@link KeyVaultBackupAsyncClient#beginSelectiveKeyRestore(String, String, String)} API.

- * - * - *
- * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
- * String sasToken = "<sas-token>";
- * 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"));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultBackupClient}.

- * - *
- * - *
- * - * @see com.azure.security.keyvault.administration - * @see KeyVaultBackupClientBuilder - */ -@ServiceClient(builder = KeyVaultBackupClientBuilder.class, isAsync = true) -public final class KeyVaultBackupAsyncClient { - /** - * The logger to be used. - */ - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultBackupAsyncClient.class); - - private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); - - /** - * The underlying AutoRest client used to interact with the Key Vault service. - */ - private final KeyVaultAdministrationClientImpl clientImpl; - - /** - * The Key Vault URL this client is associated to. - */ - private final String vaultUrl; - - /** - * The {@link HttpPipeline} powering this client. - */ - private final HttpPipeline pipeline; - - Duration getDefaultPollingInterval() { - return DEFAULT_POLLING_INTERVAL; - } - - /** - * Package private constructor to be used by {@link KeyVaultBackupClientBuilder}. - */ - KeyVaultBackupAsyncClient(URL vaultUrl, HttpPipeline httpPipeline, - KeyVaultAdministrationServiceVersion serviceVersion) { - Objects.requireNonNull(vaultUrl, KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED); - - this.vaultUrl = vaultUrl.toString(); - this.pipeline = httpPipeline; - - clientImpl = new KeyVaultAdministrationClientImpl(httpPipeline, this.vaultUrl, serviceVersion); - } - - /** - * Gets the URL for the Key Vault this client is associated with. - * - * @return The Key Vault URL. - */ - public String getVaultUrl() { - return this.vaultUrl; - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.pipeline; - } - - /** - * Initiates a full backup of the Key Vault. - * - *

Code Samples

- *

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.

- * - *
-     * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
-     * String sasToken = "<sas-token>";
-     *
-     * 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 Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultBackupOperation backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code blobStorageUrl} or {@code sasToken} are invalid. - * @throws NullPointerException If the {@code blobStorageUrl} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginBackup(String blobStorageUrl, String sasToken) { - if (blobStorageUrl == null) { - throw LOGGER.logExceptionAsError(new NullPointerException( - String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'blobStorageUrl'"))); - } - - return new PollerFlux<>(getDefaultPollingInterval(), backupActivationOperation(blobStorageUrl, sasToken), - backupPollOperation(), - (pollingContext, firstResponse) -> Mono - .error(LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported"))), - backupFetchOperation()); - } - - /** - * Initiates a full backup of the Key Vault. - * - * @param blobStorageUrl The URL for the Blob Storage resource where the backup will be located. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultBackupOperation backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code blobStorageUrl} or {@code sasToken} are invalid. - */ - Mono> backupWithResponse(String blobStorageUrl, String sasToken, - Context context) { - - SASTokenParameter sasTokenParameter - = new SASTokenParameter(blobStorageUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null); - - try { - return clientImpl - .fullBackupWithResponseAsync(BinaryData.fromObject(sasTokenParameter), - new RequestOptions().setContext(context)) - .map(backupOperationResponse -> new SimpleResponse<>(backupOperationResponse.getRequest(), - backupOperationResponse.getStatusCode(), backupOperationResponse.getHeaders(), - (KeyVaultBackupOperation) transformToLongRunningOperation( - backupOperationResponse.getValue().toObject(FullBackupOperation.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - private Function, Mono> - backupActivationOperation(String blobStorageUrl, String sasToken) { - - return (pollingContext) -> { - try { - return withContext(context -> backupWithResponse(blobStorageUrl, sasToken, context)) - .flatMap(backupResponse -> Mono.just(backupResponse.getValue())); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - }; - } - - private Function, Mono>> - backupPollOperation() { - - return (pollingContext) -> { - try { - PollResponse pollResponse = pollingContext.getLatestResponse(); - - if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED - || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) { - return Mono.just(pollResponse); - } - - final KeyVaultBackupOperation keyVaultBackupOperation = pollResponse.getValue(); - - if (keyVaultBackupOperation == null) { - LOGGER.warning("Backup operation does not exist. Activation operation failed."); - - return Mono.just(new PollResponse( - LongRunningOperationStatus.fromString("BACKUP_START_FAILED", true), null)); - } - - final String jobId = keyVaultBackupOperation.getOperationId(); - - return withContext(context -> clientImpl.fullBackupStatusWithResponseAsync(jobId, - new RequestOptions().setContext(context))) - .map(response -> new SimpleResponse<>(response, - (KeyVaultBackupOperation) transformToLongRunningOperation( - response.getValue().toObject(FullBackupOperation.class)))) - .flatMap(KeyVaultBackupAsyncClient::processBackupOperationResponse); - } catch (HttpResponseException e) { - //noinspection ThrowableNotThrown - LOGGER.logExceptionAsError(e); - - return Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, null)); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - }; - } - - private Function, Mono> backupFetchOperation() { - return (pollingContext) -> { - try { - String blobContainerUri - = pollingContext.getLatestResponse().getValue().getAzureStorageBlobContainerUrl(); - - if (blobContainerUri == null) { - return Mono.empty(); - } else { - return Mono.just(blobContainerUri); - } - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - }; - } - - private static Mono> - processBackupOperationResponse(Response response) { - - String operationStatus = response.getValue().getStatus().toLowerCase(Locale.US); - - return Mono.just(new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)), - response.getValue())); - } - - /** - * Initiates a pre-backup check on the Key Vault. This operation checks if it is possible to back up the entire - * collection of keys from a key vault. - * - *

Code Samples

- *

Starts a {@link KeyVaultBackupOperation pre-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.

- * - *
-     * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
-     * String sasToken = "<sas-token>";
-     *
-     * client.beginPreBackup(blobStorageUrl, sasToken)
-     *     .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval.
-     *     .doOnError(e -> System.out.printf("Pre-backup check 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("Pre-backup check completed successfully.%n"));
-     * 
- * - * - * @param blobStorageUrl The URL for the Blob Storage resource where the backup will be located. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultBackupOperation pre-backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code blobStorageUrl} or {@code sasToken} are invalid. - * @throws NullPointerException If the {@code blobStorageUrl} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginPreBackup(String blobStorageUrl, String sasToken) { - if (blobStorageUrl == null) { - throw LOGGER.logExceptionAsError(new NullPointerException( - String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'blobStorageUrl'"))); - } - - return new PollerFlux<>(getDefaultPollingInterval(), preBackupActivationOperation(blobStorageUrl, sasToken), - backupPollOperation(), - (pollingContext, firstResponse) -> Mono - .error(LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported"))), - backupFetchOperation()); - } - - /** - * Initiates a pre-backup check on the Key Vault. This operation checks if it is possible to back up the entire - * collection of keys from a key vault. - * - * @param blobStorageUrl The URL for the Blob Storage resource where the backup will be located. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultBackupOperation pre-backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code blobStorageUrl} or {@code sasToken} are invalid. - */ - Mono> preBackupWithResponse(String blobStorageUrl, String sasToken, - Context context) { - - PreBackupOperationParameters preBackupOperationParameters - = new PreBackupOperationParameters().setStorageResourceUri(blobStorageUrl) - .setToken(sasToken) - .setUseManagedIdentity(sasToken == null); - - try { - return clientImpl - .preFullBackupWithResponseAsync(BinaryData.fromObject(preBackupOperationParameters), - new RequestOptions().setContext(context)) - .map(backupOperationResponse -> new SimpleResponse<>(backupOperationResponse.getRequest(), - backupOperationResponse.getStatusCode(), backupOperationResponse.getHeaders(), - (KeyVaultBackupOperation) transformToLongRunningOperation( - backupOperationResponse.getValue().toObject(FullBackupOperation.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - private Function, Mono> - preBackupActivationOperation(String blobStorageUrl, String sasToken) { - - return (pollingContext) -> { - try { - return withContext(context -> preBackupWithResponse(blobStorageUrl, sasToken, context)) - .flatMap(backupResponse -> Mono.just(backupResponse.getValue())); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - }; - } - - /** - * Initiates a full restore of the Key Vault. - * - *

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.

- * - *
-     * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
-     * String sasToken = "<sas-token>";
-     *
-     * 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 - * backup operation. An example of such a URL may look like the following: - * https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultRestoreOperation restore operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code folderUrl} or {@code sasToken} are invalid. - * @throws NullPointerException If the {@code folderUrl} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginRestore(String folderUrl, String sasToken) { - if (folderUrl == null) { - throw LOGGER.logExceptionAsError( - new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'"))); - } - - return new PollerFlux<>(getDefaultPollingInterval(), restoreActivationOperation(folderUrl, sasToken), - restorePollOperation(), - (pollingContext, firstResponse) -> Mono - .error(LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported"))), - (pollingContext) -> Mono.just(new KeyVaultRestoreResult())); - } - - /** - * Initiates a full restore of the Key Vault. - * - * @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 - * backup operation. An example of such a URL may look like the following: - * https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultRestoreOperation backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code folderUrl} or {@code sasToken} are invalid. - */ - Mono> restoreWithResponse(String folderUrl, String sasToken, Context context) { - String[] segments = folderUrl.split("/"); - String folderName = segments[segments.length - 1]; - String containerUrl = folderUrl.substring(0, folderUrl.length() - folderName.length()); - - SASTokenParameter sasTokenParameter - = new SASTokenParameter(containerUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null); - - RestoreOperationParameters restoreOperationParameters - = new RestoreOperationParameters(sasTokenParameter, folderName); - - try { - return clientImpl - .fullRestoreOperationWithResponseAsync(BinaryData.fromObject(restoreOperationParameters), - new RequestOptions().setContext(context)) - .map(restoreOperationResponse -> new SimpleResponse<>(restoreOperationResponse.getRequest(), - restoreOperationResponse.getStatusCode(), restoreOperationResponse.getHeaders(), - (KeyVaultRestoreOperation) transformToLongRunningOperation( - restoreOperationResponse.getValue().toObject(RestoreOperation.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - private Function, Mono> - restoreActivationOperation(String folderUrl, String sasToken) { - - return (pollingContext) -> { - try { - return withContext(context -> restoreWithResponse(folderUrl, sasToken, context)) - .flatMap(restoreResponse -> Mono.just(restoreResponse.getValue())); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - }; - } - - private Function, Mono>> - restorePollOperation() { - - return (pollingContext) -> { - try { - PollResponse pollResponse = pollingContext.getLatestResponse(); - - if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED - || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) { - - return Mono.just(pollResponse); - } - - final KeyVaultRestoreOperation keyVaultRestoreOperation = pollResponse.getValue(); - - if (keyVaultRestoreOperation == null) { - LOGGER.warning("Restore operation does not exist. Activation operation failed."); - - return Mono.just(new PollResponse( - LongRunningOperationStatus.fromString("RESTORE_START_FAILED", true), null)); - } - - final String jobId = keyVaultRestoreOperation.getOperationId(); - - return withContext(context -> clientImpl - .restoreStatusWithResponseAsync(jobId, new RequestOptions().setContext(context)) - .map(response -> new SimpleResponse<>(response, - (KeyVaultRestoreOperation) transformToLongRunningOperation( - response.getValue().toObject(RestoreOperation.class)))) - .flatMap(KeyVaultBackupAsyncClient::processRestoreOperationResponse)); - } catch (HttpResponseException e) { - //noinspection ThrowableNotThrown - LOGGER.logExceptionAsError(e); - - return Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, null)); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - }; - } - - static Mono> - processRestoreOperationResponse(Response response) { - - String operationStatus = response.getValue().getStatus().toLowerCase(Locale.US); - - return Mono.just(new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)), - response.getValue())); - } - - /** - * Initiates a pre-restore check on the Key Vault. This operation checks if it is possible to restore an entire - * collection of keys from a backup. - * - *

Code Samples

- *

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

- * - *
-     * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
-     * String sasToken = "<sas-token>";
-     *
-     * client.beginPreRestore(folderUrl, sasToken)
-     *     .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval.
-     *     .doOnError(e -> System.out.printf("Pre-restore check 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("Pre-restore check completed 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 - * backup operation. An example of such a URL may look like the following: - * {@code https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313}. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultRestoreOperation restore operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code folderUrl} or {@code sasToken} are invalid. - * @throws NullPointerException If the {@code folderUrl} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginPreRestore(String folderUrl, - String sasToken) { - - if (folderUrl == null) { - throw LOGGER.logExceptionAsError( - new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'"))); - } - - return new PollerFlux<>(getDefaultPollingInterval(), preRestoreActivationOperation(folderUrl, sasToken), - restorePollOperation(), - (pollingContext, firstResponse) -> Mono - .error(LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported"))), - (pollingContext) -> Mono.just(new KeyVaultRestoreResult())); - } - - /** - * Initiates a pre-restore check on the Key Vault. This operation checks if it is possible to restore an entire - * collection of keys from a backup. - * - * @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 - * backup operation. An example of such a URL may look like the following: - * {@code https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313}. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultRestoreOperation backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code folderUrl} or {@code sasToken} are invalid. - */ - Mono> preRestoreWithResponse(String folderUrl, String sasToken, - Context context) { - - String[] segments = folderUrl.split("/"); - String folderName = segments[segments.length - 1]; - String containerUrl = folderUrl.substring(0, folderUrl.length() - folderName.length()); - - SASTokenParameter sasTokenParameter - = new SASTokenParameter(containerUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null); - - PreRestoreOperationParameters preRestoreOperationParameters - = new PreRestoreOperationParameters().setFolderToRestore(folderName) - .setSasTokenParameters(sasTokenParameter); - - try { - return clientImpl - .preFullRestoreOperationWithResponseAsync(BinaryData.fromObject(preRestoreOperationParameters), - new RequestOptions().setContext(context)) - .map(restoreOperationResponse -> new SimpleResponse<>(restoreOperationResponse.getRequest(), - restoreOperationResponse.getStatusCode(), restoreOperationResponse.getHeaders(), - (KeyVaultRestoreOperation) transformToLongRunningOperation( - restoreOperationResponse.getValue().toObject(RestoreOperation.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - private Function, Mono> - preRestoreActivationOperation(String folderUrl, String sasToken) { - - return (pollingContext) -> { - try { - return withContext(context -> preRestoreWithResponse(folderUrl, sasToken, context)) - .flatMap(restoreResponse -> Mono.just(restoreResponse.getValue())); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - }; - } - - /** - * Restores all versions of a given key using the supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - *

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.

- * - *
-     * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
-     * String sasToken = "<sas-token>";
-     * 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 - * the blob container where the backup resides. This would be the exact value that is returned as the result of a - * backup operation. An example of such a URL may look like the following: - * https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultRestoreOperation restore operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code keyName}, {@code folderUrl} or {@code sasToken} are - * invalid. - * @throws NullPointerException If the {@code keyName} or {@code folderUrl} are {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux - beginSelectiveKeyRestore(String keyName, String folderUrl, String sasToken) { - - if (keyName == null) { - throw LOGGER.logExceptionAsError( - new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'keyName'"))); - } - - if (folderUrl == null) { - throw LOGGER.logExceptionAsError( - new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'"))); - } - - return new PollerFlux<>(getDefaultPollingInterval(), - selectiveKeyRestoreActivationOperation(keyName, folderUrl, sasToken), selectiveKeyRestorePollOperation(), - (pollingContext, firstResponse) -> Mono - .error(LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported"))), - (pollingContext) -> Mono.just(new KeyVaultSelectiveKeyRestoreResult())); - } - - /** - * Restores all versions of a given key using the supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @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 - * the blob container where the backup resides. This would be the exact value that is returned as the result of a - * backup operation. An example of such a URL may look like the following: - * https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link PollerFlux} polling on the {@link KeyVaultRestoreOperation backup operation} status. - */ - Mono> selectiveKeyRestoreWithResponse(String keyName, - String folderUrl, String sasToken, Context context) { - - String[] segments = folderUrl.split("/"); - String folderName = segments[segments.length - 1]; - String containerUrl = folderUrl.substring(0, folderUrl.length() - folderName.length()); - - SASTokenParameter sasTokenParameter - = new SASTokenParameter(containerUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null); - SelectiveKeyRestoreOperationParameters selectiveKeyRestoreOperationParameters - = new SelectiveKeyRestoreOperationParameters(sasTokenParameter, folderName); - - try { - return clientImpl.selectiveKeyRestoreOperationWithResponseAsync(keyName, - BinaryData.fromObject(selectiveKeyRestoreOperationParameters), new RequestOptions().setContext(context)) - .map(selectiveKeyRestoreOperationResponse -> new SimpleResponse<>( - selectiveKeyRestoreOperationResponse.getRequest(), - selectiveKeyRestoreOperationResponse.getStatusCode(), - selectiveKeyRestoreOperationResponse.getHeaders(), - (KeyVaultSelectiveKeyRestoreOperation) transformToLongRunningOperation( - selectiveKeyRestoreOperationResponse.getValue().toObject(SelectiveKeyRestoreOperation.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - private Function, Mono> - selectiveKeyRestoreActivationOperation(String keyName, String folderUrl, String sasToken) { - - return (pollingContext) -> { - try { - return withContext(context -> selectiveKeyRestoreWithResponse(keyName, folderUrl, sasToken, context)) - .flatMap(selectiveKeyRestoreResponse -> Mono.just(selectiveKeyRestoreResponse.getValue())); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - }; - } - - private - Function, Mono>> - selectiveKeyRestorePollOperation() { - - return (pollingContext) -> { - try { - PollResponse pollResponse = pollingContext.getLatestResponse(); - - if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED - || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) { - - return Mono.just(pollResponse); - } - - final KeyVaultSelectiveKeyRestoreOperation keyVaultSelectiveKeyRestoreOperation - = pollResponse.getValue(); - - if (keyVaultSelectiveKeyRestoreOperation == null) { - LOGGER.warning("Restore operation does not exist. Activation operation failed."); - - return Mono.just(new PollResponse( - LongRunningOperationStatus.fromString("SELECTIVE_RESTORE_START_FAILED", true), null)); - } - - final String jobId = keyVaultSelectiveKeyRestoreOperation.getOperationId(); - - return withContext(context -> clientImpl - .selectiveKeyRestoreStatusWithResponseAsync(jobId, new RequestOptions().setContext(context)) - .map(response -> new SimpleResponse<>(response, - (KeyVaultSelectiveKeyRestoreOperation) transformToLongRunningOperation( - response.getValue().toObject(SelectiveKeyRestoreOperation.class)))) - .flatMap(KeyVaultBackupAsyncClient::processSelectiveKeyRestoreOperationResponse)); - } catch (HttpResponseException e) { - //noinspection ThrowableNotThrown - LOGGER.logExceptionAsError(e); - - return Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, null)); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - }; - } - - private static Mono> - processSelectiveKeyRestoreOperationResponse(Response response) { - - String operationStatus = response.getValue().getStatus().toLowerCase(Locale.US); - - return Mono.just(new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)), - response.getValue())); - } -} 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 deleted file mode 100644 index 1282747dda11..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClient.java +++ /dev/null @@ -1,925 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.RequestOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.PollingContext; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; -import com.azure.security.keyvault.administration.implementation.models.FullBackupOperation; -import com.azure.security.keyvault.administration.implementation.models.PreBackupOperationParameters; -import com.azure.security.keyvault.administration.implementation.models.PreRestoreOperationParameters; -import com.azure.security.keyvault.administration.implementation.models.RestoreOperation; -import com.azure.security.keyvault.administration.implementation.models.RestoreOperationParameters; -import com.azure.security.keyvault.administration.implementation.models.SASTokenParameter; -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperationParameters; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; -import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; - -import java.net.URL; -import java.time.Duration; -import java.util.Locale; -import java.util.Objects; -import java.util.function.Function; - -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.toLongRunningOperationStatus; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.transformToLongRunningOperation; - -/** - * The {@link KeyVaultBackupClient} provides synchronous methods to perform full a backup and restore of a key vault, - * as well as selectively restoring specific keys from a backup. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link KeyVaultBackupClient} class, a vault url and a credential object.

- * - *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, - * which is appropriate for most scenarios, including local development and production environments. Additionally, - * we recommend using a - * - * managed identity for authentication in production environments. - * You can find more information on different ways of authenticating and their corresponding credential types in the - * - * Azure Identity documentation".

- * - *

Sample: Construct Asynchronous Backup Client

- * - *

The following code sample demonstrates the creation of a {@link KeyVaultBackupClient}, using the - * {@link KeyVaultBackupClientBuilder} to configure it.

- * - * - *
- * KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - *
- * - *
- * - *

Back Up a Collection of Keys

- * The {@link KeyVaultBackupClient} can be used to back up the entire collection of keys from a key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the - * {@link KeyVaultBackupClient#beginBackup(String, String)} API.

- * - * - *
- * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
- * String sasToken = "<sas-token>";
- *
- * 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());
- * }
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultBackupAsyncClient}.

- * - *
- * - *
- * - *

Restore a Collection of Keys

- * The {@link KeyVaultBackupClient} can be used to restore an entire collection of keys from a backup. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup, - * using the {@link KeyVaultBackupClient#beginRestore(String, String)} API.

- * - * - *
- * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
- * String sasToken = "<sas-token>";
- *
- * SyncPoller<KeyVaultRestoreOperation, KeyVaultRestoreResult> restorePoller =
- *     client.beginRestore(folderUrl, sasToken);
- * PollResponse<KeyVaultRestoreOperation> pollResponse = restorePoller.poll();
- *
- * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
- *
- * PollResponse<KeyVaultRestoreOperation> finalPollResponse = restorePoller.waitForCompletion();
- *
- * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
- *     System.out.printf("Backup restored successfully.%n");
- * } else {
- *     KeyVaultRestoreOperation operation = restorePoller.poll().getValue();
- *
- *     System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage());
- * }
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultBackupAsyncClient}.

- * - *
- * - *
- * - *

Selectively Restore a Key

- * The {@link KeyVaultBackupClient} can be used to restore a specific key from a backup. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously restore a specific key from a backup, using - * the {@link KeyVaultBackupClient#beginSelectiveKeyRestore(String, String, String)} API.

- * - * - *
- * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
- * String sasToken = "<sas-token>";
- * String keyName = "myKey";
- *
- * SyncPoller<KeyVaultSelectiveKeyRestoreOperation, KeyVaultSelectiveKeyRestoreResult> restorePoller =
- *     client.beginSelectiveKeyRestore(folderUrl, sasToken, keyName);
- * PollResponse<KeyVaultSelectiveKeyRestoreOperation> pollResponse = restorePoller.poll();
- *
- * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
- *
- * PollResponse<KeyVaultSelectiveKeyRestoreOperation> finalPollResponse = restorePoller.waitForCompletion();
- *
- * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
- *     System.out.printf("Key restored successfully.%n");
- * } else {
- *     KeyVaultSelectiveKeyRestoreOperation operation = restorePoller.poll().getValue();
- *
- *     System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage());
- * }
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultBackupAsyncClient}.

- * - *
- * - *
- * - * @see com.azure.security.keyvault.administration - * @see KeyVaultBackupClientBuilder - */ -@ServiceClient(builder = KeyVaultBackupClientBuilder.class) -public final class KeyVaultBackupClient { - /** - * The logger to be used. - */ - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultBackupClient.class); - - private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); - - /** - * The underlying AutoRest client used to interact with the Key Vault service. - */ - private final KeyVaultAdministrationClientImpl clientImpl; - - /** - * The Key Vault URL this client is associated to. - */ - private final String vaultUrl; - - Duration getDefaultPollingInterval() { - return DEFAULT_POLLING_INTERVAL; - } - - /** - * Package private constructor to be used by {@link KeyVaultBackupClientBuilder}. - */ - KeyVaultBackupClient(URL vaultUrl, HttpPipeline httpPipeline, KeyVaultAdministrationServiceVersion serviceVersion) { - Objects.requireNonNull(vaultUrl, KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED); - - this.vaultUrl = vaultUrl.toString(); - - clientImpl = new KeyVaultAdministrationClientImpl(httpPipeline, this.vaultUrl, serviceVersion); - } - - /** - * Get the vault endpoint URL. - * - * @return The vault endpoint URL. - */ - public String getVaultUrl() { - return this.vaultUrl; - } - - /** - * Initiates a full backup of the Key Vault. - * - *

Code Samples

- *

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.

- * - *
-     * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
-     * String sasToken = "<sas-token>";
-     *
-     * 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 Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link SyncPoller} polling on the {@link KeyVaultBackupOperation backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code blobStorageUrl} or {@code sasToken} are invalid. - * @throws NullPointerException If the {@code blobStorageUrl} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginBackup(String blobStorageUrl, String sasToken) { - if (blobStorageUrl == null) { - throw LOGGER.logExceptionAsError(new NullPointerException( - String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'blobStorageUrl'"))); - } - - return SyncPoller.createPoller(getDefaultPollingInterval(), - cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - backupActivationOperation(blobStorageUrl, sasToken, Context.NONE).apply(cxt)), - backupPollOperation(Context.NONE), (pollingContext, firstResponse) -> { - throw LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported")); - }, backupFetchOperation()); - } - - /** - * Initiates a full backup of the Key Vault. - * - * @param blobStorageUrl The URL for the Blob Storage resource where the backup will be located. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} containing the {@link KeyVaultBackupOperation backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code blobStorageUrl} or {@code sasToken} are invalid. - */ - Response backupWithResponse(String blobStorageUrl, String sasToken, Context context) { - SASTokenParameter sasTokenParameter - = new SASTokenParameter(blobStorageUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null); - - try { - Response backupOperationResponse = clientImpl.fullBackupWithResponse( - BinaryData.fromObject(sasTokenParameter), new RequestOptions().setContext(context)); - - return new SimpleResponse<>(backupOperationResponse.getRequest(), backupOperationResponse.getStatusCode(), - backupOperationResponse.getHeaders(), (KeyVaultBackupOperation) transformToLongRunningOperation( - backupOperationResponse.getValue().toObject(FullBackupOperation.class))); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - private Function, KeyVaultBackupOperation> - backupActivationOperation(String blobStorageUrl, String sasToken, Context context) { - - return (pollingContext) -> { - try { - return backupWithResponse(blobStorageUrl, sasToken, context).getValue(); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - }; - } - - private Function, PollResponse> - backupPollOperation(Context context) { - - return (pollingContext) -> { - try { - PollResponse pollResponse = pollingContext.getLatestResponse(); - - if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED - || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) { - - return pollResponse; - } - - final KeyVaultBackupOperation keyVaultBackupOperation = pollResponse.getValue(); - - if (keyVaultBackupOperation == null) { - LOGGER.warning("Backup operation does not exist. Activation operation failed."); - - return new PollResponse<>(LongRunningOperationStatus.fromString("BACKUP_START_FAILED", true), null); - } - - final String jobId = keyVaultBackupOperation.getOperationId(); - Response backupOperationResponse - = clientImpl.fullBackupStatusWithResponse(jobId, new RequestOptions().setContext(context)); - - return processBackupOperationResponse(new SimpleResponse<>(backupOperationResponse, - (KeyVaultBackupOperation) transformToLongRunningOperation( - backupOperationResponse.getValue().toObject(FullBackupOperation.class)))); - } catch (HttpResponseException e) { - //noinspection ThrowableNotThrown - LOGGER.logExceptionAsError(e); - - return new PollResponse<>(LongRunningOperationStatus.FAILED, null); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - }; - } - - private Function, String> backupFetchOperation() { - return (pollingContext) -> { - try { - return pollingContext.getLatestResponse().getValue().getAzureStorageBlobContainerUrl(); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - }; - } - - private static PollResponse - processBackupOperationResponse(Response response) { - - String operationStatus = response.getValue().getStatus().toLowerCase(Locale.US); - - return new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)), - response.getValue()); - } - - /** - * Initiates a pre-backup check on the Key Vault. This operation checks if it is possible to back up the entire - * collection of keys from a key vault. - * - *

Code Samples

- *

Starts a {@link KeyVaultBackupOperation pre-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.

- * - *
-     * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
-     * String sasToken = "<sas-token>";
-     *
-     * SyncPoller<KeyVaultBackupOperation, String> preBackupPoller = client.beginPreBackup(blobStorageUrl, sasToken);
-     * PollResponse<KeyVaultBackupOperation> pollResponse = preBackupPoller.poll();
-     *
-     * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
-     *
-     * PollResponse<KeyVaultBackupOperation> finalPollResponse = preBackupPoller.waitForCompletion();
-     *
-     * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
-     *     System.out.printf("Pre-backup check completed successfully.%n");
-     * } else {
-     *     KeyVaultBackupOperation operation = preBackupPoller.poll().getValue();
-     *
-     *     System.out.printf("Pre-backup check 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 Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link SyncPoller} polling on the {@link KeyVaultBackupOperation pre-backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code blobStorageUrl} or {@code sasToken} are invalid. - * @throws NullPointerException If the {@code blobStorageUrl} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginPreBackup(String blobStorageUrl, String sasToken) { - if (blobStorageUrl == null) { - throw LOGGER.logExceptionAsError(new NullPointerException( - String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'blobStorageUrl'"))); - } - - return SyncPoller.createPoller(getDefaultPollingInterval(), - cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - preBackupActivationOperation(blobStorageUrl, sasToken, Context.NONE).apply(cxt)), - backupPollOperation(Context.NONE), (pollingContext, firstResponse) -> { - throw LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported")); - }, backupFetchOperation()); - } - - private Function, KeyVaultBackupOperation> - preBackupActivationOperation(String blobStorageUrl, String sasToken, Context context) { - - return (pollingContext) -> { - try { - return preBackupWithResponse(blobStorageUrl, sasToken, context).getValue(); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - }; - } - - /** - * Initiates a pre-backup check on the Key Vault. This operation checks if it is possible to back up the entire - * collection of keys from a key vault. - * - * @param blobStorageUrl The URL for the Blob Storage resource where the backup will be located. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} containing the {@link KeyVaultBackupOperation pre-backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code blobStorageUrl} or {@code sasToken} are invalid. - */ - Response preBackupWithResponse(String blobStorageUrl, String sasToken, Context context) { - PreBackupOperationParameters preBackupOperationParameters - = new PreBackupOperationParameters().setStorageResourceUri(blobStorageUrl) - .setToken(sasToken) - .setUseManagedIdentity(sasToken == null); - - try { - Response backupOperationResponse = clientImpl.preFullBackupWithResponse( - BinaryData.fromObject(preBackupOperationParameters), new RequestOptions().setContext(context)); - - return new SimpleResponse<>(backupOperationResponse.getRequest(), backupOperationResponse.getStatusCode(), - backupOperationResponse.getHeaders(), (KeyVaultBackupOperation) transformToLongRunningOperation( - backupOperationResponse.getValue().toObject(FullBackupOperation.class))); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Initiates a full restore of the Key Vault. - * - *

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.

- * - *
-     * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
-     * String sasToken = "<sas-token>";
-     *
-     * 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 - * backup operation. An example of such a URL may look like the following: - * https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link SyncPoller} to poll on the {@link KeyVaultRestoreOperation restore operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code folderUrl} or {@code sasToken} are invalid. - * @throws NullPointerException If the {@code folderUrl} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginRestore(String folderUrl, String sasToken) { - if (folderUrl == null) { - throw LOGGER.logExceptionAsError( - new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'"))); - } - - return SyncPoller.createPoller(getDefaultPollingInterval(), - context -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - restoreActivationOperation(folderUrl, sasToken, Context.NONE).apply(context)), - restorePollOperation(Context.NONE), (pollingContext, firstResponse) -> { - throw LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported")); - }, (pollingContext) -> new KeyVaultRestoreResult()); - } - - /** - * Initiates a full restore of the Key Vault. - * - * @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 - * backup operation. An example of such a URL may look like the following: - * https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} containing the {@link KeyVaultRestoreOperation backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code folderUrl} or {@code sasToken} are invalid. - */ - Response restoreWithResponse(String folderUrl, String sasToken, Context context) { - String[] segments = folderUrl.split("/"); - String folderName = segments[segments.length - 1]; - String containerUrl = folderUrl.substring(0, folderUrl.length() - folderName.length()); - - SASTokenParameter sasTokenParameter - = new SASTokenParameter(containerUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null); - RestoreOperationParameters restoreOperationParameters - = new RestoreOperationParameters(sasTokenParameter, folderName); - - try { - Response restoreOperationResponse = clientImpl.fullRestoreOperationWithResponse( - BinaryData.fromObject(restoreOperationParameters), new RequestOptions().setContext(context)); - - return new SimpleResponse<>(restoreOperationResponse.getRequest(), restoreOperationResponse.getStatusCode(), - restoreOperationResponse.getHeaders(), (KeyVaultRestoreOperation) transformToLongRunningOperation( - restoreOperationResponse.getValue().toObject(RestoreOperation.class))); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - private Function, KeyVaultRestoreOperation> - restoreActivationOperation(String folderUrl, String sasToken, Context context) { - - return (pollingContext) -> { - try { - return restoreWithResponse(folderUrl, sasToken, context).getValue(); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - }; - } - - private Function, PollResponse> - restorePollOperation(Context context) { - - return (pollingContext) -> { - try { - PollResponse pollResponse = pollingContext.getLatestResponse(); - - if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED - || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) { - - return pollResponse; - } - - final KeyVaultRestoreOperation keyVaultRestoreOperation = pollResponse.getValue(); - - if (keyVaultRestoreOperation == null) { - LOGGER.warning("Restore operation does not exist. Activation operation failed."); - - return new PollResponse<>(LongRunningOperationStatus.fromString("RESTORE_START_FAILED", true), - null); - } - - final String jobId = keyVaultRestoreOperation.getOperationId(); - Response response - = clientImpl.restoreStatusWithResponse(jobId, new RequestOptions().setContext(context)); - - return processRestoreOperationResponse( - new SimpleResponse<>(response, (KeyVaultRestoreOperation) transformToLongRunningOperation( - response.getValue().toObject(RestoreOperation.class)))); - } catch (HttpResponseException e) { - //noinspection ThrowableNotThrown - LOGGER.logExceptionAsError(e); - - return new PollResponse<>(LongRunningOperationStatus.FAILED, null); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - }; - } - - private static PollResponse - processRestoreOperationResponse(Response response) { - - String operationStatus = response.getValue().getStatus().toLowerCase(Locale.US); - - return new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)), - response.getValue()); - } - - /** - * Initiates a pre-restore check on the Key Vault. This operation checks if it is possible to restore an entire - * collection of keys from a backup. - * - *

Code Samples

- *

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

- * - *
-     * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
-     * String sasToken = "<sas-token>";
-     *
-     * SyncPoller<KeyVaultRestoreOperation, KeyVaultRestoreResult> preRestorePoller =
-     *     client.beginPreRestore(folderUrl, sasToken);
-     * PollResponse<KeyVaultRestoreOperation> pollResponse = preRestorePoller.poll();
-     *
-     * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
-     *
-     * PollResponse<KeyVaultRestoreOperation> finalPollResponse = preRestorePoller.waitForCompletion();
-     *
-     * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
-     *     System.out.printf("Pre-restore check completed successfully.%n");
-     * } else {
-     *     KeyVaultRestoreOperation operation = preRestorePoller.poll().getValue();
-     *
-     *     System.out.printf("Pre-restore check 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 - * backup operation. An example of such a URL may look like the following: - * {@code https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313}. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link SyncPoller} to poll on the {@link KeyVaultRestoreOperation restore operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code folderUrl} or {@code sasToken} are invalid. - * @throws NullPointerException If the {@code folderUrl} is {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginPreRestore(String folderUrl, - String sasToken) { - if (folderUrl == null) { - throw LOGGER.logExceptionAsError( - new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'"))); - } - - Context context = Context.NONE; - - return SyncPoller.createPoller(getDefaultPollingInterval(), - cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - preRestoreActivationOperation(folderUrl, sasToken, context).apply(cxt)), - restorePollOperation(context), (pollingContext, firstResponse) -> { - throw LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported")); - }, (pollingContext) -> new KeyVaultRestoreResult()); - } - - /** - * Initiates a pre-restore check on the Key Vault. This operation checks if it is possible to restore an entire - * collection of keys from a backup. - * - * @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 - * backup operation. An example of such a URL may look like the following: - * {@code https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313}. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} containing the {@link KeyVaultRestoreOperation backup operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code folderUrl} or {@code sasToken} are invalid. - */ - Response preRestoreWithResponse(String folderUrl, String sasToken, Context context) { - String[] segments = folderUrl.split("/"); - String folderName = segments[segments.length - 1]; - String containerUrl = folderUrl.substring(0, folderUrl.length() - folderName.length()); - - SASTokenParameter sasTokenParameter - = new SASTokenParameter(containerUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null); - PreRestoreOperationParameters restoreOperationParameters - = new PreRestoreOperationParameters().setFolderToRestore(folderName) - .setSasTokenParameters(sasTokenParameter); - - try { - Response restoreOperationResponse = clientImpl.preFullRestoreOperationWithResponse( - BinaryData.fromObject(restoreOperationParameters), new RequestOptions().setContext(context)); - - return new SimpleResponse<>(restoreOperationResponse.getRequest(), restoreOperationResponse.getStatusCode(), - restoreOperationResponse.getHeaders(), (KeyVaultRestoreOperation) transformToLongRunningOperation( - restoreOperationResponse.getValue().toObject(RestoreOperation.class))); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - private Function, KeyVaultRestoreOperation> - preRestoreActivationOperation(String folderUrl, String sasToken, Context context) { - - return (pollingContext) -> { - try { - return preRestoreWithResponse(folderUrl, sasToken, context).getValue(); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - }; - } - - /** - * Restores all versions of a given key using the supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - *

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.

- * - *
-     * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
-     * String sasToken = "<sas-token>";
-     * String keyName = "myKey";
-     *
-     * SyncPoller<KeyVaultSelectiveKeyRestoreOperation, KeyVaultSelectiveKeyRestoreResult> restorePoller =
-     *     client.beginSelectiveKeyRestore(folderUrl, sasToken, keyName);
-     * PollResponse<KeyVaultSelectiveKeyRestoreOperation> pollResponse = restorePoller.poll();
-     *
-     * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
-     *
-     * PollResponse<KeyVaultSelectiveKeyRestoreOperation> finalPollResponse = restorePoller.waitForCompletion();
-     *
-     * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
-     *     System.out.printf("Key restored successfully.%n");
-     * } else {
-     *     KeyVaultSelectiveKeyRestoreOperation operation = restorePoller.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 - * the blob container where the backup resides. This would be the exact value that is returned as the result of a - * backup operation. An example of such a URL may look like the following: - * https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * - * @return A {@link SyncPoller} to poll on the {@link KeyVaultRestoreOperation restore operation} status. - * - * @throws KeyVaultAdministrationException If the given {@code folderUrl} or {@code sasToken} are invalid. - * @throws NullPointerException If the {@code keyName} or {@code folderUrl} are {@code null}. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller - beginSelectiveKeyRestore(String keyName, String folderUrl, String sasToken) { - - if (keyName == null) { - throw LOGGER.logExceptionAsError( - new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'keyName'"))); - } - - if (folderUrl == null) { - throw LOGGER.logExceptionAsError( - new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'"))); - } - - return SyncPoller.createPoller(getDefaultPollingInterval(), - context -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - selectiveKeyRestoreActivationOperation(keyName, folderUrl, sasToken, Context.NONE).apply(context)), - selectiveKeyRestorePollOperation(Context.NONE), (pollingContext, firstResponse) -> { - throw LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported")); - }, (pollingContext) -> new KeyVaultSelectiveKeyRestoreResult()); - } - - /** - * Restores all versions of a given key using the supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @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 - * the blob container where the backup resides. This would be the exact value that is returned as the result of a - * backup operation. An example of such a URL may look like the following: - * https://contoso.blob.core.windows.net/backup/mhsm-contoso-2020090117323313. - * @param sasToken Optional Shared Access Signature (SAS) token to authorize access to the blob. If {@code null}, - * Managed Identity will be used to authenticate instead. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} containing the {@link KeyVaultSelectiveKeyRestoreOperation backup operation} status. - */ - Response selectiveKeyRestoreWithResponse(String keyName, String folderUrl, - String sasToken, Context context) { - - String[] segments = folderUrl.split("/"); - String folderName = segments[segments.length - 1]; - String containerUrl = folderUrl.substring(0, folderUrl.length() - folderName.length()); - - SASTokenParameter sasTokenParameter - = new SASTokenParameter(containerUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null); - SelectiveKeyRestoreOperationParameters selectiveKeyRestoreOperationParameters - = new SelectiveKeyRestoreOperationParameters(sasTokenParameter, folderName); - - try { - Response selectiveKeyRestoreOperationResponse - = clientImpl.selectiveKeyRestoreOperationWithResponse(keyName, - BinaryData.fromObject(selectiveKeyRestoreOperationParameters), - new RequestOptions().setContext(context)); - - return new SimpleResponse<>(selectiveKeyRestoreOperationResponse.getRequest(), - selectiveKeyRestoreOperationResponse.getStatusCode(), selectiveKeyRestoreOperationResponse.getHeaders(), - (KeyVaultSelectiveKeyRestoreOperation) transformToLongRunningOperation( - selectiveKeyRestoreOperationResponse.getValue().toObject(SelectiveKeyRestoreOperation.class))); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - private Function, KeyVaultSelectiveKeyRestoreOperation> - selectiveKeyRestoreActivationOperation(String keyName, String folderUrl, String sasToken, Context context) { - - return (pollingContext) -> { - try { - return selectiveKeyRestoreWithResponse(keyName, folderUrl, sasToken, context).getValue(); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - }; - } - - private - Function, PollResponse> - selectiveKeyRestorePollOperation(Context context) { - - return (pollingContext) -> { - try { - PollResponse pollResponse = pollingContext.getLatestResponse(); - - if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED - || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) { - - return pollResponse; - } - - final KeyVaultSelectiveKeyRestoreOperation keyVaultSelectiveKeyRestoreOperation - = pollResponse.getValue(); - - if (keyVaultSelectiveKeyRestoreOperation == null) { - LOGGER.warning("Restore operation does not exist. Activation operation failed."); - - return new PollResponse<>( - LongRunningOperationStatus.fromString("SELECTIVE_RESTORE_START_FAILED", true), null); - } - - final String jobId = keyVaultSelectiveKeyRestoreOperation.getOperationId(); - - Response response - = clientImpl.selectiveKeyRestoreStatusWithResponse(jobId, new RequestOptions().setContext(context)); - - return processSelectiveKeyRestoreOperationResponse(new SimpleResponse<>(response, - (KeyVaultSelectiveKeyRestoreOperation) transformToLongRunningOperation( - response.getValue().toObject(SelectiveKeyRestoreOperation.class)))); - } catch (HttpResponseException e) { - //noinspection ThrowableNotThrown - LOGGER.logExceptionAsError(e); - - return new PollResponse<>(LongRunningOperationStatus.FAILED, null); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - }; - } - - private static PollResponse - processSelectiveKeyRestoreOperationResponse(Response response) { - - String operationStatus = response.getValue().getStatus().toLowerCase(Locale.US); - - return new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)), - response.getValue()); - } -} 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 deleted file mode 100644 index a4365be92552..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilder.java +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeader; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.policy.AddHeadersPolicy; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.HttpPolicyProviders; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.TracingOptions; -import com.azure.core.util.builder.ClientBuilderUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.tracing.Tracer; -import com.azure.core.util.tracing.TracerProvider; -import com.azure.security.keyvault.administration.implementation.KeyVaultCredentialPolicy; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * This class provides a fluent builder API to help aid the configuration and instantiation of the - * {@link KeyVaultBackupAsyncClient backup async client} and {@link KeyVaultBackupClient backup client}, by calling - * {@link KeyVaultBackupClientBuilder#buildAsyncClient() buildAsyncClient} and - * {@link KeyVaultBackupClientBuilder#buildClient() buildClient} respectively. It constructs an instance of the desired - * client. - * - *

The minimal configuration options required by {@link KeyVaultBackupClientBuilder} to build a - * {@link KeyVaultBackupAsyncClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

- * - * - *
- * KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .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 KeyVaultBackupClientBuilder}.

- * - * - *
- * KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder()
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- *     .httpClient(HttpClient.createDefault())
- *     .buildAsyncClient();
- * 
- * - * - *

The minimal configuration options required by {@link KeyVaultBackupClientBuilder} to build a - * {@link KeyVaultBackupClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

- * - * - *
- * KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - * @see KeyVaultBackupClient - * @see KeyVaultBackupAsyncClient - */ -@ServiceClientBuilder(serviceClients = { KeyVaultBackupClient.class, KeyVaultBackupAsyncClient.class }) -public final class KeyVaultBackupClientBuilder implements TokenCredentialTrait, - HttpTrait, ConfigurationTrait { - // This is the properties file name. - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultBackupClientBuilder.class); - private static final String AZURE_KEY_VAULT_RBAC = "azure-security-keyvault-administration.properties"; - private static final String SDK_NAME = "name"; - private static final String SDK_VERSION = "version"; - - // Please see here - // for more information on Azure resource provider namespaces. - private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; - private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); - - private final List perCallPolicies; - private final List perRetryPolicies; - private final Map properties; - - private TokenCredential credential; - private HttpPipeline pipeline; - private URL vaultUrl; - private HttpClient httpClient; - private HttpLogOptions httpLogOptions; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - private Configuration configuration; - private ClientOptions clientOptions; - private KeyVaultAdministrationServiceVersion serviceVersion; - private boolean disableChallengeResourceVerification = false; - - /** - * Creates a {@link KeyVaultBackupClientBuilder} instance that is able to configure and construct instances of - * {@link KeyVaultBackupClient} and {@link KeyVaultBackupAsyncClient}. - */ - public KeyVaultBackupClientBuilder() { - httpLogOptions = new HttpLogOptions(); - perCallPolicies = new ArrayList<>(); - perRetryPolicies = new ArrayList<>(); - properties = CoreUtils.getProperties(AZURE_KEY_VAULT_RBAC); - } - - /** - * Creates an {@link KeyVaultBackupClient} based on options set in the Builder. Every time {@code buildClient()} - * is called a new instance of {@link KeyVaultBackupClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline} and - * {@link #vaultUrl(String) vaultUrl} are used to create the {@link KeyVaultBackupClient client}. All other - * builder settings are ignored. - * - * @return A {@link KeyVaultBackupClient} with the options set from the builder. - * - * @throws NullPointerException If {@code vaultUrl} is {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public KeyVaultBackupClient buildClient() { - Configuration buildConfiguration = validateEndpointAndGetBuildConfiguration(); - serviceVersion = getServiceVersion(); - if (pipeline != null) { - return new KeyVaultBackupClient(vaultUrl, pipeline, serviceVersion); - } - HttpPipeline buildPipeline = getPipeline(buildConfiguration); - return new KeyVaultBackupClient(vaultUrl, buildPipeline, serviceVersion); - } - - /** - * Creates a {@link KeyVaultBackupAsyncClient} based on options set in the Builder. Every time {@code - * buildAsyncClient()} is called a new instance of {@link KeyVaultBackupAsyncClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline} and - * {@link #vaultUrl(String) endpoint} are used to create the {@link KeyVaultBackupAsyncClient client}. All other - * builder settings are ignored. - * - * @return A {@link KeyVaultBackupAsyncClient} with the options set from the builder. - * - * @throws NullPointerException If {@code vaultUrl} is {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public KeyVaultBackupAsyncClient buildAsyncClient() { - Configuration buildConfiguration = validateEndpointAndGetBuildConfiguration(); - serviceVersion = getServiceVersion(); - if (pipeline != null) { - return new KeyVaultBackupAsyncClient(vaultUrl, pipeline, serviceVersion); - } - HttpPipeline buildPipeline = getPipeline(buildConfiguration); - return new KeyVaultBackupAsyncClient(vaultUrl, buildPipeline, serviceVersion); - } - - private Configuration validateEndpointAndGetBuildConfiguration() { - Configuration buildConfiguration - = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; - - URL buildEndpoint = getBuildEndpoint(buildConfiguration); - - if (buildEndpoint == null) { - throw LOGGER - .logExceptionAsError(new IllegalStateException(KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED)); - } - return buildConfiguration; - } - - private KeyVaultAdministrationServiceVersion getServiceVersion() { - return serviceVersion != null ? serviceVersion : KeyVaultAdministrationServiceVersion.getLatest(); - } - - private HttpPipeline getPipeline(Configuration buildConfiguration) { - - // Closest to API goes first, closest to wire goes last. - final List policies = new ArrayList<>(); - - String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); - String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); - - httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; - - ClientOptions localClientOptions = clientOptions != null ? clientOptions : DEFAULT_CLIENT_OPTIONS; - - policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, - clientVersion, buildConfiguration)); - - List httpHeaderList = new ArrayList<>(); - localClientOptions.getHeaders() - .forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); - policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); - - // Add per call additional policies. - policies.addAll(perCallPolicies); - HttpPolicyProviders.addBeforeRetryPolicies(policies); - - // Add retry policy. - policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); - - policies.add(new KeyVaultCredentialPolicy(credential, disableChallengeResourceVerification)); - - // Add per retry additional policies. - policies.addAll(perRetryPolicies); - - HttpPolicyProviders.addAfterRetryPolicies(policies); - policies.add(new HttpLoggingPolicy(httpLogOptions)); - - TracingOptions tracingOptions = localClientOptions.getTracingOptions(); - Tracer tracer = TracerProvider.getDefaultProvider() - .createTracer(clientName, clientVersion, KEYVAULT_TRACING_NAMESPACE_VALUE, tracingOptions); - - return new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) - .httpClient(httpClient) - .clientOptions(localClientOptions) - .tracer(tracer) - .build(); - } - - /** - * Sets the URL to the Key Vault on which the client operates. Appears as "DNS Name" in the Azure portal. You should - * validate that this URL references a valid Key Vault or Managed HSM resource. - * Refer to the following documentation for details. - * - * @param vaultUrl The vault URL is used as destination on Azure to send requests to. - * - * @return The updated {@link KeyVaultBackupClientBuilder} object. - * - * @throws IllegalArgumentException If {@code vaultUrl} is null or it cannot be parsed into a valid URL. - * @throws NullPointerException If {@code credential} is {@code null}. - */ - public KeyVaultBackupClientBuilder vaultUrl(String vaultUrl) { - if (vaultUrl == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); - } - - try { - this.vaultUrl = new URL(vaultUrl); - } catch (MalformedURLException e) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("The Azure Key Vault URL is malformed.", e)); - } - - return this; - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * - * @return The updated {@link KeyVaultBackupClientBuilder} object. - * - * @throws NullPointerException If {@code credential} is {@code null}. - */ - @Override - public KeyVaultBackupClientBuilder credential(TokenCredential credential) { - if (credential == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); - } - - this.credential = credential; - - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * @return The updated {@link KeyVaultBackupClientBuilder} object. - */ - @Override - public KeyVaultBackupClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; - - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * @return The updated {@link KeyVaultBackupClientBuilder} object. - * - * @throws NullPointerException If {@code policy} is {@code null}. - */ - @Override - public KeyVaultBackupClientBuilder addPolicy(HttpPipelinePolicy policy) { - if (policy == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); - } - - if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { - perCallPolicies.add(policy); - } else { - perRetryPolicies.add(policy); - } - - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * @return The updated {@link KeyVaultBackupClientBuilder} object. - */ - @Override - public KeyVaultBackupClientBuilder httpClient(HttpClient client) { - this.httpClient = client; - - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * The {@link #vaultUrl(String) vaultUrl} is not ignored when - * {@code pipeline} is set. - * - * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return The updated {@link KeyVaultBackupClientBuilder} object. - */ - @Override - public KeyVaultBackupClientBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - - return this; - } - - /** - * Sets the configuration store that is used during construction of the service client. - *

- * The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global - * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. - * - * @param configuration The configuration store used to get configuration details. - * - * @return The updated {@link KeyVaultBackupClientBuilder} object. - */ - @Override - public KeyVaultBackupClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - - return this; - } - - /** - * Sets the {@link RetryPolicy} that is used when each request is sent. - *

- * The default retry policy will be used in the pipeline, if not provided. - *

- * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy User's retry policy applied to each request. - * - * @return The updated {@link KeyVaultBackupClientBuilder} object. - */ - public KeyVaultBackupClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated {@link KeyVaultBackupClientBuilder} object. - */ - @Override - public KeyVaultBackupClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * @see HttpClientOptions - * @return The updated {@link KeyVaultBackupClientBuilder} object. - */ - @Override - public KeyVaultBackupClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - - return this; - } - - /** - * Sets the {@link KeyVaultAdministrationServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, the service version that will be used will be the latest known service - * version based on the version of the client library being used. If no service version is specified, updating to a - * newer version the client library will have the result of potentially moving to a newer service version. - * - * @param serviceVersion {@link KeyVaultAdministrationServiceVersion} of the service API used when making requests. - * - * @return The updated {@link KeyVaultBackupClientBuilder} object. - */ - public KeyVaultBackupClientBuilder serviceVersion(KeyVaultAdministrationServiceVersion serviceVersion) { - this.serviceVersion = serviceVersion; - - return this; - } - - /** - * Disables verifying if the authentication challenge resource matches the Key Vault or Managed HSM domain. This - * verification is performed by default. - * - * @return The updated {@link KeyVaultBackupClientBuilder} object. - */ - public KeyVaultBackupClientBuilder disableChallengeResourceVerification() { - this.disableChallengeResourceVerification = true; - - return this; - } - - private URL getBuildEndpoint(Configuration configuration) { - if (vaultUrl != null) { - return vaultUrl; - } - - String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); - - if (CoreUtils.isNullOrEmpty(configEndpoint)) { - return null; - } - - try { - return new URL(configEndpoint); - } catch (MalformedURLException ex) { - return null; - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClient.java deleted file mode 100644 index 7f00b581c6a1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClient.java +++ /dev/null @@ -1,419 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.BinaryData; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils; -import com.azure.security.keyvault.administration.implementation.models.Setting; -import com.azure.security.keyvault.administration.implementation.models.SettingsListResult; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; -import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; -import com.azure.security.keyvault.administration.models.KeyVaultSettingType; -import reactor.core.publisher.Mono; - -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.EMPTY_OPTIONS; - -/** - * The {@link KeyVaultSettingsAsyncClient} provides asynchronous methods to create, update, get and list - * {@link KeyVaultSetting settings} for an Azure Key Vault account. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link KeyVaultSettingsAsyncClient} class, a vault url and a credential object.

- * - *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, - * which is appropriate for most scenarios, including local development and production environments. Additionally, - * we recommend using a - * - * managed identity for authentication in production environments. - * You can find more information on different ways of authenticating and their corresponding credential types in the - * - * Azure Identity documentation".

- * - *

Sample: Construct Asynchronous Backup Client

- * - *

The following code sample demonstrates the creation of a {@link KeyVaultSettingsAsyncClient}, using the - * {@link KeyVaultSettingsClientBuilder} to configure it.

- * - * - *
- * KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = new KeyVaultSettingsClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildAsyncClient();
- * 
- * - * - *
- * - *
- * - *

Get All Settings

- * The {@link KeyVaultSettingsAsyncClient} can be used to list all the settings for an Azure Key Vault account. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously back up an entire collection of keys using, using the - * {@link KeyVaultSettingsAsyncClient#getSettings()} API.

- * - * - *
- * keyVaultSettingsAsyncClient.getSettings().subscribe(getSettingsResult ->
- *     getSettingsResult.getSettings().forEach(setting ->
- *         System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),
- *             setting.asBoolean())));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultSettingsClient}.

- * - *
- * - *
- * - *

Retrieve a Specific Setting

- * The {@link KeyVaultSettingsClient} can be used to retrieve a specific setting. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously restore an entire collection of keys from a backup, - * using the {@link KeyVaultSettingsClient#getSetting(String)} (String, String)} API.

- * - * - *
- * keyVaultSettingsAsyncClient.getSetting(settingName)
- *     .subscribe(setting ->
- *         System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean()));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultSettingsClient}.

- * - *
- * - *
- * - *

Update a Specific Setting

- * The {@link KeyVaultSettingsAsyncClient} can be used to restore a specific key from a backup. - * - *

Code Sample:

- *

The following code sample demonstrates how to asynchronously restore a specific key from a backup, using - * the {@link KeyVaultSettingsAsyncClient#updateSetting(KeyVaultSetting)} API.

- * - * - *
- * KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);
- *
- * keyVaultSettingsAsyncClient.updateSetting(settingToUpdate)
- *     .subscribe(updatedSetting ->
- *         System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(),
- *             updatedSetting.asBoolean()));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link KeyVaultSettingsClient}.

- * - *
- * - *
- * - * @see com.azure.security.keyvault.administration - * @see KeyVaultSettingsClientBuilder - */ -@ServiceClient( - builder = KeyVaultSettingsClientBuilder.class, - isAsync = true, - serviceInterfaces = KeyVaultAdministrationClientImpl.KeyVaultAdministrationClientService.class) -public final class KeyVaultSettingsAsyncClient { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultSettingsAsyncClient.class); - private final KeyVaultAdministrationClientImpl implClient; - - /** - * Creates a {@link KeyVaultSettingsAsyncClient} that uses a {@link KeyVaultAdministrationClientImpl} to service requests. - * - * @param implClient The implementation client used to service requests. - */ - KeyVaultSettingsAsyncClient(KeyVaultAdministrationClientImpl implClient) { - this.implClient = implClient; - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.implClient.getHttpPipeline(); - } - - /** - * Updates a given {@link KeyVaultSetting account setting}. - * - *

Code Samples

- *

Updates a given {@link KeyVaultSetting setting}. Prints out the details of the updated - * {@link KeyVaultRoleDefinition setting}.

- * - *
-     * KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);
-     *
-     * keyVaultSettingsAsyncClient.updateSetting(settingToUpdate)
-     *     .subscribe(updatedSetting ->
-     *         System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(),
-     *             updatedSetting.asBoolean()));
-     * 
- * - * - * @param setting The {@link KeyVaultSetting account setting} to update. - * - * @return A {@link Mono} containing the updated {@link KeyVaultSetting account setting}. - * - * @throws NullPointerException if {@code setting} is {@code null}. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateSetting(KeyVaultSetting setting) { - Objects.requireNonNull(setting, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'setting'")); - - try { - String settingValue = null; - - if (setting.getType() == KeyVaultSettingType.BOOLEAN) { - settingValue = Boolean.toString(setting.asBoolean()); - } - - return implClient - .updateSettingWithResponseAsync(setting.getName(), BinaryData.fromObject(settingValue), EMPTY_OPTIONS) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> transformToKeyVaultSetting(response.getValue().toObject(Setting.class))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Updates a given {@link KeyVaultSetting account setting}. - * - *

Code Samples

- *

Updates a given {@link KeyVaultSetting setting}. Prints out the details of the {@link Response HTTP response} - * and the updated {@link KeyVaultSetting setting}.

- * - *
-     * KeyVaultSetting mySettingToUpdate = new KeyVaultSetting(settingName, true);
-     *
-     * keyVaultSettingsAsyncClient.updateSettingWithResponse(mySettingToUpdate)
-     *     .subscribe(response ->
-     *         System.out.printf("Response successful with status code: %d. Updated setting '%s' to '%s'.%n",
-     *             response.getStatusCode(), response.getValue().getName(), response.getValue().asBoolean()));
-     * 
- * - * - * @param setting The {@link KeyVaultSetting account setting} to update. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the updated - * {@link KeyVaultSetting account setting}. - * - * @throws NullPointerException if {@code setting} is {@code null}. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateSettingWithResponse(KeyVaultSetting setting) { - Objects.requireNonNull(setting, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'setting'")); - - try { - String settingValue = null; - - if (setting.getType() == KeyVaultSettingType.BOOLEAN) { - settingValue = Boolean.toString(setting.asBoolean()); - } - - return implClient - .updateSettingWithResponseAsync(setting.getName(), BinaryData.fromObject(settingValue), EMPTY_OPTIONS) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> new SimpleResponse<>(response, - transformToKeyVaultSetting(response.getValue().toObject(Setting.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Get the value of a specific account setting. - * - *

Code Samples

- *

Retrieves a specific {@link KeyVaultSetting setting}. Prints out the details of the retrieved - * {@link KeyVaultRoleDefinition setting}.

- * - *
-     * keyVaultSettingsAsyncClient.getSetting(settingName)
-     *     .subscribe(setting ->
-     *         System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean()));
-     * 
- * - * - * @param name The name of setting to retrieve the value of. - * - * @return A {@link Mono} containing the {@link KeyVaultSetting account setting}. - * - * @throws IllegalArgumentException thrown if the setting type is not supported. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSetting(String name) { - try { - return implClient.getSettingWithResponseAsync(name, EMPTY_OPTIONS) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> transformToKeyVaultSetting(response.getValue().toObject(Setting.class))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Get the value of a specific account setting. - * - *

Code Samples

- *

Retrieves a specific {@link KeyVaultSetting setting}. Prints out the details of the - * {@link Response HTTP response} and the retrieved {@link KeyVaultSetting setting}.

- * - *
-     * keyVaultSettingsAsyncClient.getSettingWithResponse(settingName)
-     *     .subscribe(response ->
-     *         System.out.printf("Response successful with status code: %d. Retrieved setting '%s' with value '%s'.%n",
-     *             response.getStatusCode(), response.getValue().getName(), response.getValue().asBoolean()));
-     * 
- * - * - * @param name The name of setting to retrieve the value of. - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultSetting account setting}. - * - * @throws IllegalArgumentException thrown if the setting type is not supported. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSettingWithResponse(String name) { - try { - return implClient.getSettingWithResponseAsync(name, EMPTY_OPTIONS) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> new SimpleResponse<>(response, - transformToKeyVaultSetting(response.getValue().toObject(Setting.class)))); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Get the account's settings. - * - *

Code Samples

- *

Retrieves all the {@link KeyVaultSetting settings} for an account. Prints out the details of the retrieved - * {@link KeyVaultRoleDefinition settings}.

- * - *
-     * keyVaultSettingsAsyncClient.getSettings().subscribe(getSettingsResult ->
-     *     getSettingsResult.getSettings().forEach(setting ->
-     *         System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),
-     *             setting.asBoolean())));
-     * 
- * - * - * @return A {@link Mono} containing a {@link KeyVaultGetSettingsResult result object} wrapping the list of - * {@link KeyVaultSetting account settings}. - * - * @throws IllegalArgumentException thrown if a setting type in the list is not supported. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSettings() { - try { - return implClient.getSettingsWithResponseAsync(EMPTY_OPTIONS) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> { - List keyVaultSettings = response.getValue() - .toObject(SettingsListResult.class) - .getSettings() - .stream() - .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting) - .collect(Collectors.toList()); - - return new KeyVaultGetSettingsResult(keyVaultSettings); - }); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Get the account's settings. - * - *

Code Samples

- *

Retrieves all {@link KeyVaultSetting settings for an account}. Prints out the details of the - * {@link Response HTTP response} and the retrieved {@link KeyVaultSetting settings}.

- * - *
-     * keyVaultSettingsAsyncClient.getSettingsWithResponse()
-     *     .subscribe(response -> {
-     *         System.out.printf("Response successful with status code: %d.", response.getStatusCode());
-     *
-     *         KeyVaultGetSettingsResult getSettingsResult = response.getValue();
-     *         List<KeyVaultSetting> settings = getSettingsResult.getSettings();
-     *
-     *         settings.forEach(setting ->
-     *             System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),
-     *                 setting.asBoolean()));
-     *     });
-     * 
- * - * - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains a - * {@link KeyVaultGetSettingsResult result object} wrapping the list of {@link KeyVaultSetting account settings}. - * - * @throws IllegalArgumentException thrown if a setting type in the list is not supported. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSettingsWithResponse() { - try { - return implClient.getSettingsWithResponseAsync(EMPTY_OPTIONS) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(response -> { - List keyVaultSettings = response.getValue() - .toObject(SettingsListResult.class) - .getSettings() - .stream() - .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting) - .collect(Collectors.toList()); - - return new SimpleResponse<>(response, new KeyVaultGetSettingsResult(keyVaultSettings)); - }); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - static KeyVaultSetting transformToKeyVaultSetting(Setting setting) { - if (KeyVaultSettingType.BOOLEAN.toString().equalsIgnoreCase(setting.getType().toString())) { - return new KeyVaultSetting(setting.getName(), Boolean.parseBoolean(setting.getValue())); - } else { - throw new IllegalArgumentException( - String.format("Could not deserialize setting with name '%s'. Type '%s' is not supported.", - setting.getName(), setting.getType())); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClient.java deleted file mode 100644 index 9dc632580de2..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClient.java +++ /dev/null @@ -1,395 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.RequestOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; -import com.azure.security.keyvault.administration.implementation.models.Setting; -import com.azure.security.keyvault.administration.implementation.models.SettingsListResult; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; -import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; -import com.azure.security.keyvault.administration.models.KeyVaultSettingType; - -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.EMPTY_OPTIONS; - -/** - * The {@link KeyVaultSettingsClient} provides synchronous methods to create, update, get and list - * {@link KeyVaultSetting settings} for an Azure Key Vault account. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link KeyVaultSettingsClient} class, a vault url and a credential object.

- * - *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, - * which is appropriate for most scenarios, including local development and production environments. Additionally, - * we recommend using a - * - * managed identity for authentication in production environments. - * You can find more information on different ways of authenticating and their corresponding credential types in the - * - * Azure Identity documentation".

- * - *

Sample: Construct Synchronous Backup Client

- * - *

The following code sample demonstrates the creation of a {@link KeyVaultSettingsClient}, using the - * {@link KeyVaultSettingsClientBuilder} to configure it.

- * - * - *
- * KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - *
- * - *
- * - *

Get All Settings

- * The {@link KeyVaultSettingsClient} can be used to list all the settings for an Azure Key Vault account. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the - * {@link KeyVaultSettingsClient#getSettings()} API.

- * - * - *
- * KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings();
- * List<KeyVaultSetting> settings = getSettingsResult.getSettings();
- *
- * settings.forEach(setting ->
- *     System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),
- *         setting.asBoolean()));
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultSettingsAsyncClient}.

- * - *
- * - *
- * - *

Retrieve a Specific Setting

- * The {@link KeyVaultSettingsClient} can be used to retrieve a specific setting. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup, - * using the {@link KeyVaultSettingsClient#getSetting(String)} (String, String)} API.

- * - * - *
- * KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName);
- *
- * System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean());
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultSettingsAsyncClient}.

- * - *
- * - *
- * - *

Update a Specific Setting

- * The {@link KeyVaultSettingsClient} can be used to restore a specific key from a backup. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously restore a specific key from a backup, using - * the {@link KeyVaultSettingsClient#updateSetting(KeyVaultSetting)} API.

- * - * - *
- * KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);
- * KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate);
- *
- * System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean());
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link KeyVaultSettingsAsyncClient}.

- * - *
- * - *
- * - * @see com.azure.security.keyvault.administration - * @see KeyVaultSettingsClientBuilder - */ -@ServiceClient(builder = KeyVaultSettingsClientBuilder.class) -public final class KeyVaultSettingsClient { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultSettingsClient.class); - private final KeyVaultAdministrationClientImpl implClient; - - /** - * Initializes an instance of {@link KeyVaultSettingsClient} class. - * - * @param implClient The implementation client used to service requests. - */ - KeyVaultSettingsClient(KeyVaultAdministrationClientImpl implClient) { - this.implClient = implClient; - } - - /** - * Updates a given {@link KeyVaultSetting account setting}. - * - *

Code Samples

- *

Updates a given {@link KeyVaultSetting setting}. Prints out the details of the updated - * {@link KeyVaultRoleDefinition setting}.

- * - *
-     * KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);
-     * KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate);
-     *
-     * System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean());
-     * 
- * - * - * @param setting The {@link KeyVaultSetting account setting} to update. - * - * @return The updated {@link KeyVaultSetting account setting}. - * - * @throws NullPointerException if {@code setting} is {@code null}. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultSetting updateSetting(KeyVaultSetting setting) { - Objects.requireNonNull(setting, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'setting'")); - - try { - String settingValue = null; - - if (setting.getType() == KeyVaultSettingType.BOOLEAN) { - settingValue = Boolean.toString(setting.asBoolean()); - } - - return KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(implClient - .updateSettingWithResponse(setting.getName(), BinaryData.fromObject(settingValue), EMPTY_OPTIONS) - .getValue() - .toObject(Setting.class)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Updates a given {@link KeyVaultSetting account setting}. - * - *

Code Samples

- *

Updates a given {@link KeyVaultSetting setting}. Prints out the details of the {@link Response HTTP response} - * and the updated {@link KeyVaultSetting setting}.

- * - *
-     * KeyVaultSetting mySettingToUpdate = new KeyVaultSetting(settingName, true);
-     * Response<KeyVaultSetting> response =
-     *     keyVaultSettingsClient.updateSettingWithResponse(mySettingToUpdate, new Context("key1", "value1"));
-     *
-     * System.out.printf("Response successful with status code: %d. Updated setting '%s' to '%s'.%n",
-     *     response.getStatusCode(), response.getValue().getName(), response.getValue().asBoolean());
-     * 
- * - * - * @param setting The {@link KeyVaultSetting account setting} to update. - * @param context Additional {@link Context} that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} whose {@link Response#getValue() value} contains the updated - * {@link KeyVaultSetting account setting}. - * - * @throws NullPointerException if {@code setting} is {@code null}. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateSettingWithResponse(KeyVaultSetting setting, Context context) { - Objects.requireNonNull(setting, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'setting'")); - - try { - String settingValue = null; - - if (setting.getType() == KeyVaultSettingType.BOOLEAN) { - settingValue = Boolean.toString(setting.asBoolean()); - } - - Response response = implClient.updateSettingWithResponse(setting.getName(), - BinaryData.fromObject(settingValue), new RequestOptions().setContext(context)); - - return new SimpleResponse<>(response, - KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(response.getValue().toObject(Setting.class))); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Get the value of a specific account setting. - * - *

Code Samples

- *

Retrieves a specific {@link KeyVaultSetting setting}. Prints out the details of the retrieved - * {@link KeyVaultRoleDefinition setting}.

- * - *
-     * KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName);
-     *
-     * System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean());
-     * 
- * - * - * @param name The name of setting to retrieve the value of. - * - * @return The {@link KeyVaultSetting account setting}. - * - * @throws IllegalArgumentException thrown if the setting type is not supported. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultSetting getSetting(String name) { - try { - return KeyVaultSettingsAsyncClient.transformToKeyVaultSetting( - implClient.getSettingWithResponse(name, EMPTY_OPTIONS).getValue().toObject(Setting.class)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Get the value of a specific account setting. - * - *

Code Samples

- *

Retrieves a specific {@link KeyVaultSetting setting}. Prints out the details of the - * {@link Response HTTP response} and the retrieved {@link KeyVaultSetting setting}.

- * - *
-     * Response<KeyVaultSetting> response =
-     *     keyVaultSettingsClient.getSettingWithResponse(settingName, new Context("key1", "value1"));
-     *
-     * System.out.printf("Response successful with status code: %d. Retrieved setting '%s' with value '%s'.%n",
-     *     response.getStatusCode(), response.getValue().getName(), response.getValue().asBoolean());
-     * 
- * - * - * @param name The name of setting to retrieve the value of. - * @param context Additional {@link Context} that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultSetting account setting}. - * - * @throws IllegalArgumentException thrown if the setting type is not supported. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSettingWithResponse(String name, Context context) { - try { - Response response - = implClient.getSettingWithResponse(name, new RequestOptions().setContext(context)); - - return new SimpleResponse<>(response, - KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(response.getValue().toObject(Setting.class))); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Get the account's settings. - * - *

Code Samples

- *

Retrieves all the {@link KeyVaultSetting settings} for an account. Prints out the details of the retrieved - * {@link KeyVaultRoleDefinition settings}.

- * - *
-     * KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings();
-     * List<KeyVaultSetting> settings = getSettingsResult.getSettings();
-     *
-     * settings.forEach(setting ->
-     *     System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),
-     *         setting.asBoolean()));
-     * 
- * - * - * @return A {@link KeyVaultGetSettingsResult result object} wrapping the list of - * {@link KeyVaultSetting account settings}. - * - * @throws IllegalArgumentException thrown if a setting type in the list is not supported. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultGetSettingsResult getSettings() { - try { - List keyVaultSettings = implClient.getSettingsWithResponse(EMPTY_OPTIONS) - .getValue() - .toObject(SettingsListResult.class) - .getSettings() - .stream() - .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting) - .collect(Collectors.toList()); - - return new KeyVaultGetSettingsResult(keyVaultSettings); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Get the account's settings. - * - *

Code Samples

- *

Retrieves all {@link KeyVaultSetting settings for an account}. Prints out the details of the - * {@link Response HTTP response} and the retrieved {@link KeyVaultSetting settings}.

- * - *
-     * Response<KeyVaultGetSettingsResult> response =
-     *     keyVaultSettingsClient.getSettingsWithResponse(new Context("key1", "value1"));
-     *
-     * System.out.printf("Response successful with status code: %d.", response.getStatusCode());
-     *
-     * KeyVaultGetSettingsResult myGetSettingsResult = response.getValue();
-     * List<KeyVaultSetting> mySettings = myGetSettingsResult.getSettings();
-     *
-     * mySettings.forEach(setting ->
-     *     System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),
-     *         setting.asBoolean()));
-     * 
- * - * - * @param context Additional {@link Context} that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Response} whose {@link Response#getValue() value} contains a - * {@link KeyVaultGetSettingsResult result object} wrapping the list of {@link KeyVaultSetting account settings}. - * - * @throws IllegalArgumentException thrown if a setting type in the list is not supported. - * @throws KeyVaultAdministrationException thrown if the request is rejected by the server. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSettingsWithResponse(Context context) { - try { - Response response - = implClient.getSettingsWithResponse(new RequestOptions().setContext(context)); - List keyVaultSettings = response.getValue() - .toObject(SettingsListResult.class) - .getSettings() - .stream() - .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting) - .collect(Collectors.toList()); - - return new SimpleResponse<>(response, new KeyVaultGetSettingsResult(keyVaultSettings)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilder.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilder.java deleted file mode 100644 index 3fc4cd90f706..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilder.java +++ /dev/null @@ -1,486 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.policy.AddDatePolicy; -import com.azure.core.http.policy.AddHeadersFromContextPolicy; -import com.azure.core.http.policy.AddHeadersPolicy; -import com.azure.core.http.policy.CookiePolicy; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.HttpPolicyProviders; -import com.azure.core.http.policy.RequestIdPolicy; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.TracingOptions; -import com.azure.core.util.builder.ClientBuilderUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.tracing.Tracer; -import com.azure.core.util.tracing.TracerProvider; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; -import com.azure.security.keyvault.administration.implementation.KeyVaultCredentialPolicy; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * This class provides a fluent builder API to help aid the configuration and instantiation of the - * {@link KeyVaultSettingsAsyncClient settings async client} and {@link KeyVaultSettingsClient settings client}, by - * calling {@link KeyVaultSettingsClientBuilder#buildAsyncClient() buildAsyncClient} and - * {@link KeyVaultSettingsClientBuilder#buildClient() buildClient} respectively. It constructs an instance of the - * desired client. - * - *

The minimal configuration options required by {@link KeyVaultSettingsClientBuilder} to build a - * {@link KeyVaultSettingsAsyncClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

- * - * - *
- * KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = new KeyVaultSettingsClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .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 KeyVaultSettingsClientBuilder}.

- * - * - *
- * KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = new KeyVaultSettingsClientBuilder()
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- *     .httpClient(HttpClient.createDefault())
- *     .buildAsyncClient();
- * 
- * - * - *

The minimal configuration options required by {@link KeyVaultSettingsClientBuilder} to build a - * {@link KeyVaultSettingsClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

- * - * - *
- * KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - * @see KeyVaultSettingsClient - * @see KeyVaultSettingsAsyncClient - */ -@ServiceClientBuilder(serviceClients = { KeyVaultSettingsClient.class, KeyVaultSettingsAsyncClient.class }) -public final class KeyVaultSettingsClientBuilder implements TokenCredentialTrait, - HttpTrait, ConfigurationTrait { - - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultSettingsClientBuilder.class); - private static final String AZURE_KEY_VAULT_RBAC = "azure-security-keyvault-administration.properties"; - private static final String SDK_NAME = "name"; - private static final String SDK_VERSION = "version"; - - // Please see here - // for more information on Azure resource provider namespaces. - private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; - private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); - - private final List pipelinePolicies; - private final Map properties; - - private TokenCredential credential; - private HttpPipeline pipeline; - private String vaultUrl; - private HttpClient httpClient; - private HttpLogOptions httpLogOptions; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - private Configuration configuration; - private ClientOptions clientOptions; - private KeyVaultAdministrationServiceVersion serviceVersion; - private boolean disableChallengeResourceVerification = false; - - /** - * Create an instance of the KeyVaultSettingsClientBuilder. - */ - public KeyVaultSettingsClientBuilder() { - this.httpLogOptions = new HttpLogOptions(); - this.pipelinePolicies = new ArrayList<>(); - this.properties = CoreUtils.getProperties(AZURE_KEY_VAULT_RBAC); - } - - /** - * Sets the URL to the Key Vault on which the client operates. Appears as "DNS Name" in the Azure portal. You should - * validate that this URL references a valid Key Vault or Managed HSM resource. - * Refer to the following documentation for details. - * - * @param vaultUrl The vault URL is used as destination on Azure to send requests to. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - * - * @throws IllegalArgumentException If {@code vaultUrl} is null or it cannot be parsed into a valid URL. - * @throws NullPointerException If {@code credential} is {@code null}. - */ - public KeyVaultSettingsClientBuilder vaultUrl(String vaultUrl) { - if (vaultUrl == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); - } - - try { - URL url = new URL(vaultUrl); - this.vaultUrl = url.toString(); - } catch (MalformedURLException e) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("The Azure Key Vault URL is malformed.", e)); - } - - return this; - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * - * @return The updated {@link KeyVaultAccessControlClientBuilder} object. - * - * @throws NullPointerException If {@code credential} is {@code null}. - */ - @Override - public KeyVaultSettingsClientBuilder credential(TokenCredential credential) { - if (credential == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); - } - - this.credential = credential; - - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * The {@link #vaultUrl(String) vaultUrl} is not ignored when - * {@code pipeline} is set. - * - * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - */ - @Override - public KeyVaultSettingsClientBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - */ - @Override - public KeyVaultSettingsClientBuilder httpClient(HttpClient client) { - this.httpClient = client; - - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - */ - @Override - public KeyVaultSettingsClientBuilder httpLogOptions(HttpLogOptions logOptions) { - this.httpLogOptions = logOptions; - - return this; - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - * - * @see HttpClientOptions - */ - @Override - public KeyVaultSettingsClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - */ - @Override - public KeyVaultSettingsClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - * - * @throws NullPointerException If {@code policy} is {@code null}. - */ - @Override - public KeyVaultSettingsClientBuilder addPolicy(HttpPipelinePolicy policy) { - if (policy == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); - } - - this.pipelinePolicies.add(policy); - - return this; - } - - /** - * Sets the configuration store that is used during construction of the service client. - *

- * The default configuration store is a clone of the - * {@link Configuration#getGlobalConfiguration() global configuration store}, use {@link Configuration#NONE} to - * bypass using configuration settings during construction. - * - * @param configuration The configuration store used to get configuration details. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - */ - @Override - public KeyVaultSettingsClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - - return this; - } - - /** - * Sets the {@link KeyVaultAdministrationServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, the service version that will be used will be the latest known service - * version based on the version of the client library being used. If no service version is specified, updating to a - * newer version the client library will have the result of potentially moving to a newer service version. - * - * @param serviceVersion {@link KeyVaultAdministrationServiceVersion} of the service API used when making requests. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - */ - public KeyVaultSettingsClientBuilder serviceVersion(KeyVaultAdministrationServiceVersion serviceVersion) { - this.serviceVersion = serviceVersion; - - return this; - } - - /** - * Sets the {@link RetryPolicy} that is used when each request is sent. - *

- * The default retry policy will be used in the pipeline, if not provided. - *

- * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy User's retry policy applied to each request. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - */ - public KeyVaultSettingsClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - - return this; - } - - /** - * Disables verifying if the authentication challenge resource matches the Key Vault or Managed HSM domain. This - * verification is performed by default. - * - * @return The updated {@link KeyVaultSettingsClientBuilder} object. - */ - public KeyVaultSettingsClientBuilder disableChallengeResourceVerification() { - this.disableChallengeResourceVerification = true; - - return this; - } - - /** - * Builds an instance of KeyVaultSettingsClientImpl with the provided parameters. - * - * @return an instance of KeyVaultSettingsClientImpl. - */ - private KeyVaultAdministrationClientImpl buildImplClient() { - HttpPipeline buildPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); - - KeyVaultAdministrationServiceVersion version - = (serviceVersion != null) ? serviceVersion : KeyVaultAdministrationServiceVersion.getLatest(); - - return new KeyVaultAdministrationClientImpl(buildPipeline, vaultUrl, version); - } - - private HttpPipeline createHttpPipeline() { - if (pipeline != null) { - return pipeline; - } - - Configuration buildConfiguration - = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; - - if (vaultUrl == null) { - throw LOGGER - .logExceptionAsError(new IllegalStateException(KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED)); - } - - serviceVersion = serviceVersion != null ? serviceVersion : KeyVaultAdministrationServiceVersion.getLatest(); - - final List policies = new ArrayList<>(); - - String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); - String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); - - httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; - - ClientOptions localClientOptions = clientOptions != null ? clientOptions : DEFAULT_CLIENT_OPTIONS; - - String applicationId = CoreUtils.getApplicationId(localClientOptions, httpLogOptions); - - policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); - policies.add(new RequestIdPolicy()); - policies.add(new AddHeadersFromContextPolicy()); - - HttpHeaders headers = new HttpHeaders(); - localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); - if (headers.getSize() > 0) { - policies.add(new AddHeadersPolicy(headers)); - } - - policies.addAll(this.pipelinePolicies.stream() - .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) - .collect(Collectors.toList())); - - HttpPolicyProviders.addBeforeRetryPolicies(policies); - - policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); - policies.add(new KeyVaultCredentialPolicy(credential, disableChallengeResourceVerification)); - policies.add(new AddDatePolicy()); - policies.add(new CookiePolicy()); - policies.addAll(this.pipelinePolicies.stream() - .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) - .collect(Collectors.toList())); - HttpPolicyProviders.addAfterRetryPolicies(policies); - policies.add(new HttpLoggingPolicy(httpLogOptions)); - - TracingOptions tracingOptions = localClientOptions.getTracingOptions(); - Tracer tracer = TracerProvider.getDefaultProvider() - .createTracer(clientName, clientVersion, KEYVAULT_TRACING_NAMESPACE_VALUE, tracingOptions); - - return new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) - .httpClient(httpClient) - .clientOptions(localClientOptions) - .tracer(tracer) - .build(); - } - - /** - * Builds an instance of KeyVaultSettingsAsyncClient class. - * - * @return an instance of KeyVaultSettingsAsyncClient. - */ - public KeyVaultSettingsAsyncClient buildAsyncClient() { - return new KeyVaultSettingsAsyncClient(buildImplClient()); - } - - /** - * Builds an instance of KeyVaultSettingsClient class. - * - * @return an instance of KeyVaultSettingsClient. - */ - public KeyVaultSettingsClient buildClient() { - return new KeyVaultSettingsClient(buildImplClient()); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationClientImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationClientImpl.java deleted file mode 100644 index 6dc41591da8b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationClientImpl.java +++ /dev/null @@ -1,2596 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.security.keyvault.administration.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Patch; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.exception.ClientAuthenticationException; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.http.rest.RequestOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.polling.DefaultPollingStrategy; -import com.azure.core.util.polling.PollerFlux; -import com.azure.core.util.polling.PollingStrategyOptions; -import com.azure.core.util.polling.SyncDefaultPollingStrategy; -import com.azure.core.util.polling.SyncPoller; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.core.util.serializer.TypeReference; -import com.azure.security.keyvault.administration.KeyVaultAdministrationServiceVersion; -import com.azure.security.keyvault.administration.implementation.models.FullBackupOperation; -import com.azure.security.keyvault.administration.implementation.models.RestoreOperation; -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperation; -import java.time.Duration; -import reactor.core.publisher.Mono; - -/** - * Initializes a new instance of the KeyVaultAdministrationClient type. - */ -public final class KeyVaultAdministrationClientImpl { - /** - * The proxy service used to perform REST calls. - */ - private final KeyVaultAdministrationClientService service; - - /** - */ - private final String vaultBaseUrl; - - /** - * Gets. - * - * @return the vaultBaseUrl value. - */ - public String getVaultBaseUrl() { - return this.vaultBaseUrl; - } - - /** - * Service version. - */ - private final KeyVaultAdministrationServiceVersion serviceVersion; - - /** - * Gets Service version. - * - * @return the serviceVersion value. - */ - public KeyVaultAdministrationServiceVersion getServiceVersion() { - return this.serviceVersion; - } - - /** - * The HTTP pipeline to send requests through. - */ - private final HttpPipeline httpPipeline; - - /** - * Gets The HTTP pipeline to send requests through. - * - * @return the httpPipeline value. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * The serializer to serialize an object into a string. - */ - private final SerializerAdapter serializerAdapter; - - /** - * Gets The serializer to serialize an object into a string. - * - * @return the serializerAdapter value. - */ - public SerializerAdapter getSerializerAdapter() { - return this.serializerAdapter; - } - - /** - * The RoleAssignmentsImpl object to access its operations. - */ - private final RoleAssignmentsImpl roleAssignments; - - /** - * Gets the RoleAssignmentsImpl object to access its operations. - * - * @return the RoleAssignmentsImpl object. - */ - public RoleAssignmentsImpl getRoleAssignments() { - return this.roleAssignments; - } - - /** - * The RoleDefinitionsImpl object to access its operations. - */ - private final RoleDefinitionsImpl roleDefinitions; - - /** - * Gets the RoleDefinitionsImpl object to access its operations. - * - * @return the RoleDefinitionsImpl object. - */ - public RoleDefinitionsImpl getRoleDefinitions() { - return this.roleDefinitions; - } - - /** - * Initializes an instance of KeyVaultAdministrationClient client. - * - * @param vaultBaseUrl - * @param serviceVersion Service version. - */ - public KeyVaultAdministrationClientImpl(String vaultBaseUrl, KeyVaultAdministrationServiceVersion serviceVersion) { - this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion); - } - - /** - * Initializes an instance of KeyVaultAdministrationClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param vaultBaseUrl - * @param serviceVersion Service version. - */ - public KeyVaultAdministrationClientImpl(HttpPipeline httpPipeline, String vaultBaseUrl, - KeyVaultAdministrationServiceVersion serviceVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion); - } - - /** - * Initializes an instance of KeyVaultAdministrationClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param serializerAdapter The serializer to serialize an object into a string. - * @param vaultBaseUrl - * @param serviceVersion Service version. - */ - public KeyVaultAdministrationClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, - String vaultBaseUrl, KeyVaultAdministrationServiceVersion serviceVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.vaultBaseUrl = vaultBaseUrl; - this.serviceVersion = serviceVersion; - this.roleAssignments = new RoleAssignmentsImpl(this); - this.roleDefinitions = new RoleDefinitionsImpl(this); - this.service = RestProxy.create(KeyVaultAdministrationClientService.class, this.httpPipeline, - this.getSerializerAdapter()); - } - - /** - * The interface defining all the services for KeyVaultAdministrationClient to be used by the proxy service to - * perform REST calls. - */ - @Host("{vaultBaseUrl}") - @ServiceInterface(name = "KeyVaultAdministrationClient") - public interface KeyVaultAdministrationClientService { - @Get("/backup/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> fullBackupStatus(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Get("/backup/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response fullBackupStatusSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Post("/backup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> fullBackup(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData azureStorageBlobContainerUri, RequestOptions requestOptions, - Context context); - - @Post("/backup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response fullBackupSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData azureStorageBlobContainerUri, RequestOptions requestOptions, - Context context); - - @Post("/prebackup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> preFullBackup(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData preBackupOperationParameters, RequestOptions requestOptions, - Context context); - - @Post("/prebackup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response preFullBackupSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData preBackupOperationParameters, RequestOptions requestOptions, - Context context); - - @Get("/restore/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> restoreStatus(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Get("/restore/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response restoreStatusSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Put("/prerestore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> preFullRestoreOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData preRestoreOperationParameters, RequestOptions requestOptions, - Context context); - - @Put("/prerestore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response preFullRestoreOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData preRestoreOperationParameters, RequestOptions requestOptions, - Context context); - - @Put("/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> fullRestoreOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData restoreBlobDetails, - RequestOptions requestOptions, Context context); - - @Put("/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response fullRestoreOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData restoreBlobDetails, - RequestOptions requestOptions, Context context); - - @Get("/restore/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> selectiveKeyRestoreStatus(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Get("/restore/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response selectiveKeyRestoreStatusSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Put("/keys/{keyName}/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> selectiveKeyRestoreOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("keyName") String keyName, - @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData restoreBlobDetails, RequestOptions requestOptions, - Context context); - - @Put("/keys/{keyName}/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response selectiveKeyRestoreOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("keyName") String keyName, - @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData restoreBlobDetails, RequestOptions requestOptions, - Context context); - - @Patch("/settings/{setting-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> updateSetting(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("setting-name") String settingName, - @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); - - @Patch("/settings/{setting-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response updateSettingSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("setting-name") String settingName, - @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, - @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); - - @Get("/settings/{setting-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> getSetting(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("setting-name") String settingName, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Get("/settings/{setting-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response getSettingSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam("setting-name") String settingName, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Get("/settings") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> getSettings(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Get("/settings") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response getSettingsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - } - - /** - * Returns the status of full backup operation. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param jobId The id returned as part of the backup request. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullBackupStatusWithResponseAsync(String jobId, RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.fullBackupStatus(this.getVaultBaseUrl(), - this.getServiceVersion().getVersion(), jobId, accept, requestOptions, context)); - } - - /** - * Returns the status of full backup operation. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param jobId The id returned as part of the backup request. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return full backup operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response fullBackupStatusWithResponse(String jobId, RequestOptions requestOptions) { - final String accept = "application/json"; - return service.fullBackupStatusSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), jobId, - accept, requestOptions, Context.NONE); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Required)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullBackupWithResponseAsync(BinaryData azureStorageBlobContainerUri, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.fullBackup(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), - contentType, accept, azureStorageBlobContainerUri, requestOptions, context)); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Required)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return full backup operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response fullBackupWithResponse(BinaryData azureStorageBlobContainerUri, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return service.fullBackupSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), contentType, - accept, azureStorageBlobContainerUri, requestOptions, Context.NONE); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Required)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of full backup operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginFullBackupAsync(BinaryData azureStorageBlobContainerUri, - RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.fullBackupWithResponseAsync(azureStorageBlobContainerUri, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Required)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of full backup operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginFullBackup(BinaryData azureStorageBlobContainerUri, - RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.fullBackupWithResponse(azureStorageBlobContainerUri, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Required)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of full backup operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux - beginFullBackupWithModelAsync(BinaryData azureStorageBlobContainerUri, RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.fullBackupWithResponseAsync(azureStorageBlobContainerUri, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(FullBackupOperation.class), - TypeReference.createInstance(FullBackupOperation.class)); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Required)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of full backup operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller - beginFullBackupWithModel(BinaryData azureStorageBlobContainerUri, RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.fullBackupWithResponse(azureStorageBlobContainerUri, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(FullBackupOperation.class), - TypeReference.createInstance(FullBackupOperation.class)); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Optional)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> preFullBackupWithResponseAsync(BinaryData preBackupOperationParameters, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.preFullBackup(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), - contentType, accept, preBackupOperationParameters, requestOptions, context)); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Optional)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return full backup operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response preFullBackupWithResponse(BinaryData preBackupOperationParameters, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return service.preFullBackupSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), contentType, - accept, preBackupOperationParameters, requestOptions, Context.NONE); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Optional)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of full backup operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginPreFullBackupAsync(BinaryData preBackupOperationParameters, - RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.preFullBackupWithResponseAsync(preBackupOperationParameters, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Optional)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of full backup operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginPreFullBackup(BinaryData preBackupOperationParameters, - RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.preFullBackupWithResponse(preBackupOperationParameters, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Optional)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of full backup operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux - beginPreFullBackupWithModelAsync(BinaryData preBackupOperationParameters, RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.preFullBackupWithResponseAsync(preBackupOperationParameters, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(FullBackupOperation.class), - TypeReference.createInstance(FullBackupOperation.class)); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     storageResourceUri: String (Optional)
-     *     token: String (Optional)
-     *     useManagedIdentity: Boolean (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     *     jobId: String (Optional)
-     *     azureStorageBlobContainerUri: String (Optional)
-     * }
-     * }
-     * 
- * - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of full backup operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller - beginPreFullBackupWithModel(BinaryData preBackupOperationParameters, RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.preFullBackupWithResponse(preBackupOperationParameters, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(FullBackupOperation.class), - TypeReference.createInstance(FullBackupOperation.class)); - } - - /** - * Returns the status of restore operation. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param jobId The Job Id returned part of the restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreStatusWithResponseAsync(String jobId, RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.restoreStatus(this.getVaultBaseUrl(), - this.getServiceVersion().getVersion(), jobId, accept, requestOptions, context)); - } - - /** - * Returns the status of restore operation. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param jobId The Job Id returned part of the restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return restore operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response restoreStatusWithResponse(String jobId, RequestOptions requestOptions) { - final String accept = "application/json"; - return service.restoreStatusSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), jobId, accept, - requestOptions, Context.NONE); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Optional): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> preFullRestoreOperationWithResponseAsync(BinaryData preRestoreOperationParameters, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.preFullRestoreOperation(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), - contentType, accept, preRestoreOperationParameters, requestOptions, context)); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Optional): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return restore operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response preFullRestoreOperationWithResponse(BinaryData preRestoreOperationParameters, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return service.preFullRestoreOperationSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), - contentType, accept, preRestoreOperationParameters, requestOptions, Context.NONE); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Optional): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux - beginPreFullRestoreOperationAsync(BinaryData preRestoreOperationParameters, RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.preFullRestoreOperationWithResponseAsync(preRestoreOperationParameters, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Optional): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginPreFullRestoreOperation(BinaryData preRestoreOperationParameters, - RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.preFullRestoreOperationWithResponse(preRestoreOperationParameters, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Optional): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginPreFullRestoreOperationWithModelAsync( - BinaryData preRestoreOperationParameters, RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.preFullRestoreOperationWithResponseAsync(preRestoreOperationParameters, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(RestoreOperation.class), TypeReference.createInstance(RestoreOperation.class)); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Optional): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Optional)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller - beginPreFullRestoreOperationWithModel(BinaryData preRestoreOperationParameters, RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.preFullRestoreOperationWithResponse(preRestoreOperationParameters, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(RestoreOperation.class), TypeReference.createInstance(RestoreOperation.class)); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullRestoreOperationWithResponseAsync(BinaryData restoreBlobDetails, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.fullRestoreOperation(this.getVaultBaseUrl(), - this.getServiceVersion().getVersion(), contentType, accept, restoreBlobDetails, requestOptions, context)); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return restore operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response fullRestoreOperationWithResponse(BinaryData restoreBlobDetails, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return service.fullRestoreOperationSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), - contentType, accept, restoreBlobDetails, requestOptions, Context.NONE); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginFullRestoreOperationAsync(BinaryData restoreBlobDetails, - RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.fullRestoreOperationWithResponseAsync(restoreBlobDetails, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginFullRestoreOperation(BinaryData restoreBlobDetails, - RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.fullRestoreOperationWithResponse(restoreBlobDetails, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux - beginFullRestoreOperationWithModelAsync(BinaryData restoreBlobDetails, RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.fullRestoreOperationWithResponseAsync(restoreBlobDetails, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(RestoreOperation.class), TypeReference.createInstance(RestoreOperation.class)); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folderToRestore: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller - beginFullRestoreOperationWithModel(BinaryData restoreBlobDetails, RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.fullRestoreOperationWithResponse(restoreBlobDetails, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(RestoreOperation.class), TypeReference.createInstance(RestoreOperation.class)); - } - - /** - * Returns the status of the selective key restore operation. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param jobId The Job Id returned part of the restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return selective Key Restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> selectiveKeyRestoreStatusWithResponseAsync(String jobId, - RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.selectiveKeyRestoreStatus(this.getVaultBaseUrl(), - this.getServiceVersion().getVersion(), jobId, accept, requestOptions, context)); - } - - /** - * Returns the status of the selective key restore operation. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param jobId The Job Id returned part of the restore operation. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return selective Key Restore operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response selectiveKeyRestoreStatusWithResponse(String jobId, RequestOptions requestOptions) { - final String accept = "application/json"; - return service.selectiveKeyRestoreStatusSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), - jobId, accept, requestOptions, Context.NONE); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folder: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return selective Key Restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> selectiveKeyRestoreOperationWithResponseAsync(String keyName, - BinaryData restoreBlobDetails, RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.selectiveKeyRestoreOperation(this.getVaultBaseUrl(), - this.getServiceVersion().getVersion(), keyName, contentType, accept, restoreBlobDetails, requestOptions, - context)); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folder: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return selective Key Restore operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response selectiveKeyRestoreOperationWithResponse(String keyName, BinaryData restoreBlobDetails, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return service.selectiveKeyRestoreOperationSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), - keyName, contentType, accept, restoreBlobDetails, requestOptions, Context.NONE); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folder: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of selective Key Restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginSelectiveKeyRestoreOperationAsync(String keyName, - BinaryData restoreBlobDetails, RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.selectiveKeyRestoreOperationWithResponseAsync(keyName, restoreBlobDetails, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folder: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of selective Key Restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginSelectiveKeyRestoreOperation(String keyName, - BinaryData restoreBlobDetails, RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.selectiveKeyRestoreOperationWithResponse(keyName, restoreBlobDetails, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folder: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link PollerFlux} for polling of selective Key Restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux - beginSelectiveKeyRestoreOperationWithModelAsync(String keyName, BinaryData restoreBlobDetails, - RequestOptions requestOptions) { - return PollerFlux.create(Duration.ofSeconds(1), - () -> this.selectiveKeyRestoreOperationWithResponseAsync(keyName, restoreBlobDetails, requestOptions), - new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(SelectiveKeyRestoreOperation.class), - TypeReference.createInstance(SelectiveKeyRestoreOperation.class)); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     sasTokenParameters (Required): {
-     *         storageResourceUri: String (Required)
-     *         token: String (Optional)
-     *         useManagedIdentity: Boolean (Optional)
-     *     }
-     *     folder: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
-     *     statusDetails: String (Optional)
-     *     error (Optional): {
-     *         code: String (Optional)
-     *         message: String (Optional)
-     *         innererror (Optional): (recursive schema, see innererror above)
-     *     }
-     *     jobId: String (Optional)
-     *     startTime: Long (Optional)
-     *     endTime: Long (Optional)
-     * }
-     * }
-     * 
- * - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the {@link SyncPoller} for polling of selective Key Restore operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller - beginSelectiveKeyRestoreOperationWithModel(String keyName, BinaryData restoreBlobDetails, - RequestOptions requestOptions) { - return SyncPoller.createPoller(Duration.ofSeconds(1), - () -> this.selectiveKeyRestoreOperationWithResponse(keyName, restoreBlobDetails, requestOptions), - new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) - - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion())), - TypeReference.createInstance(SelectiveKeyRestoreOperation.class), - TypeReference.createInstance(SelectiveKeyRestoreOperation.class)); - } - - /** - * Updates key vault account setting, stores it, then returns the setting name and value to the client. - * - * Description of the pool setting to be updated. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     value: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     name: String (Required)
-     *     value: String (Required)
-     *     type: String(boolean) (Optional)
-     * }
-     * }
-     * 
- * - * @param settingName The name of the account setting. Must be a valid settings option. - * @param parameters The parameters to update an account setting. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return a Key Vault account setting along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateSettingWithResponseAsync(String settingName, BinaryData parameters, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.updateSetting(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), - settingName, contentType, accept, parameters, requestOptions, context)); - } - - /** - * Updates key vault account setting, stores it, then returns the setting name and value to the client. - * - * Description of the pool setting to be updated. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     value: String (Required)
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     name: String (Required)
-     *     value: String (Required)
-     *     type: String(boolean) (Optional)
-     * }
-     * }
-     * 
- * - * @param settingName The name of the account setting. Must be a valid settings option. - * @param parameters The parameters to update an account setting. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return a Key Vault account setting along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateSettingWithResponse(String settingName, BinaryData parameters, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return service.updateSettingSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), settingName, - contentType, accept, parameters, requestOptions, Context.NONE); - } - - /** - * Get specified account setting object. - * - * Retrieves the setting object of a specified setting name. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     name: String (Required)
-     *     value: String (Required)
-     *     type: String(boolean) (Optional)
-     * }
-     * }
-     * 
- * - * @param settingName The name of the account setting. Must be a valid settings option. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return specified account setting object. - * - * Retrieves the setting object of a specified setting name along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSettingWithResponseAsync(String settingName, RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getSetting(this.getVaultBaseUrl(), - this.getServiceVersion().getVersion(), settingName, accept, requestOptions, context)); - } - - /** - * Get specified account setting object. - * - * Retrieves the setting object of a specified setting name. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     name: String (Required)
-     *     value: String (Required)
-     *     type: String(boolean) (Optional)
-     * }
-     * }
-     * 
- * - * @param settingName The name of the account setting. Must be a valid settings option. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return specified account setting object. - * - * Retrieves the setting object of a specified setting name along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSettingWithResponse(String settingName, RequestOptions requestOptions) { - final String accept = "application/json"; - return service.getSettingSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), settingName, - accept, requestOptions, Context.NONE); - } - - /** - * List account settings. - * - * Retrieves a list of all the available account settings that can be configured. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     settings (Optional): [
-     *          (Optional){
-     *             name: String (Required)
-     *             value: String (Required)
-     *             type: String(boolean) (Optional)
-     *         }
-     *     ]
-     * }
-     * }
-     * 
- * - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the settings list result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSettingsWithResponseAsync(RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getSettings(this.getVaultBaseUrl(), - this.getServiceVersion().getVersion(), accept, requestOptions, context)); - } - - /** - * List account settings. - * - * Retrieves a list of all the available account settings that can be configured. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     settings (Optional): [
-     *          (Optional){
-     *             name: String (Required)
-     *             value: String (Required)
-     *             type: String(boolean) (Optional)
-     *         }
-     *     ]
-     * }
-     * }
-     * 
- * - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the settings list result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSettingsWithResponse(RequestOptions requestOptions) { - final String accept = "application/json"; - return service.getSettingsSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), accept, - requestOptions, Context.NONE); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationUtils.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationUtils.java deleted file mode 100644 index 9e995b461f80..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationUtils.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.implementation; - -import com.azure.core.exception.HttpResponseException; -import com.azure.security.keyvault.administration.implementation.models.Error; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationError; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; - -/** - * A class containing utility methods for the Azure Security Key Vault Administration library. - */ -public final class KeyVaultAdministrationUtils { - private KeyVaultAdministrationUtils() { - throw new UnsupportedOperationException("Cannot instantiate KeyVaultAdministrationUtils"); - } - - /** - * Convert a {@link HttpResponseException} to a {@link KeyVaultAdministrationException}. - * - * @param exception The {@link HttpResponseException}. - * - * @return An instance of the public {@link KeyVaultAdministrationException}. - */ - public static KeyVaultAdministrationException toKeyVaultAdministrationException(HttpResponseException exception) { - if (exception == null) { - return null; - } - - return new KeyVaultAdministrationException(exception.getMessage(), exception.getResponse(), - toKeyVaultAdministrationError(exception.getValue())); - } - - /** - * Convert an implementation {@link Error} to a public {@link KeyVaultAdministrationError}. - * - * @param value The {@link Error} returned by the service. - * - * @return An instance of the public {@link KeyVaultAdministrationError}. - */ - public static KeyVaultAdministrationError toKeyVaultAdministrationError(Object value) { - if (value == null) { - return null; - } else { - if (value instanceof Error) { - Error error = (Error) value; - - return new KeyVaultAdministrationError(error.getCode(), error.getMessage(), - toKeyVaultAdministrationError(error.getInnerError())); - } else { - return new KeyVaultAdministrationError("ServiceError", value.toString(), null); - } - } - } - - /** - * Maps a {@link Throwable} to {@link KeyVaultAdministrationException} if it's an instance of - * {@link HttpResponseException}, else it returns the original throwable. - * - * @param throwable A {@link Throwable}. - * - * @return A {@link Throwable} that is either an instance of the public {@link KeyVaultAdministrationException} or the - * original {@link Throwable}. - */ - public static Throwable mapThrowableToKeyVaultAdministrationException(Throwable throwable) { - if (throwable instanceof HttpResponseException) { - return toKeyVaultAdministrationException((HttpResponseException) throwable); - } else { - return throwable; - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java deleted file mode 100644 index 7f1673a58f67..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration.implementation; - -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.TokenRequestContext; -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpPipelineNextPolicy; -import com.azure.core.http.HttpPipelineNextSyncPolicy; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; -import com.azure.core.util.Base64Util; -import com.azure.core.util.BinaryData; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static com.azure.core.http.HttpHeaderName.CONTENT_LENGTH; -import static com.azure.core.http.HttpHeaderName.WWW_AUTHENTICATE; - -/** - * A policy that authenticates requests with the Azure Key Vault service. The content added by this policy is - * leveraged in {@link TokenCredential} to get and set the correct "Authorization" header value. - * - * @see TokenCredential - */ -public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultCredentialPolicy.class); - private static final String BEARER_TOKEN_PREFIX = "Bearer "; - private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; - private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; - private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); - private ChallengeParameters challenge; - private final boolean disableChallengeResourceVerification; - - /** - * Creates a {@link KeyVaultCredentialPolicy}. - * - * @param credential The token credential to authenticate the request. - */ - public KeyVaultCredentialPolicy(TokenCredential credential, boolean disableChallengeResourceVerification) { - super(credential); - - this.disableChallengeResourceVerification = disableChallengeResourceVerification; - } - - /** - * Extracts attributes off the bearer challenge in the authentication header. - * - * @param authenticateHeader The authentication header containing the challenge. - * @param authChallengePrefix The authentication challenge name. - * - * @return A challenge attributes map. - */ - private static Map extractChallengeAttributes(String authenticateHeader, - String authChallengePrefix) { - if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { - return Collections.emptyMap(); - } - - String[] attributes = authenticateHeader.replace("\"", "").substring(authChallengePrefix.length()).split(","); - Map attributeMap = new HashMap<>(); - - for (String pair : attributes) { - // Using trim is ugly, but we need it here because currently the 'claims' attribute comes after two spaces. - String[] keyValue = pair.trim().split("=", 2); - - attributeMap.put(keyValue[0], keyValue[1]); - } - - return attributeMap; - } - - /** - * Verifies whether a challenge is bearer or not. - * - * @param authenticateHeader The authentication header containing all the challenges. - * @param authChallengePrefix The authentication challenge name. - * - * @return A boolean indicating if the challenge is a bearer challenge or not. - */ - private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { - return (!CoreUtils.isNullOrEmpty(authenticateHeader) - && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); - } - - @Override - public Mono authorizeRequest(HttpPipelineCallContext context) { - return Mono.defer(() -> { - HttpRequest request = context.getHttpRequest(); - - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } - - if (this.challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext - = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - return setAuthorizationHeader(context, tokenRequestContext); - } - - // The body is removed from the initial request because Key Vault supports other authentication schemes - // which also protect the body of the request. As a result, before we know the auth scheme we need to - // avoid sending an unprotected body to Key Vault. We don't currently support this enhanced auth scheme - // in the SDK, but we still don't want to send any unprotected data to vaults which require it. - - // Do not overwrite previous contents if retrying after initial request failed (e.g. timeout). - if (!context.getData(KEY_VAULT_STASHED_CONTENT_KEY).isPresent()) { - if (request.getBody() != null) { - context.setData(KEY_VAULT_STASHED_CONTENT_KEY, request.getBody()); - context.setData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY, - request.getHeaders().getValue(CONTENT_LENGTH)); - request.setHeader(CONTENT_LENGTH, "0"); - request.setBody((Flux) null); - } - } - - return Mono.empty(); - }); - } - - @SuppressWarnings("unchecked") - @Override - public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { - return Mono.defer(() -> { - HttpRequest request = context.getHttpRequest(); - Optional contentOptional = context.getData(KEY_VAULT_STASHED_CONTENT_KEY); - Optional contentLengthOptional = context.getData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY); - - if (request.getBody() == null && contentOptional.isPresent() && contentLengthOptional.isPresent()) { - request.setBody((Flux) contentOptional.get()); - request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); - } - - String authority = getRequestAuthority(request); - Map challengeAttributes - = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); - String scope = challengeAttributes.get("resource"); - - if (scope != null) { - scope = scope + "/.default"; - } else { - scope = challengeAttributes.get("scope"); - } - - if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); - - if (this.challenge == null) { - return Mono.just(false); - } - } else { - if (!disableChallengeResourceVerification) { - if (!isChallengeResourceValid(request, scope)) { - throw LOGGER.logExceptionAsError(new RuntimeException(String - .format("The challenge resource '%s' does not match the requested domain. If you wish to " - + "disable this check for your client, pass 'true' to the SecretClientBuilder" - + ".disableChallengeResourceVerification() method when building it. See " - + "https://aka.ms/azsdk/blog/vault-uri for more information.", scope))); - } - } - - String authorization = challengeAttributes.get("authorization"); - - if (authorization == null) { - authorization = challengeAttributes.get("authorization_uri"); - } - - final URI authorizationUri; - - try { - authorizationUri = new URI(authorization); - } catch (URISyntaxException e) { - throw LOGGER.logExceptionAsError(new RuntimeException( - String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); - } - - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); - - CHALLENGE_CACHE.put(authority, this.challenge); - } - - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext - .setClaims(new String(Base64Util.decodeString(claims), StandardCharsets.UTF_8)); - } - } - } - - return setAuthorizationHeader(context, tokenRequestContext).then(Mono.just(true)); - }); - } - - @Override - public void authorizeRequestSync(HttpPipelineCallContext context) { - HttpRequest request = context.getHttpRequest(); - - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } - - if (this.challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - setAuthorizationHeaderSync(context, tokenRequestContext); - - return; - } - - // The body is removed from the initial request because Key Vault supports other authentication schemes which - // also protect the body of the request. As a result, before we know the auth scheme we need to avoid sending an - // unprotected body to Key Vault. We don't currently support this enhanced auth scheme in the SDK, but we still - // don't want to send any unprotected data to vaults which require it. - - // Do not overwrite previous contents if retrying after initial request failed (e.g. timeout). - if (!context.getData(KEY_VAULT_STASHED_CONTENT_KEY).isPresent()) { - if (request.getBodyAsBinaryData() != null) { - context.setData(KEY_VAULT_STASHED_CONTENT_KEY, request.getBodyAsBinaryData()); - context.setData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY, request.getHeaders().getValue(CONTENT_LENGTH)); - request.setHeader(CONTENT_LENGTH, "0"); - request.setBody((BinaryData) null); - } - } - } - - @Override - public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, HttpResponse response) { - HttpRequest request = context.getHttpRequest(); - Optional contentOptional = context.getData(KEY_VAULT_STASHED_CONTENT_KEY); - Optional contentLengthOptional = context.getData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY); - - if (request.getBody() == null && contentOptional.isPresent() && contentLengthOptional.isPresent()) { - request.setBody((BinaryData) (contentOptional.get())); - request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); - } - - String authority = getRequestAuthority(request); - Map challengeAttributes - = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); - String scope = challengeAttributes.get("resource"); - - if (scope != null) { - scope = scope + "/.default"; - } else { - scope = challengeAttributes.get("scope"); - } - - if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); - - if (this.challenge == null) { - return false; - } - } else { - if (!disableChallengeResourceVerification) { - if (!isChallengeResourceValid(request, scope)) { - throw LOGGER.logExceptionAsError(new RuntimeException(String.format( - "The challenge resource '%s' does not match the requested domain. If you wish to disable " - + "this check for your client, pass 'true' to the SecretClientBuilder" - + ".disableChallengeResourceVerification() method when building it. See " - + "https://aka.ms/azsdk/blog/vault-uri for more information.", - scope))); - } - } - - String authorization = challengeAttributes.get("authorization"); - - if (authorization == null) { - authorization = challengeAttributes.get("authorization_uri"); - } - - final URI authorizationUri; - - try { - authorizationUri = new URI(authorization); - } catch (URISyntaxException e) { - throw LOGGER.logExceptionAsError(new RuntimeException( - String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); - } - - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); - - CHALLENGE_CACHE.put(authority, this.challenge); - } - - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext.setClaims(new String(Base64Util.decodeString(claims))); - } - } - } - - setAuthorizationHeaderSync(context, tokenRequestContext); - - return true; - } - - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { - return Mono.error(new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme.")); - } - - HttpPipelineNextPolicy nextPolicy = next.clone(); - - return authorizeRequest(context).then(Mono.defer(next::process)).flatMap(httpResponse -> { - String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (httpResponse.getStatusCode() == 401 && authHeader != null) { - return handleChallenge(context, httpResponse, nextPolicy); - } - - return Mono.just(httpResponse); - }); - } - - @Override - public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { - if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { - throw LOGGER.logExceptionAsError( - new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme.")); - } - - HttpPipelineNextSyncPolicy nextPolicy = next.clone(); - - authorizeRequestSync(context); - - HttpResponse httpResponse = next.processSync(); - String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (httpResponse.getStatusCode() == 401 && authHeader != null) { - return handleChallengeSync(context, httpResponse, nextPolicy); - } - - return httpResponse; - } - - private Mono handleChallenge(HttpPipelineCallContext context, HttpResponse httpResponse, - HttpPipelineNextPolicy next) { - return authorizeRequestOnChallenge(context, httpResponse).flatMap(authorized -> { - if (authorized) { - // The body needs to be closed or read to the end to release the connection. - httpResponse.close(); - - HttpPipelineNextPolicy nextPolicy = next.clone(); - - return next.process().flatMap(newResponse -> { - String authHeader = newResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (newResponse.getStatusCode() == 401 - && authHeader != null - && isClaimsPresent(newResponse) - && !isClaimsPresent(httpResponse)) { - - return handleChallenge(context, newResponse, nextPolicy); - } else { - return Mono.just(newResponse); - } - }); - } - - return Mono.just(httpResponse); - }); - } - - private HttpResponse handleChallengeSync(HttpPipelineCallContext context, HttpResponse httpResponse, - HttpPipelineNextSyncPolicy next) { - if (authorizeRequestOnChallengeSync(context, httpResponse)) { - // The body needs to be closed or read to the end to release the connection. - httpResponse.close(); - - HttpPipelineNextSyncPolicy nextPolicy = next.clone(); - HttpResponse newResponse = next.processSync(); - String authHeader = newResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (newResponse.getStatusCode() == 401 - && authHeader != null - && isClaimsPresent(newResponse) - && !isClaimsPresent(httpResponse)) { - - return handleChallengeSync(context, newResponse, nextPolicy); - } - - return newResponse; - } - - return httpResponse; - } - - private boolean isClaimsPresent(HttpResponse httpResponse) { - Map challengeAttributes - = extractChallengeAttributes(httpResponse.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); - - String error = challengeAttributes.get("error"); - - if (error != null) { - String base64Claims = challengeAttributes.get("claims"); - - return "insufficient_claims".equalsIgnoreCase(error) && base64Claims != null; - } - - return false; - } - - private static class ChallengeParameters { - private final URI authorizationUri; - private final String tenantId; - private final String[] scopes; - - ChallengeParameters(URI authorizationUri, String[] scopes) { - this.authorizationUri = authorizationUri; - tenantId = authorizationUri.getPath().split("/")[1]; - this.scopes = scopes; - } - - /** - * Get the {@code authorization} or {@code authorization_uri} parameter from the challenge response. - */ - public URI getAuthorizationUri() { - return authorizationUri; - } - - /** - * Get the {@code resource} or {@code scope} parameter from the challenge response. This should end with - * "/.default". - */ - public String[] getScopes() { - return scopes; - } - - /** - * Get the tenant ID from {@code authorizationUri}. - */ - public String getTenantId() { - return tenantId; - } - } - - public static void clearCache() { - CHALLENGE_CACHE.clear(); - } - - /** - * Gets the host name and port of the Key Vault or Managed HSM endpoint. - * - * @param request The {@link HttpRequest} to extract the host name and port from. - * - * @return The host name and port of the Key Vault or Managed HSM endpoint. - */ - private static String getRequestAuthority(HttpRequest request) { - URL url = request.getUrl(); - String authority = url.getAuthority(); - int port = url.getPort(); - - // Append port for complete authority. - if (!authority.contains(":") && port > 0) { - authority = authority + ":" + port; - } - - return authority; - } - - private static boolean isChallengeResourceValid(HttpRequest request, String scope) { - final URI scopeUri; - - try { - scopeUri = new URI(scope); - } catch (URISyntaxException e) { - throw LOGGER.logExceptionAsError( - new RuntimeException(String.format("The challenge resource '%s' is not a valid URI.", scope), e)); - } - - // Returns false if the host specified in the scope does not match the requested domain. - return request.getUrl() - .getHost() - .toLowerCase(Locale.ROOT) - .endsWith("." + scopeUri.getHost().toLowerCase(Locale.ROOT)); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java deleted file mode 100644 index c7044e3839df..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java +++ /dev/null @@ -1,712 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.security.keyvault.administration.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.exception.ClientAuthenticationException; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.RequestOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.security.keyvault.administration.KeyVaultAdministrationServiceVersion; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in RoleAssignments. - */ -public final class RoleAssignmentsImpl { - /** - * The proxy service used to perform REST calls. - */ - private final RoleAssignmentsService service; - - /** - * The service client containing this operation class. - */ - private final KeyVaultAdministrationClientImpl client; - - /** - * Initializes an instance of RoleAssignmentsImpl. - * - * @param client the instance of the service client containing this operation class. - */ - RoleAssignmentsImpl(KeyVaultAdministrationClientImpl client) { - this.service - = RestProxy.create(RoleAssignmentsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * Gets Service version. - * - * @return the serviceVersion value. - */ - public KeyVaultAdministrationServiceVersion getServiceVersion() { - return client.getServiceVersion(); - } - - /** - * The interface defining all the services for KeyVaultAdministrationClientRoleAssignments to be used by the proxy - * service to perform REST calls. - */ - @Host("{vaultBaseUrl}") - @ServiceInterface(name = "KeyVaultAdministrationClientRoleAs") - public interface RoleAssignmentsService { - @Delete("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> delete(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Delete("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response deleteSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Put("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> create(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, - RequestOptions requestOptions, Context context); - - @Put("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response createSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, - RequestOptions requestOptions, Context context); - - @Get("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> get(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Get("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response getSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Get("/{scope}/providers/Microsoft.Authorization/roleAssignments") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> listForScope(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Get("/{scope}/providers/Microsoft.Authorization/roleAssignments") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response listForScopeSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> listForScopeNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response listForScopeNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - } - - /** - * Deletes a role assignment. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignment to delete. - * @param roleAssignmentName The name of the role assignment to delete. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role Assignments along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String scope, String roleAssignmentName, - RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.delete(this.client.getVaultBaseUrl(), - this.client.getServiceVersion().getVersion(), scope, roleAssignmentName, accept, requestOptions, context)); - } - - /** - * Deletes a role assignment. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignment to delete. - * @param roleAssignmentName The name of the role assignment to delete. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role Assignments along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String scope, String roleAssignmentName, - RequestOptions requestOptions) { - final String accept = "application/json"; - return service.deleteSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, - roleAssignmentName, accept, requestOptions, Context.NONE); - } - - /** - * Creates a role assignment. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     properties (Required): {
-     *         roleDefinitionId: String (Required)
-     *         principalId: String (Required)
-     *     }
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignment to create. - * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. - * @param parameters Parameters for the role assignment. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role Assignments along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(String scope, String roleAssignmentName, - BinaryData parameters, RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.create(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), - scope, roleAssignmentName, contentType, accept, parameters, requestOptions, context)); - } - - /** - * Creates a role assignment. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     properties (Required): {
-     *         roleDefinitionId: String (Required)
-     *         principalId: String (Required)
-     *     }
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignment to create. - * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. - * @param parameters Parameters for the role assignment. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role Assignments along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(String scope, String roleAssignmentName, BinaryData parameters, - RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return service.createSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, - roleAssignmentName, contentType, accept, parameters, requestOptions, Context.NONE); - } - - /** - * Get the specified role assignment. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignment. - * @param roleAssignmentName The name of the role assignment to get. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the specified role assignment along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String scope, String roleAssignmentName, - RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.get(this.client.getVaultBaseUrl(), - this.client.getServiceVersion().getVersion(), scope, roleAssignmentName, accept, requestOptions, context)); - } - - /** - * Get the specified role assignment. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignment. - * @param roleAssignmentName The name of the role assignment to get. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the specified role assignment along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String scope, String roleAssignmentName, - RequestOptions requestOptions) { - final String accept = "application/json"; - return service.getSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, - roleAssignmentName, accept, requestOptions, Context.NONE); - } - - /** - * Gets role assignments for a scope. - *

Query Parameters

- * - * - * - * - *
Query Parameters
NameTypeRequiredDescription
$filterStringNoThe filter to apply on the operation. Use $filter=atScope() to - * return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments - * at, above or below the scope for the specified principal.
- * You can add these to a request with {@link RequestOptions#addQueryParam} - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignments. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role assignments for a scope along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listForScopeSinglePageAsync(String scope, RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listForScope(this.client.getVaultBaseUrl(), - this.client.getServiceVersion().getVersion(), scope, accept, requestOptions, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); - } - - /** - * Gets role assignments for a scope. - *

Query Parameters

- * - * - * - * - *
Query Parameters
NameTypeRequiredDescription
$filterStringNoThe filter to apply on the operation. Use $filter=atScope() to - * return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments - * at, above or below the scope for the specified principal.
- * You can add these to a request with {@link RequestOptions#addQueryParam} - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignments. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role assignments for a scope as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listForScopeAsync(String scope, RequestOptions requestOptions) { - RequestOptions requestOptionsForNextPage = new RequestOptions(); - requestOptionsForNextPage.setContext( - requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); - return new PagedFlux<>(() -> listForScopeSinglePageAsync(scope, requestOptions), - nextLink -> listForScopeNextSinglePageAsync(nextLink, requestOptionsForNextPage)); - } - - /** - * Gets role assignments for a scope. - *

Query Parameters

- * - * - * - * - *
Query Parameters
NameTypeRequiredDescription
$filterStringNoThe filter to apply on the operation. Use $filter=atScope() to - * return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments - * at, above or below the scope for the specified principal.
- * You can add these to a request with {@link RequestOptions#addQueryParam} - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignments. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role assignments for a scope along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private PagedResponse listForScopeSinglePage(String scope, RequestOptions requestOptions) { - final String accept = "application/json"; - Response res = service.listForScopeSync(this.client.getVaultBaseUrl(), - this.client.getServiceVersion().getVersion(), scope, accept, requestOptions, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); - } - - /** - * Gets role assignments for a scope. - *

Query Parameters

- * - * - * - * - *
Query Parameters
NameTypeRequiredDescription
$filterStringNoThe filter to apply on the operation. Use $filter=atScope() to - * return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments - * at, above or below the scope for the specified principal.
- * You can add these to a request with {@link RequestOptions#addQueryParam} - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role assignments. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role assignments for a scope as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listForScope(String scope, RequestOptions requestOptions) { - RequestOptions requestOptionsForNextPage = new RequestOptions(); - requestOptionsForNextPage.setContext( - requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); - return new PagedIterable<>(() -> listForScopeSinglePage(scope, requestOptions), - nextLink -> listForScopeNextSinglePage(nextLink, requestOptionsForNextPage)); - } - - /** - * Get the next page of items. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param nextLink The URL to get the next list of items. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role assignment list operation result along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listForScopeNextSinglePageAsync(String nextLink, - RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listForScopeNext(nextLink, this.client.getVaultBaseUrl(), accept, - requestOptions, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); - } - - /** - * Get the next page of items. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String (Optional)
-     *     properties (Optional): {
-     *         scope: String(///keys) (Optional)
-     *         roleDefinitionId: String (Optional)
-     *         principalId: String (Optional)
-     *     }
-     * }
-     * }
-     * 
- * - * @param nextLink The URL to get the next list of items. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role assignment list operation result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private PagedResponse listForScopeNextSinglePage(String nextLink, RequestOptions requestOptions) { - final String accept = "application/json"; - Response res = service.listForScopeNextSync(nextLink, this.client.getVaultBaseUrl(), accept, - requestOptions, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); - } - - private List getValues(BinaryData binaryData, String path) { - try { - Map obj = binaryData.toObject(Map.class); - List values = (List) obj.get(path); - return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); - } catch (RuntimeException e) { - return null; - } - } - - private String getNextLink(BinaryData binaryData, String path) { - try { - Map obj = binaryData.toObject(Map.class); - return (String) obj.get(path); - } catch (RuntimeException e) { - return null; - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java deleted file mode 100644 index 4a6e020fff6d..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java +++ /dev/null @@ -1,977 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.security.keyvault.administration.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.exception.ClientAuthenticationException; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.RequestOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.security.keyvault.administration.KeyVaultAdministrationServiceVersion; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in RoleDefinitions. - */ -public final class RoleDefinitionsImpl { - /** - * The proxy service used to perform REST calls. - */ - private final RoleDefinitionsService service; - - /** - * The service client containing this operation class. - */ - private final KeyVaultAdministrationClientImpl client; - - /** - * Initializes an instance of RoleDefinitionsImpl. - * - * @param client the instance of the service client containing this operation class. - */ - RoleDefinitionsImpl(KeyVaultAdministrationClientImpl client) { - this.service - = RestProxy.create(RoleDefinitionsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * Gets Service version. - * - * @return the serviceVersion value. - */ - public KeyVaultAdministrationServiceVersion getServiceVersion() { - return client.getServiceVersion(); - } - - /** - * The interface defining all the services for KeyVaultAdministrationClientRoleDefinitions to be used by the proxy - * service to perform REST calls. - */ - @Host("{vaultBaseUrl}") - @ServiceInterface(name = "KeyVaultAdministrationClientRoleDe") - public interface RoleDefinitionsService { - @Delete("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> delete(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Delete("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response deleteSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Put("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> createOrUpdate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, - RequestOptions requestOptions, Context context); - - @Put("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response createOrUpdateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, - RequestOptions requestOptions, Context context); - - @Get("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> get(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Get("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response getSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Get("/{scope}/providers/Microsoft.Authorization/roleDefinitions") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> list(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Get("/{scope}/providers/Microsoft.Authorization/roleDefinitions") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response listSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, - @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) - @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) - @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Response listNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, - RequestOptions requestOptions, Context context); - } - - /** - * Deletes a custom role definition. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. - * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String scope, String roleDefinitionName, - RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.delete(this.client.getVaultBaseUrl(), - this.client.getServiceVersion().getVersion(), scope, roleDefinitionName, accept, requestOptions, context)); - } - - /** - * Deletes a custom role definition. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. - * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String scope, String roleDefinitionName, - RequestOptions requestOptions) { - final String accept = "application/json"; - return service.deleteSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, - roleDefinitionName, accept, requestOptions, Context.NONE); - } - - /** - * Creates or updates a custom role definition. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     properties (Required): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to create or update. It can be any valid GUID. - * @param parameters Parameters for the role definition. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String scope, String roleDefinitionName, - BinaryData parameters, RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.createOrUpdate(this.client.getVaultBaseUrl(), - this.client.getServiceVersion().getVersion(), scope, roleDefinitionName, contentType, accept, parameters, - requestOptions, context)); - } - - /** - * Creates or updates a custom role definition. - *

Request Body Schema

- * - *
-     * {@code
-     * {
-     *     properties (Required): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to create or update. It can be any valid GUID. - * @param parameters Parameters for the role definition. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String scope, String roleDefinitionName, - BinaryData parameters, RequestOptions requestOptions) { - final String contentType = "application/json"; - final String accept = "application/json"; - return service.createOrUpdateSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), - scope, roleDefinitionName, contentType, accept, parameters, requestOptions, Context.NONE); - } - - /** - * Get the specified role definition. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition to get. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to get. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the specified role definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String scope, String roleDefinitionName, - RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.get(this.client.getVaultBaseUrl(), - this.client.getServiceVersion().getVersion(), scope, roleDefinitionName, accept, requestOptions, context)); - } - - /** - * Get the specified role definition. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition to get. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to get. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return the specified role definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String scope, String roleDefinitionName, - RequestOptions requestOptions) { - final String accept = "application/json"; - return service.getSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, - roleDefinitionName, accept, requestOptions, Context.NONE); - } - - /** - * Get all role definitions that are applicable at scope and above. - *

Query Parameters

- * - * - * - * - *
Query Parameters
NameTypeRequiredDescription
$filterStringNoThe filter to apply on the operation. Use atScopeAndBelow - * filter to search below the given scope as well.
- * You can add these to a request with {@link RequestOptions#addQueryParam} - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return all role definitions that are applicable at scope and above along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listSinglePageAsync(String scope, RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getVaultBaseUrl(), - this.client.getServiceVersion().getVersion(), scope, accept, requestOptions, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); - } - - /** - * Get all role definitions that are applicable at scope and above. - *

Query Parameters

- * - * - * - * - *
Query Parameters
NameTypeRequiredDescription
$filterStringNoThe filter to apply on the operation. Use atScopeAndBelow - * filter to search below the given scope as well.
- * You can add these to a request with {@link RequestOptions#addQueryParam} - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return all role definitions that are applicable at scope and above as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(String scope, RequestOptions requestOptions) { - RequestOptions requestOptionsForNextPage = new RequestOptions(); - requestOptionsForNextPage.setContext( - requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); - return new PagedFlux<>(() -> listSinglePageAsync(scope, requestOptions), - nextLink -> listNextSinglePageAsync(nextLink, requestOptionsForNextPage)); - } - - /** - * Get all role definitions that are applicable at scope and above. - *

Query Parameters

- * - * - * - * - *
Query Parameters
NameTypeRequiredDescription
$filterStringNoThe filter to apply on the operation. Use atScopeAndBelow - * filter to search below the given scope as well.
- * You can add these to a request with {@link RequestOptions#addQueryParam} - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return all role definitions that are applicable at scope and above along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private PagedResponse listSinglePage(String scope, RequestOptions requestOptions) { - final String accept = "application/json"; - Response res = service.listSync(this.client.getVaultBaseUrl(), - this.client.getServiceVersion().getVersion(), scope, accept, requestOptions, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); - } - - /** - * Get all role definitions that are applicable at scope and above. - *

Query Parameters

- * - * - * - * - *
Query Parameters
NameTypeRequiredDescription
$filterStringNoThe filter to apply on the operation. Use atScopeAndBelow - * filter to search below the given scope as well.
- * You can add these to a request with {@link RequestOptions#addQueryParam} - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param scope The scope of the role definition. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return all role definitions that are applicable at scope and above as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String scope, RequestOptions requestOptions) { - RequestOptions requestOptionsForNextPage = new RequestOptions(); - requestOptionsForNextPage.setContext( - requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); - return new PagedIterable<>(() -> listSinglePage(scope, requestOptions), - nextLink -> listNextSinglePage(nextLink, requestOptionsForNextPage)); - } - - /** - * Get the next page of items. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param nextLink The URL to get the next list of items. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role definition list operation result along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listNext(nextLink, this.client.getVaultBaseUrl(), accept, requestOptions, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); - } - - /** - * Get the next page of items. - *

Response Body Schema

- * - *
-     * {@code
-     * {
-     *     id: String (Optional)
-     *     name: String (Optional)
-     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
-     *     properties (Optional): {
-     *         roleName: String (Optional)
-     *         description: String (Optional)
-     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
-     *         permissions (Optional): [
-     *              (Optional){
-     *                 actions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 notActions (Optional): [
-     *                     String (Optional)
-     *                 ]
-     *                 dataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *                 notDataActions (Optional): [
-     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
-     *                 ]
-     *             }
-     *         ]
-     *         assignableScopes (Optional): [
-     *             String(///keys) (Optional)
-     *         ]
-     *     }
-     * }
-     * }
-     * 
- * - * @param nextLink The URL to get the next list of items. - * @param requestOptions The options to configure the HTTP request before HTTP client sends it. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. - * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. - * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. - * @return role definition list operation result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private PagedResponse listNextSinglePage(String nextLink, RequestOptions requestOptions) { - final String accept = "application/json"; - Response res - = service.listNextSync(nextLink, this.client.getVaultBaseUrl(), accept, requestOptions, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); - } - - private List getValues(BinaryData binaryData, String path) { - try { - Map obj = binaryData.toObject(Map.class); - List values = (List) obj.get(path); - return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); - } catch (RuntimeException e) { - return null; - } - } - - private String getNextLink(BinaryData binaryData, String path) { - try { - Map obj = binaryData.toObject(Map.class); - return (String) obj.get(path); - } catch (RuntimeException e) { - return null; - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Error.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Error.java deleted file mode 100644 index 11a8af359290..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Error.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The key vault server error. - */ -@Immutable -public final class Error implements JsonSerializable { - - /* - * The error code. - */ - @Generated - private String code; - - /* - * The error message. - */ - @Generated - private String message; - - /* - * The key vault server error. - */ - @Generated - private Error innerError; - - /** - * Creates an instance of Error class. - */ - @Generated - private Error() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - @Generated - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - @Generated - public String getMessage() { - return this.message; - } - - /** - * Get the innerError property: The key vault server error. - * - * @return the innerError value. - */ - @Generated - public Error getInnerError() { - return this.innerError; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Error from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Error if the JsonReader was pointing to an instance of it, or null if it was pointing to - * JSON null. - * @throws IOException If an error occurs while reading the Error. - */ - @Generated - public static Error fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Error deserializedError = new Error(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("code".equals(fieldName)) { - deserializedError.code = reader.getString(); - } else if ("message".equals(fieldName)) { - deserializedError.message = reader.getString(); - } else if ("innererror".equals(fieldName)) { - deserializedError.innerError = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - return deserializedError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperation.java deleted file mode 100644 index 9e80b74d3953..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperation.java +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * Full backup operation. - */ -@Immutable -public final class FullBackupOperation implements JsonSerializable { - - /* - * Status of the backup operation. - */ - @Generated - private OperationStatus status; - - /* - * The status details of backup operation. - */ - @Generated - private String statusDetails; - - /* - * Error encountered, if any, during the full backup operation. - */ - @Generated - private FullBackupOperationError error; - - /* - * The start time of the backup operation in UTC - */ - @Generated - private Long startTime; - - /* - * The end time of the backup operation in UTC - */ - @Generated - private Long endTime; - - /* - * Identifier for the full backup operation. - */ - @Generated - private String jobId; - - /* - * The Azure blob storage container Uri which contains the full backup - */ - @Generated - private String azureStorageBlobContainerUri; - - /** - * Creates an instance of FullBackupOperation class. - */ - @Generated - private FullBackupOperation() { - } - - /** - * Get the status property: Status of the backup operation. - * - * @return the status value. - */ - @Generated - public OperationStatus getStatus() { - return this.status; - } - - /** - * Get the statusDetails property: The status details of backup operation. - * - * @return the statusDetails value. - */ - @Generated - public String getStatusDetails() { - return this.statusDetails; - } - - /** - * Get the error property: Error encountered, if any, during the full backup operation. - * - * @return the error value. - */ - @Generated - public FullBackupOperationError getError() { - return this.error; - } - - /** - * Get the startTime property: The start time of the backup operation in UTC. - * - * @return the startTime value. - */ - @Generated - public OffsetDateTime getStartTime() { - if (this.startTime == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.startTime), ZoneOffset.UTC); - } - - /** - * Get the endTime property: The end time of the backup operation in UTC. - * - * @return the endTime value. - */ - @Generated - public OffsetDateTime getEndTime() { - if (this.endTime == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.endTime), ZoneOffset.UTC); - } - - /** - * Get the jobId property: Identifier for the full backup operation. - * - * @return the jobId value. - */ - @Generated - public String getJobId() { - return this.jobId; - } - - /** - * Get the azureStorageBlobContainerUri property: The Azure blob storage container Uri which contains the full - * backup. - * - * @return the azureStorageBlobContainerUri value. - */ - @Generated - public String getAzureStorageBlobContainerUri() { - return this.azureStorageBlobContainerUri; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); - jsonWriter.writeStringField("statusDetails", this.statusDetails); - jsonWriter.writeJsonField("error", this.error); - jsonWriter.writeNumberField("startTime", this.startTime); - jsonWriter.writeNumberField("endTime", this.endTime); - jsonWriter.writeStringField("jobId", this.jobId); - jsonWriter.writeStringField("azureStorageBlobContainerUri", this.azureStorageBlobContainerUri); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of FullBackupOperation from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of FullBackupOperation if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the FullBackupOperation. - */ - @Generated - public static FullBackupOperation fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - FullBackupOperation deserializedFullBackupOperation = new FullBackupOperation(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("status".equals(fieldName)) { - deserializedFullBackupOperation.status = OperationStatus.fromString(reader.getString()); - } else if ("statusDetails".equals(fieldName)) { - deserializedFullBackupOperation.statusDetails = reader.getString(); - } else if ("error".equals(fieldName)) { - deserializedFullBackupOperation.error = FullBackupOperationError.fromJson(reader); - } else if ("startTime".equals(fieldName)) { - deserializedFullBackupOperation.startTime = reader.getNullable(JsonReader::getLong); - } else if ("endTime".equals(fieldName)) { - deserializedFullBackupOperation.endTime = reader.getNullable(JsonReader::getLong); - } else if ("jobId".equals(fieldName)) { - deserializedFullBackupOperation.jobId = reader.getString(); - } else if ("azureStorageBlobContainerUri".equals(fieldName)) { - deserializedFullBackupOperation.azureStorageBlobContainerUri = reader.getString(); - } else { - reader.skipChildren(); - } - } - return deserializedFullBackupOperation; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperationError.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperationError.java deleted file mode 100644 index 04d1ce8d1244..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperationError.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The FullBackupOperationError model. - */ -@Immutable -public final class FullBackupOperationError implements JsonSerializable { - - /* - * The error code. - */ - @Generated - private String code; - - /* - * The error message. - */ - @Generated - private String message; - - /* - * The key vault server error. - */ - @Generated - private FullBackupOperationError innerError; - - /** - * Creates an instance of FullBackupOperationError class. - */ - @Generated - private FullBackupOperationError() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - @Generated - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - @Generated - public String getMessage() { - return this.message; - } - - /** - * Get the innerError property: The key vault server error. - * - * @return the innerError value. - */ - @Generated - public FullBackupOperationError getInnerError() { - return this.innerError; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of FullBackupOperationError from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of FullBackupOperationError if the JsonReader was pointing to an instance of it, or null if - * it was pointing to JSON null. - * @throws IOException If an error occurs while reading the FullBackupOperationError. - */ - @Generated - public static FullBackupOperationError fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - FullBackupOperationError deserializedFullBackupOperationError = new FullBackupOperationError(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("code".equals(fieldName)) { - deserializedFullBackupOperationError.code = reader.getString(); - } else if ("message".equals(fieldName)) { - deserializedFullBackupOperationError.message = reader.getString(); - } else if ("innererror".equals(fieldName)) { - deserializedFullBackupOperationError.innerError = FullBackupOperationError.fromJson(reader); - } else { - reader.skipChildren(); - } - } - return deserializedFullBackupOperationError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/OperationStatus.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/OperationStatus.java deleted file mode 100644 index 3177a6fdba2f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/OperationStatus.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The status of a long-running operation. - */ -public final class OperationStatus extends ExpandableStringEnum { - - /** - * The operation is in progress. - */ - @Generated - public static final OperationStatus IN_PROGRESS = fromString("InProgress"); - - /** - * The operation successfully completed. - */ - @Generated - public static final OperationStatus SUCCEEDED = fromString("Succeeded"); - - /** - * The operation was canceled. - */ - @Generated - public static final OperationStatus CANCELED = fromString("Canceled"); - - /** - * The operation failed. - */ - @Generated - public static final OperationStatus FAILED = fromString("Failed"); - - /** - * Creates a new instance of OperationStatus value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public OperationStatus() { - } - - /** - * Creates or finds a OperationStatus from its string representation. - * - * @param name a name to look for. - * @return the corresponding OperationStatus. - */ - @Generated - public static OperationStatus fromString(String name) { - return fromString(name, OperationStatus.class); - } - - /** - * Gets known OperationStatus values. - * - * @return known OperationStatus values. - */ - @Generated - public static Collection values() { - return values(OperationStatus.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Permission.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Permission.java deleted file mode 100644 index c66cfa63bf54..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Permission.java +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.annotation.Generated; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.administration.models.KeyVaultDataAction; -import java.io.IOException; -import java.util.List; - -/** - * Role definition permissions. - */ -@Fluent -public final class Permission implements JsonSerializable { - - /* - * Action permissions that are granted. - */ - @Generated - private List actions; - - /* - * Action permissions that are excluded but not denied. They may be granted by other role definitions assigned to a - * principal. - */ - @Generated - private List notActions; - - /* - * Data action permissions that are granted. - */ - @Generated - private List dataActions; - - /* - * Data action permissions that are excluded but not denied. They may be granted by other role definitions assigned - * to a principal. - */ - @Generated - private List notDataActions; - - /** - * Creates an instance of Permission class. - */ - @Generated - public Permission() { - } - - /** - * Get the actions property: Action permissions that are granted. - * - * @return the actions value. - */ - @Generated - public List getActions() { - return this.actions; - } - - /** - * Set the actions property: Action permissions that are granted. - * - * @param actions the actions value to set. - * @return the Permission object itself. - */ - @Generated - public Permission setActions(List actions) { - this.actions = actions; - return this; - } - - /** - * Get the notActions property: Action permissions that are excluded but not denied. They may be granted by other - * role definitions assigned to a principal. - * - * @return the notActions value. - */ - @Generated - public List getNotActions() { - return this.notActions; - } - - /** - * Set the notActions property: Action permissions that are excluded but not denied. They may be granted by other - * role definitions assigned to a principal. - * - * @param notActions the notActions value to set. - * @return the Permission object itself. - */ - @Generated - public Permission setNotActions(List notActions) { - this.notActions = notActions; - return this; - } - - /** - * Get the dataActions property: Data action permissions that are granted. - * - * @return the dataActions value. - */ - @Generated - public List getDataActions() { - return this.dataActions; - } - - /** - * Set the dataActions property: Data action permissions that are granted. - * - * @param dataActions the dataActions value to set. - * @return the Permission object itself. - */ - @Generated - public Permission setDataActions(List dataActions) { - this.dataActions = dataActions; - return this; - } - - /** - * Get the notDataActions property: Data action permissions that are excluded but not denied. They may be granted by - * other role definitions assigned to a principal. - * - * @return the notDataActions value. - */ - @Generated - public List getNotDataActions() { - return this.notDataActions; - } - - /** - * Set the notDataActions property: Data action permissions that are excluded but not denied. They may be granted by - * other role definitions assigned to a principal. - * - * @param notDataActions the notDataActions value to set. - * @return the Permission object itself. - */ - @Generated - public Permission setNotDataActions(List notDataActions) { - this.notDataActions = notDataActions; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("actions", this.actions, (writer, element) -> writer.writeString(element)); - jsonWriter.writeArrayField("notActions", this.notActions, (writer, element) -> writer.writeString(element)); - jsonWriter.writeArrayField("dataActions", this.dataActions, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - jsonWriter.writeArrayField("notDataActions", this.notDataActions, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Permission from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Permission if the JsonReader was pointing to an instance of it, or null if it was pointing - * to JSON null. - * @throws IOException If an error occurs while reading the Permission. - */ - @Generated - public static Permission fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Permission deserializedPermission = new Permission(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("actions".equals(fieldName)) { - List actions = reader.readArray(reader1 -> reader1.getString()); - deserializedPermission.actions = actions; - } else if ("notActions".equals(fieldName)) { - List notActions = reader.readArray(reader1 -> reader1.getString()); - deserializedPermission.notActions = notActions; - } else if ("dataActions".equals(fieldName)) { - List dataActions - = reader.readArray(reader1 -> KeyVaultDataAction.fromString(reader1.getString())); - deserializedPermission.dataActions = dataActions; - } else if ("notDataActions".equals(fieldName)) { - List notDataActions - = reader.readArray(reader1 -> KeyVaultDataAction.fromString(reader1.getString())); - deserializedPermission.notDataActions = notDataActions; - } else { - reader.skipChildren(); - } - } - return deserializedPermission; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreBackupOperationParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreBackupOperationParameters.java deleted file mode 100644 index 82e2a4dc67ea..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreBackupOperationParameters.java +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.annotation.Generated; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The authentication method and location for the backup operation. - */ -@Fluent -public final class PreBackupOperationParameters implements JsonSerializable { - - /* - * Azure Blob storage container Uri - */ - @Generated - private String storageResourceUri; - - /* - * The SAS token pointing to an Azure Blob storage container - */ - @Generated - private String token; - - /* - * Indicates which authentication method should be used. If set to true, Managed HSM will use the configured - * user-assigned managed identity to authenticate with Azure Storage. Otherwise, a SAS token has to be specified. - */ - @Generated - private Boolean useManagedIdentity; - - /** - * Creates an instance of PreBackupOperationParameters class. - */ - @Generated - public PreBackupOperationParameters() { - } - - /** - * Get the storageResourceUri property: Azure Blob storage container Uri. - * - * @return the storageResourceUri value. - */ - @Generated - public String getStorageResourceUri() { - return this.storageResourceUri; - } - - /** - * Set the storageResourceUri property: Azure Blob storage container Uri. - * - * @param storageResourceUri the storageResourceUri value to set. - * @return the PreBackupOperationParameters object itself. - */ - @Generated - public PreBackupOperationParameters setStorageResourceUri(String storageResourceUri) { - this.storageResourceUri = storageResourceUri; - return this; - } - - /** - * Get the token property: The SAS token pointing to an Azure Blob storage container. - * - * @return the token value. - */ - @Generated - public String getToken() { - return this.token; - } - - /** - * Set the token property: The SAS token pointing to an Azure Blob storage container. - * - * @param token the token value to set. - * @return the PreBackupOperationParameters object itself. - */ - @Generated - public PreBackupOperationParameters setToken(String token) { - this.token = token; - return this; - } - - /** - * Get the useManagedIdentity property: Indicates which authentication method should be used. If set to true, - * Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, - * a SAS token has to be specified. - * - * @return the useManagedIdentity value. - */ - @Generated - public Boolean isUseManagedIdentity() { - return this.useManagedIdentity; - } - - /** - * Set the useManagedIdentity property: Indicates which authentication method should be used. If set to true, - * Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, - * a SAS token has to be specified. - * - * @param useManagedIdentity the useManagedIdentity value to set. - * @return the PreBackupOperationParameters object itself. - */ - @Generated - public PreBackupOperationParameters setUseManagedIdentity(Boolean useManagedIdentity) { - this.useManagedIdentity = useManagedIdentity; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("storageResourceUri", this.storageResourceUri); - jsonWriter.writeStringField("token", this.token); - jsonWriter.writeBooleanField("useManagedIdentity", this.useManagedIdentity); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of PreBackupOperationParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of PreBackupOperationParameters if the JsonReader was pointing to an instance of it, or null - * if it was pointing to JSON null. - * @throws IOException If an error occurs while reading the PreBackupOperationParameters. - */ - @Generated - public static PreBackupOperationParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - PreBackupOperationParameters deserializedPreBackupOperationParameters = new PreBackupOperationParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("storageResourceUri".equals(fieldName)) { - deserializedPreBackupOperationParameters.storageResourceUri = reader.getString(); - } else if ("token".equals(fieldName)) { - deserializedPreBackupOperationParameters.token = reader.getString(); - } else if ("useManagedIdentity".equals(fieldName)) { - deserializedPreBackupOperationParameters.useManagedIdentity - = reader.getNullable(JsonReader::getBoolean); - } else { - reader.skipChildren(); - } - } - return deserializedPreBackupOperationParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreRestoreOperationParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreRestoreOperationParameters.java deleted file mode 100644 index bc6c4cc9456e..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreRestoreOperationParameters.java +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.annotation.Generated; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The authentication method and location for the restore operation. - */ -@Fluent -public final class PreRestoreOperationParameters implements JsonSerializable { - - /* - * A user-provided SAS token to an Azure blob storage container. - */ - @Generated - private SASTokenParameter sasTokenParameters; - - /* - * The Folder name of the blob where the previous successful full backup was stored - */ - @Generated - private String folderToRestore; - - /** - * Creates an instance of PreRestoreOperationParameters class. - */ - @Generated - public PreRestoreOperationParameters() { - } - - /** - * Get the sasTokenParameters property: A user-provided SAS token to an Azure blob storage container. - * - * @return the sasTokenParameters value. - */ - @Generated - public SASTokenParameter getSasTokenParameters() { - return this.sasTokenParameters; - } - - /** - * Set the sasTokenParameters property: A user-provided SAS token to an Azure blob storage container. - * - * @param sasTokenParameters the sasTokenParameters value to set. - * @return the PreRestoreOperationParameters object itself. - */ - @Generated - public PreRestoreOperationParameters setSasTokenParameters(SASTokenParameter sasTokenParameters) { - this.sasTokenParameters = sasTokenParameters; - return this; - } - - /** - * Get the folderToRestore property: The Folder name of the blob where the previous successful full backup was - * stored. - * - * @return the folderToRestore value. - */ - @Generated - public String getFolderToRestore() { - return this.folderToRestore; - } - - /** - * Set the folderToRestore property: The Folder name of the blob where the previous successful full backup was - * stored. - * - * @param folderToRestore the folderToRestore value to set. - * @return the PreRestoreOperationParameters object itself. - */ - @Generated - public PreRestoreOperationParameters setFolderToRestore(String folderToRestore) { - this.folderToRestore = folderToRestore; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("sasTokenParameters", this.sasTokenParameters); - jsonWriter.writeStringField("folderToRestore", this.folderToRestore); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of PreRestoreOperationParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of PreRestoreOperationParameters if the JsonReader was pointing to an instance of it, or null - * if it was pointing to JSON null. - * @throws IOException If an error occurs while reading the PreRestoreOperationParameters. - */ - @Generated - public static PreRestoreOperationParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - PreRestoreOperationParameters deserializedPreRestoreOperationParameters - = new PreRestoreOperationParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("sasTokenParameters".equals(fieldName)) { - deserializedPreRestoreOperationParameters.sasTokenParameters = SASTokenParameter.fromJson(reader); - } else if ("folderToRestore".equals(fieldName)) { - deserializedPreRestoreOperationParameters.folderToRestore = reader.getString(); - } else { - reader.skipChildren(); - } - } - return deserializedPreRestoreOperationParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperation.java deleted file mode 100644 index c6da7ae001ad..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperation.java +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * Restore operation. - */ -@Immutable -public final class RestoreOperation implements JsonSerializable { - - /* - * Status of the restore operation. - */ - @Generated - private OperationStatus status; - - /* - * The status details of restore operation. - */ - @Generated - private String statusDetails; - - /* - * Error encountered, if any, during the restore operation. - */ - @Generated - private FullBackupOperationError error; - - /* - * Identifier for the restore operation. - */ - @Generated - private String jobId; - - /* - * The start time of the restore operation - */ - @Generated - private Long startTime; - - /* - * The end time of the restore operation - */ - @Generated - private Long endTime; - - /** - * Creates an instance of RestoreOperation class. - */ - @Generated - private RestoreOperation() { - } - - /** - * Get the status property: Status of the restore operation. - * - * @return the status value. - */ - @Generated - public OperationStatus getStatus() { - return this.status; - } - - /** - * Get the statusDetails property: The status details of restore operation. - * - * @return the statusDetails value. - */ - @Generated - public String getStatusDetails() { - return this.statusDetails; - } - - /** - * Get the error property: Error encountered, if any, during the restore operation. - * - * @return the error value. - */ - @Generated - public FullBackupOperationError getError() { - return this.error; - } - - /** - * Get the jobId property: Identifier for the restore operation. - * - * @return the jobId value. - */ - @Generated - public String getJobId() { - return this.jobId; - } - - /** - * Get the startTime property: The start time of the restore operation. - * - * @return the startTime value. - */ - @Generated - public OffsetDateTime getStartTime() { - if (this.startTime == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.startTime), ZoneOffset.UTC); - } - - /** - * Get the endTime property: The end time of the restore operation. - * - * @return the endTime value. - */ - @Generated - public OffsetDateTime getEndTime() { - if (this.endTime == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.endTime), ZoneOffset.UTC); - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); - jsonWriter.writeStringField("statusDetails", this.statusDetails); - jsonWriter.writeJsonField("error", this.error); - jsonWriter.writeStringField("jobId", this.jobId); - jsonWriter.writeNumberField("startTime", this.startTime); - jsonWriter.writeNumberField("endTime", this.endTime); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RestoreOperation from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RestoreOperation if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the RestoreOperation. - */ - @Generated - public static RestoreOperation fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RestoreOperation deserializedRestoreOperation = new RestoreOperation(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("status".equals(fieldName)) { - deserializedRestoreOperation.status = OperationStatus.fromString(reader.getString()); - } else if ("statusDetails".equals(fieldName)) { - deserializedRestoreOperation.statusDetails = reader.getString(); - } else if ("error".equals(fieldName)) { - deserializedRestoreOperation.error = FullBackupOperationError.fromJson(reader); - } else if ("jobId".equals(fieldName)) { - deserializedRestoreOperation.jobId = reader.getString(); - } else if ("startTime".equals(fieldName)) { - deserializedRestoreOperation.startTime = reader.getNullable(JsonReader::getLong); - } else if ("endTime".equals(fieldName)) { - deserializedRestoreOperation.endTime = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - return deserializedRestoreOperation; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperationParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperationParameters.java deleted file mode 100644 index 014035a12613..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperationParameters.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The authentication method and location for the restore operation. - */ -@Immutable -public final class RestoreOperationParameters implements JsonSerializable { - - /* - * A user-provided SAS token to an Azure blob storage container. - */ - @Generated - private final SASTokenParameter sasTokenParameters; - - /* - * The Folder name of the blob where the previous successful full backup was stored - */ - @Generated - private final String folderToRestore; - - /** - * Creates an instance of RestoreOperationParameters class. - * - * @param sasTokenParameters the sasTokenParameters value to set. - * @param folderToRestore the folderToRestore value to set. - */ - @Generated - public RestoreOperationParameters(SASTokenParameter sasTokenParameters, String folderToRestore) { - this.sasTokenParameters = sasTokenParameters; - this.folderToRestore = folderToRestore; - } - - /** - * Get the sasTokenParameters property: A user-provided SAS token to an Azure blob storage container. - * - * @return the sasTokenParameters value. - */ - @Generated - public SASTokenParameter getSasTokenParameters() { - return this.sasTokenParameters; - } - - /** - * Get the folderToRestore property: The Folder name of the blob where the previous successful full backup was - * stored. - * - * @return the folderToRestore value. - */ - @Generated - public String getFolderToRestore() { - return this.folderToRestore; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("sasTokenParameters", this.sasTokenParameters); - jsonWriter.writeStringField("folderToRestore", this.folderToRestore); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RestoreOperationParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RestoreOperationParameters if the JsonReader was pointing to an instance of it, or null if - * it was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the RestoreOperationParameters. - */ - @Generated - public static RestoreOperationParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SASTokenParameter sasTokenParameters = null; - String folderToRestore = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("sasTokenParameters".equals(fieldName)) { - sasTokenParameters = SASTokenParameter.fromJson(reader); - } else if ("folderToRestore".equals(fieldName)) { - folderToRestore = reader.getString(); - } else { - reader.skipChildren(); - } - } - return new RestoreOperationParameters(sasTokenParameters, folderToRestore); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignment.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignment.java deleted file mode 100644 index 163d5116e52f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignment.java +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Role Assignments. - */ -@Immutable -public final class RoleAssignment implements JsonSerializable { - - /* - * The role assignment ID. - */ - @Generated - private String id; - - /* - * The role assignment name. - */ - @Generated - private String name; - - /* - * The role assignment type. - */ - @Generated - private String type; - - /* - * Role assignment properties. - */ - @Generated - private RoleAssignmentPropertiesWithScope properties; - - /** - * Creates an instance of RoleAssignment class. - */ - @Generated - private RoleAssignment() { - } - - /** - * Get the id property: The role assignment ID. - * - * @return the id value. - */ - @Generated - public String getId() { - return this.id; - } - - /** - * Get the name property: The role assignment name. - * - * @return the name value. - */ - @Generated - public String getName() { - return this.name; - } - - /** - * Get the type property: The role assignment type. - * - * @return the type value. - */ - @Generated - public String getType() { - return this.type; - } - - /** - * Get the properties property: Role assignment properties. - * - * @return the properties value. - */ - @Generated - public RoleAssignmentPropertiesWithScope getProperties() { - return this.properties; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleAssignment from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleAssignment if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the RoleAssignment. - */ - @Generated - public static RoleAssignment fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleAssignment deserializedRoleAssignment = new RoleAssignment(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("id".equals(fieldName)) { - deserializedRoleAssignment.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedRoleAssignment.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedRoleAssignment.type = reader.getString(); - } else if ("properties".equals(fieldName)) { - deserializedRoleAssignment.properties = RoleAssignmentPropertiesWithScope.fromJson(reader); - } else { - reader.skipChildren(); - } - } - return deserializedRoleAssignment; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentCreateParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentCreateParameters.java deleted file mode 100644 index 4eb1e9dfb4d5..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentCreateParameters.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Role assignment create parameters. - */ -@Immutable -public final class RoleAssignmentCreateParameters implements JsonSerializable { - - /* - * Role assignment properties. - */ - @Generated - private final RoleAssignmentProperties properties; - - /** - * Creates an instance of RoleAssignmentCreateParameters class. - * - * @param properties the properties value to set. - */ - @Generated - public RoleAssignmentCreateParameters(RoleAssignmentProperties properties) { - this.properties = properties; - } - - /** - * Get the properties property: Role assignment properties. - * - * @return the properties value. - */ - @Generated - public RoleAssignmentProperties getProperties() { - return this.properties; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleAssignmentCreateParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleAssignmentCreateParameters if the JsonReader was pointing to an instance of it, or - * null if it was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the RoleAssignmentCreateParameters. - */ - @Generated - public static RoleAssignmentCreateParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleAssignmentProperties properties = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("properties".equals(fieldName)) { - properties = RoleAssignmentProperties.fromJson(reader); - } else { - reader.skipChildren(); - } - } - return new RoleAssignmentCreateParameters(properties); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentProperties.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentProperties.java deleted file mode 100644 index a48930e5df97..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentProperties.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Role assignment properties. - */ -@Immutable -public final class RoleAssignmentProperties implements JsonSerializable { - - /* - * The role definition ID used in the role assignment. - */ - @Generated - private final String roleDefinitionId; - - /* - * The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, - * service principal, or security group. - */ - @Generated - private final String principalId; - - /** - * Creates an instance of RoleAssignmentProperties class. - * - * @param roleDefinitionId the roleDefinitionId value to set. - * @param principalId the principalId value to set. - */ - @Generated - public RoleAssignmentProperties(String roleDefinitionId, String principalId) { - this.roleDefinitionId = roleDefinitionId; - this.principalId = principalId; - } - - /** - * Get the roleDefinitionId property: The role definition ID used in the role assignment. - * - * @return the roleDefinitionId value. - */ - @Generated - public String getRoleDefinitionId() { - return this.roleDefinitionId; - } - - /** - * Get the principalId property: The principal ID assigned to the role. This maps to the ID inside the Active - * Directory. It can point to a user, service principal, or security group. - * - * @return the principalId value. - */ - @Generated - public String getPrincipalId() { - return this.principalId; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("roleDefinitionId", this.roleDefinitionId); - jsonWriter.writeStringField("principalId", this.principalId); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleAssignmentProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleAssignmentProperties if the JsonReader was pointing to an instance of it, or null if - * it was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the RoleAssignmentProperties. - */ - @Generated - public static RoleAssignmentProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String roleDefinitionId = null; - String principalId = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("roleDefinitionId".equals(fieldName)) { - roleDefinitionId = reader.getString(); - } else if ("principalId".equals(fieldName)) { - principalId = reader.getString(); - } else { - reader.skipChildren(); - } - } - return new RoleAssignmentProperties(roleDefinitionId, principalId); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentPropertiesWithScope.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentPropertiesWithScope.java deleted file mode 100644 index 3258393151fc..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentPropertiesWithScope.java +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import java.io.IOException; - -/** - * Role assignment properties with scope. - */ -@Immutable -public final class RoleAssignmentPropertiesWithScope implements JsonSerializable { - - /* - * The role scope. - */ - @Generated - private KeyVaultRoleScope scope; - - /* - * The role definition ID. - */ - @Generated - private String roleDefinitionId; - - /* - * The principal ID. - */ - @Generated - private String principalId; - - /** - * Creates an instance of RoleAssignmentPropertiesWithScope class. - */ - @Generated - private RoleAssignmentPropertiesWithScope() { - } - - /** - * Get the scope property: The role scope. - * - * @return the scope value. - */ - @Generated - public KeyVaultRoleScope getScope() { - return this.scope; - } - - /** - * Get the roleDefinitionId property: The role definition ID. - * - * @return the roleDefinitionId value. - */ - @Generated - public String getRoleDefinitionId() { - return this.roleDefinitionId; - } - - /** - * Get the principalId property: The principal ID. - * - * @return the principalId value. - */ - @Generated - public String getPrincipalId() { - return this.principalId; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("scope", this.scope == null ? null : this.scope.toString()); - jsonWriter.writeStringField("roleDefinitionId", this.roleDefinitionId); - jsonWriter.writeStringField("principalId", this.principalId); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleAssignmentPropertiesWithScope from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleAssignmentPropertiesWithScope if the JsonReader was pointing to an instance of it, or - * null if it was pointing to JSON null. - * @throws IOException If an error occurs while reading the RoleAssignmentPropertiesWithScope. - */ - @Generated - public static RoleAssignmentPropertiesWithScope fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleAssignmentPropertiesWithScope deserializedRoleAssignmentPropertiesWithScope - = new RoleAssignmentPropertiesWithScope(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("scope".equals(fieldName)) { - deserializedRoleAssignmentPropertiesWithScope.scope - = KeyVaultRoleScope.fromString(reader.getString()); - } else if ("roleDefinitionId".equals(fieldName)) { - deserializedRoleAssignmentPropertiesWithScope.roleDefinitionId = reader.getString(); - } else if ("principalId".equals(fieldName)) { - deserializedRoleAssignmentPropertiesWithScope.principalId = reader.getString(); - } else { - reader.skipChildren(); - } - } - return deserializedRoleAssignmentPropertiesWithScope; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinition.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinition.java deleted file mode 100644 index bc45f215b469..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinition.java +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinitionType; -import java.io.IOException; - -/** - * Role definition. - */ -@Immutable -public final class RoleDefinition implements JsonSerializable { - - /* - * The role definition ID. - */ - @Generated - private String id; - - /* - * The role definition name. - */ - @Generated - private String name; - - /* - * The role definition type. - */ - @Generated - private KeyVaultRoleDefinitionType type; - - /* - * Role definition properties. - */ - @Generated - private RoleDefinitionProperties properties; - - /** - * Creates an instance of RoleDefinition class. - */ - @Generated - private RoleDefinition() { - } - - /** - * Get the id property: The role definition ID. - * - * @return the id value. - */ - @Generated - public String getId() { - return this.id; - } - - /** - * Get the name property: The role definition name. - * - * @return the name value. - */ - @Generated - public String getName() { - return this.name; - } - - /** - * Get the type property: The role definition type. - * - * @return the type value. - */ - @Generated - public KeyVaultRoleDefinitionType getType() { - return this.type; - } - - /** - * Get the properties property: Role definition properties. - * - * @return the properties value. - */ - @Generated - public RoleDefinitionProperties getProperties() { - return this.properties; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleDefinition from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleDefinition if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the RoleDefinition. - */ - @Generated - public static RoleDefinition fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleDefinition deserializedRoleDefinition = new RoleDefinition(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("id".equals(fieldName)) { - deserializedRoleDefinition.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedRoleDefinition.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedRoleDefinition.type = KeyVaultRoleDefinitionType.fromString(reader.getString()); - } else if ("properties".equals(fieldName)) { - deserializedRoleDefinition.properties = RoleDefinitionProperties.fromJson(reader); - } else { - reader.skipChildren(); - } - } - return deserializedRoleDefinition; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionCreateParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionCreateParameters.java deleted file mode 100644 index eb4d7aa4dd43..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionCreateParameters.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Role definition create parameters. - */ -@Immutable -public final class RoleDefinitionCreateParameters implements JsonSerializable { - - /* - * Role definition properties. - */ - @Generated - private final RoleDefinitionProperties properties; - - /** - * Creates an instance of RoleDefinitionCreateParameters class. - * - * @param properties the properties value to set. - */ - @Generated - public RoleDefinitionCreateParameters(RoleDefinitionProperties properties) { - this.properties = properties; - } - - /** - * Get the properties property: Role definition properties. - * - * @return the properties value. - */ - @Generated - public RoleDefinitionProperties getProperties() { - return this.properties; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleDefinitionCreateParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleDefinitionCreateParameters if the JsonReader was pointing to an instance of it, or - * null if it was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the RoleDefinitionCreateParameters. - */ - @Generated - public static RoleDefinitionCreateParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleDefinitionProperties properties = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("properties".equals(fieldName)) { - properties = RoleDefinitionProperties.fromJson(reader); - } else { - reader.skipChildren(); - } - } - return new RoleDefinitionCreateParameters(properties); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionProperties.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionProperties.java deleted file mode 100644 index 8817dfb863f3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionProperties.java +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.annotation.Generated; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.KeyVaultRoleType; -import java.io.IOException; -import java.util.List; - -/** - * Role definition properties. - */ -@Fluent -public final class RoleDefinitionProperties implements JsonSerializable { - - /* - * The role name. - */ - @Generated - private String roleName; - - /* - * The role definition description. - */ - @Generated - private String description; - - /* - * The role type. - */ - @Generated - private KeyVaultRoleType roleType; - - /* - * Role definition permissions. - */ - @Generated - private List permissions; - - /* - * Role definition assignable scopes. - */ - @Generated - private List assignableScopes; - - /** - * Creates an instance of RoleDefinitionProperties class. - */ - @Generated - public RoleDefinitionProperties() { - } - - /** - * Get the roleName property: The role name. - * - * @return the roleName value. - */ - @Generated - public String getRoleName() { - return this.roleName; - } - - /** - * Set the roleName property: The role name. - * - * @param roleName the roleName value to set. - * @return the RoleDefinitionProperties object itself. - */ - @Generated - public RoleDefinitionProperties setRoleName(String roleName) { - this.roleName = roleName; - return this; - } - - /** - * Get the description property: The role definition description. - * - * @return the description value. - */ - @Generated - public String getDescription() { - return this.description; - } - - /** - * Set the description property: The role definition description. - * - * @param description the description value to set. - * @return the RoleDefinitionProperties object itself. - */ - @Generated - public RoleDefinitionProperties setDescription(String description) { - this.description = description; - return this; - } - - /** - * Get the roleType property: The role type. - * - * @return the roleType value. - */ - @Generated - public KeyVaultRoleType getRoleType() { - return this.roleType; - } - - /** - * Set the roleType property: The role type. - * - * @param roleType the roleType value to set. - * @return the RoleDefinitionProperties object itself. - */ - @Generated - public RoleDefinitionProperties setRoleType(KeyVaultRoleType roleType) { - this.roleType = roleType; - return this; - } - - /** - * Get the permissions property: Role definition permissions. - * - * @return the permissions value. - */ - @Generated - public List getPermissions() { - return this.permissions; - } - - /** - * Set the permissions property: Role definition permissions. - * - * @param permissions the permissions value to set. - * @return the RoleDefinitionProperties object itself. - */ - @Generated - public RoleDefinitionProperties setPermissions(List permissions) { - this.permissions = permissions; - return this; - } - - /** - * Get the assignableScopes property: Role definition assignable scopes. - * - * @return the assignableScopes value. - */ - @Generated - public List getAssignableScopes() { - return this.assignableScopes; - } - - /** - * Set the assignableScopes property: Role definition assignable scopes. - * - * @param assignableScopes the assignableScopes value to set. - * @return the RoleDefinitionProperties object itself. - */ - @Generated - public RoleDefinitionProperties setAssignableScopes(List assignableScopes) { - this.assignableScopes = assignableScopes; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("roleName", this.roleName); - jsonWriter.writeStringField("description", this.description); - jsonWriter.writeStringField("type", this.roleType == null ? null : this.roleType.toString()); - jsonWriter.writeArrayField("permissions", this.permissions, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeArrayField("assignableScopes", this.assignableScopes, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleDefinitionProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleDefinitionProperties if the JsonReader was pointing to an instance of it, or null if - * it was pointing to JSON null. - * @throws IOException If an error occurs while reading the RoleDefinitionProperties. - */ - @Generated - public static RoleDefinitionProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleDefinitionProperties deserializedRoleDefinitionProperties = new RoleDefinitionProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("roleName".equals(fieldName)) { - deserializedRoleDefinitionProperties.roleName = reader.getString(); - } else if ("description".equals(fieldName)) { - deserializedRoleDefinitionProperties.description = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedRoleDefinitionProperties.roleType = KeyVaultRoleType.fromString(reader.getString()); - } else if ("permissions".equals(fieldName)) { - List permissions = reader.readArray(reader1 -> Permission.fromJson(reader1)); - deserializedRoleDefinitionProperties.permissions = permissions; - } else if ("assignableScopes".equals(fieldName)) { - List assignableScopes - = reader.readArray(reader1 -> KeyVaultRoleScope.fromString(reader1.getString())); - deserializedRoleDefinitionProperties.assignableScopes = assignableScopes; - } else { - reader.skipChildren(); - } - } - return deserializedRoleDefinitionProperties; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SASTokenParameter.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SASTokenParameter.java deleted file mode 100644 index 763f8b45d21d..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SASTokenParameter.java +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.annotation.Generated; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * An authentication method and location for the operation. - */ -@Fluent -public final class SASTokenParameter implements JsonSerializable { - - /* - * Azure Blob storage container Uri - */ - @Generated - private final String storageResourceUri; - - /* - * The SAS token pointing to an Azure Blob storage container - */ - @Generated - private String token; - - /* - * Indicates which authentication method should be used. If set to true, Managed HSM will use the configured - * user-assigned managed identity to authenticate with Azure Storage. Otherwise, a SAS token has to be specified. - */ - @Generated - private Boolean useManagedIdentity; - - /** - * Creates an instance of SASTokenParameter class. - * - * @param storageResourceUri the storageResourceUri value to set. - */ - @Generated - public SASTokenParameter(String storageResourceUri) { - this.storageResourceUri = storageResourceUri; - } - - /** - * Get the storageResourceUri property: Azure Blob storage container Uri. - * - * @return the storageResourceUri value. - */ - @Generated - public String getStorageResourceUri() { - return this.storageResourceUri; - } - - /** - * Get the token property: The SAS token pointing to an Azure Blob storage container. - * - * @return the token value. - */ - @Generated - public String getToken() { - return this.token; - } - - /** - * Set the token property: The SAS token pointing to an Azure Blob storage container. - * - * @param token the token value to set. - * @return the SASTokenParameter object itself. - */ - @Generated - public SASTokenParameter setToken(String token) { - this.token = token; - return this; - } - - /** - * Get the useManagedIdentity property: Indicates which authentication method should be used. If set to true, - * Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, - * a SAS token has to be specified. - * - * @return the useManagedIdentity value. - */ - @Generated - public Boolean isUseManagedIdentity() { - return this.useManagedIdentity; - } - - /** - * Set the useManagedIdentity property: Indicates which authentication method should be used. If set to true, - * Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, - * a SAS token has to be specified. - * - * @param useManagedIdentity the useManagedIdentity value to set. - * @return the SASTokenParameter object itself. - */ - @Generated - public SASTokenParameter setUseManagedIdentity(Boolean useManagedIdentity) { - this.useManagedIdentity = useManagedIdentity; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("storageResourceUri", this.storageResourceUri); - jsonWriter.writeStringField("token", this.token); - jsonWriter.writeBooleanField("useManagedIdentity", this.useManagedIdentity); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SASTokenParameter from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SASTokenParameter if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SASTokenParameter. - */ - @Generated - public static SASTokenParameter fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String storageResourceUri = null; - String token = null; - Boolean useManagedIdentity = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("storageResourceUri".equals(fieldName)) { - storageResourceUri = reader.getString(); - } else if ("token".equals(fieldName)) { - token = reader.getString(); - } else if ("useManagedIdentity".equals(fieldName)) { - useManagedIdentity = reader.getNullable(JsonReader::getBoolean); - } else { - reader.skipChildren(); - } - } - SASTokenParameter deserializedSASTokenParameter = new SASTokenParameter(storageResourceUri); - deserializedSASTokenParameter.token = token; - deserializedSASTokenParameter.useManagedIdentity = useManagedIdentity; - return deserializedSASTokenParameter; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperation.java deleted file mode 100644 index a6b22b7e24c7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperation.java +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * Selective Key Restore operation. - */ -@Immutable -public final class SelectiveKeyRestoreOperation implements JsonSerializable { - - /* - * Status of the restore operation. - */ - @Generated - private OperationStatus status; - - /* - * The status details of restore operation. - */ - @Generated - private String statusDetails; - - /* - * Error encountered, if any, during the selective key restore operation. - */ - @Generated - private FullBackupOperationError error; - - /* - * Identifier for the selective key restore operation. - */ - @Generated - private String jobId; - - /* - * The start time of the restore operation - */ - @Generated - private Long startTime; - - /* - * The end time of the restore operation - */ - @Generated - private Long endTime; - - /** - * Creates an instance of SelectiveKeyRestoreOperation class. - */ - @Generated - private SelectiveKeyRestoreOperation() { - } - - /** - * Get the status property: Status of the restore operation. - * - * @return the status value. - */ - @Generated - public OperationStatus getStatus() { - return this.status; - } - - /** - * Get the statusDetails property: The status details of restore operation. - * - * @return the statusDetails value. - */ - @Generated - public String getStatusDetails() { - return this.statusDetails; - } - - /** - * Get the error property: Error encountered, if any, during the selective key restore operation. - * - * @return the error value. - */ - @Generated - public FullBackupOperationError getError() { - return this.error; - } - - /** - * Get the jobId property: Identifier for the selective key restore operation. - * - * @return the jobId value. - */ - @Generated - public String getJobId() { - return this.jobId; - } - - /** - * Get the startTime property: The start time of the restore operation. - * - * @return the startTime value. - */ - @Generated - public OffsetDateTime getStartTime() { - if (this.startTime == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.startTime), ZoneOffset.UTC); - } - - /** - * Get the endTime property: The end time of the restore operation. - * - * @return the endTime value. - */ - @Generated - public OffsetDateTime getEndTime() { - if (this.endTime == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.endTime), ZoneOffset.UTC); - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); - jsonWriter.writeStringField("statusDetails", this.statusDetails); - jsonWriter.writeJsonField("error", this.error); - jsonWriter.writeStringField("jobId", this.jobId); - jsonWriter.writeNumberField("startTime", this.startTime); - jsonWriter.writeNumberField("endTime", this.endTime); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SelectiveKeyRestoreOperation from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SelectiveKeyRestoreOperation if the JsonReader was pointing to an instance of it, or null - * if it was pointing to JSON null. - * @throws IOException If an error occurs while reading the SelectiveKeyRestoreOperation. - */ - @Generated - public static SelectiveKeyRestoreOperation fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SelectiveKeyRestoreOperation deserializedSelectiveKeyRestoreOperation = new SelectiveKeyRestoreOperation(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("status".equals(fieldName)) { - deserializedSelectiveKeyRestoreOperation.status = OperationStatus.fromString(reader.getString()); - } else if ("statusDetails".equals(fieldName)) { - deserializedSelectiveKeyRestoreOperation.statusDetails = reader.getString(); - } else if ("error".equals(fieldName)) { - deserializedSelectiveKeyRestoreOperation.error = FullBackupOperationError.fromJson(reader); - } else if ("jobId".equals(fieldName)) { - deserializedSelectiveKeyRestoreOperation.jobId = reader.getString(); - } else if ("startTime".equals(fieldName)) { - deserializedSelectiveKeyRestoreOperation.startTime = reader.getNullable(JsonReader::getLong); - } else if ("endTime".equals(fieldName)) { - deserializedSelectiveKeyRestoreOperation.endTime = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - return deserializedSelectiveKeyRestoreOperation; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationParameters.java deleted file mode 100644 index b1218fec61df..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationParameters.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The authentication method and location for the selective key restore operation. - */ -@Immutable -public final class SelectiveKeyRestoreOperationParameters - implements JsonSerializable { - - /* - * A user-provided SAS token to an Azure blob storage container. - */ - @Generated - private final SASTokenParameter sasTokenParameters; - - /* - * The Folder name of the blob where the previous successful full backup was stored - */ - @Generated - private final String folder; - - /** - * Creates an instance of SelectiveKeyRestoreOperationParameters class. - * - * @param sasTokenParameters the sasTokenParameters value to set. - * @param folder the folder value to set. - */ - @Generated - public SelectiveKeyRestoreOperationParameters(SASTokenParameter sasTokenParameters, String folder) { - this.sasTokenParameters = sasTokenParameters; - this.folder = folder; - } - - /** - * Get the sasTokenParameters property: A user-provided SAS token to an Azure blob storage container. - * - * @return the sasTokenParameters value. - */ - @Generated - public SASTokenParameter getSasTokenParameters() { - return this.sasTokenParameters; - } - - /** - * Get the folder property: The Folder name of the blob where the previous successful full backup was stored. - * - * @return the folder value. - */ - @Generated - public String getFolder() { - return this.folder; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("sasTokenParameters", this.sasTokenParameters); - jsonWriter.writeStringField("folder", this.folder); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SelectiveKeyRestoreOperationParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SelectiveKeyRestoreOperationParameters if the JsonReader was pointing to an instance of - * it, or null if it was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SelectiveKeyRestoreOperationParameters. - */ - @Generated - public static SelectiveKeyRestoreOperationParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SASTokenParameter sasTokenParameters = null; - String folder = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("sasTokenParameters".equals(fieldName)) { - sasTokenParameters = SASTokenParameter.fromJson(reader); - } else if ("folder".equals(fieldName)) { - folder = reader.getString(); - } else { - reader.skipChildren(); - } - } - return new SelectiveKeyRestoreOperationParameters(sasTokenParameters, folder); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Setting.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Setting.java deleted file mode 100644 index 4695e1257f6c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Setting.java +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.administration.models.KeyVaultSettingType; -import java.io.IOException; - -/** - * A Key Vault account setting. - */ -@Immutable -public final class Setting implements JsonSerializable { - - /* - * The account setting to be updated - */ - @Generated - private final String name; - - /* - * The value of the pool setting. - */ - @Generated - private final String value; - - /* - * The type specifier of the value. - */ - @Generated - private KeyVaultSettingType type; - - /** - * Creates an instance of Setting class. - * - * @param name the name value to set. - * @param value the value value to set. - */ - @Generated - private Setting(String name, String value) { - this.name = name; - this.value = value; - } - - /** - * Get the name property: The account setting to be updated. - * - * @return the name value. - */ - @Generated - public String getName() { - return this.name; - } - - /** - * Get the value property: The value of the pool setting. - * - * @return the value value. - */ - @Generated - public String getValue() { - return this.value; - } - - /** - * Get the type property: The type specifier of the value. - * - * @return the type value. - */ - @Generated - public KeyVaultSettingType getType() { - return this.type; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("value", this.value); - jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Setting from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Setting if the JsonReader was pointing to an instance of it, or null if it was pointing to - * JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the Setting. - */ - @Generated - public static Setting fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String name = null; - String value = null; - KeyVaultSettingType type = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("name".equals(fieldName)) { - name = reader.getString(); - } else if ("value".equals(fieldName)) { - value = reader.getString(); - } else if ("type".equals(fieldName)) { - type = KeyVaultSettingType.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - Setting deserializedSetting = new Setting(name, value); - deserializedSetting.type = type; - return deserializedSetting; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SettingsListResult.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SettingsListResult.java deleted file mode 100644 index 271dc4ac283c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SettingsListResult.java +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * The settings list result. - */ -@Immutable -public final class SettingsListResult implements JsonSerializable { - - /* - * A response message containing a list of account settings with their associated value. - */ - @Generated - private List settings; - - /** - * Creates an instance of SettingsListResult class. - */ - @Generated - private SettingsListResult() { - } - - /** - * Get the settings property: A response message containing a list of account settings with their associated value. - * - * @return the settings value. - */ - @Generated - public List getSettings() { - return this.settings; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SettingsListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SettingsListResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the SettingsListResult. - */ - @Generated - public static SettingsListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SettingsListResult deserializedSettingsListResult = new SettingsListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("settings".equals(fieldName)) { - List settings = reader.readArray(reader1 -> Setting.fromJson(reader1)); - deserializedSettingsListResult.settings = settings; - } else { - reader.skipChildren(); - } - } - return deserializedSettingsListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/UpdateSettingRequest.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/UpdateSettingRequest.java deleted file mode 100644 index 81eff3d0a138..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/UpdateSettingRequest.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The update settings request object. - */ -@Immutable -public final class UpdateSettingRequest implements JsonSerializable { - - /* - * The value of the pool setting. - */ - @Generated - private final String value; - - /** - * Creates an instance of UpdateSettingRequest class. - * - * @param value the value value to set. - */ - @Generated - public UpdateSettingRequest(String value) { - this.value = value; - } - - /** - * Get the value property: The value of the pool setting. - * - * @return the value value. - */ - @Generated - public String getValue() { - return this.value; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", this.value); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of UpdateSettingRequest from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of UpdateSettingRequest if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the UpdateSettingRequest. - */ - @Generated - public static UpdateSettingRequest fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String value = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("value".equals(fieldName)) { - value = reader.getString(); - } else { - reader.skipChildren(); - } - } - return new UpdateSettingRequest(value); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java deleted file mode 100644 index f49191054b5b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -/** - * - * Package containing the data models for KeyVault. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. - * - */ -package com.azure.security.keyvault.administration.implementation.models; diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/package-info.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/package-info.java deleted file mode 100644 index cbd02d9d7317..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. -/** - * Package containing the implementations for KeyVaultAccessControlClient, KeyVaultBackupClient, and - * KeyVaultSettingsClient. The key vault client performs cryptographic key operations and vault operations against the - * Key Vault service. - */ -package com.azure.security.keyvault.administration.implementation; diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultAdministrationError.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultAdministrationError.java deleted file mode 100644 index fa2adbe48d1d..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultAdministrationError.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -/** - * A class that represents an error occurred in a Key Vault operation. - */ -@Immutable -public final class KeyVaultAdministrationError { - private final String code; - private final String message; - private final KeyVaultAdministrationError innerError; - - /** - * Creates an object that represents an error occurred in a Key Vault operation. - * - * @param code The error code. - * @param message The error message. - * @param innerError An Key Vault server-side error. - */ - public KeyVaultAdministrationError(String code, String message, KeyVaultAdministrationError innerError) { - this.code = code; - this.message = message; - this.innerError = innerError; - } - - /** - * Get the error code. - * - * @return The error code. - */ - public String getCode() { - return this.code; - } - - /** - * Get the error message. - * - * @return The error message. - */ - public String getMessage() { - return this.message; - } - - /** - * Get the Key Vault server-side error. - * - * @return The Key Vault server-side error. - */ - public KeyVaultAdministrationError getInnerError() { - return this.innerError; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultAdministrationException.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultAdministrationException.java deleted file mode 100644 index 3983e0549591..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultAdministrationException.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** - * Exception thrown for an invalid response with {@link KeyVaultAdministrationError} information. - */ -@Immutable -public final class KeyVaultAdministrationException extends HttpResponseException { - /** - * Creates a new instance of the {@link KeyVaultAdministrationException} class. - * - * @param message The exception message or the response content if a message is not available. - * @param response The HTTP response. - */ - public KeyVaultAdministrationException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Creates a new instance of {@link KeyVaultAdministrationException}. - * - * @param message The exception message or the response content if a message is not available. - * @param response The HTTP response. - * @param value The deserialized response value. - */ - public KeyVaultAdministrationException(String message, HttpResponse response, KeyVaultAdministrationError value) { - super(message, response, value); - } - - @Override - public KeyVaultAdministrationError getValue() { - return (KeyVaultAdministrationError) super.getValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultBackupOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultBackupOperation.java deleted file mode 100644 index 1f05fb50b15c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultBackupOperation.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -import java.time.OffsetDateTime; - -/** - * A class that contains the details of a backup operation. - */ -@Immutable -public final class KeyVaultBackupOperation extends KeyVaultLongRunningOperation { - private final String azureStorageBlobContainerUrl; - - /** - * Creates an object containing the details of a {@link KeyVaultBackupOperation}. - * - * @param status Status of the {@link KeyVaultBackupOperation}. - * @param statusDetails The status details of the {@link KeyVaultBackupOperation}. - * @param error Error encountered, if any, during the {@link KeyVaultBackupOperation}. - * @param startTime The start time of the {@link KeyVaultBackupOperation}. - * @param endTime The end time of the {@link KeyVaultBackupOperation}. - * @param operationId Identifier for the full {@link KeyVaultBackupOperation}. - * @param azureStorageBlobContainerUrl The Azure blob storage container URI which contains the backup. - */ - public KeyVaultBackupOperation(String status, String statusDetails, KeyVaultAdministrationError error, - String operationId, OffsetDateTime startTime, OffsetDateTime endTime, String azureStorageBlobContainerUrl) { - super(status, statusDetails, error, operationId, startTime, endTime); - this.azureStorageBlobContainerUrl = azureStorageBlobContainerUrl; - } - - /** - * Get the Azure Blob Storage container URI where the backup resides. - * - * @return The backup URI in {@link String} form. - */ - public String getAzureStorageBlobContainerUrl() { - return azureStorageBlobContainerUrl; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultDataAction.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultDataAction.java deleted file mode 100644 index dd945292c216..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultDataAction.java +++ /dev/null @@ -1,278 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Supported permissions for data actions. - */ -public final class KeyVaultDataAction extends ExpandableStringEnum { - - /** - * Read HSM key metadata. - */ - @Generated - public static final KeyVaultDataAction READ_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/read/action"); - - /** - * Update an HSM key. - */ - @Generated - public static final KeyVaultDataAction WRITE_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/write/action"); - - /** - * Read deleted HSM key. - */ - @Generated - public static final KeyVaultDataAction READ_DELETED_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/deletedKeys/read/action"); - - /** - * Recover deleted HSM key. - */ - @Generated - public static final KeyVaultDataAction RECOVER_DELETED_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/deletedKeys/recover/action"); - - /** - * Backup HSM keys. - */ - @Generated - public static final KeyVaultDataAction BACKUP_HSM_KEYS - = fromString("Microsoft.KeyVault/managedHsm/keys/backup/action"); - - /** - * Restore HSM keys. - */ - @Generated - public static final KeyVaultDataAction RESTORE_HSM_KEYS - = fromString("Microsoft.KeyVault/managedHsm/keys/restore/action"); - - /** - * Delete role assignment. - */ - @Generated - public static final KeyVaultDataAction DELETE_ROLE_ASSIGNMENT - = fromString("Microsoft.KeyVault/managedHsm/roleAssignments/delete/action"); - - /** - * Get role assignment. - */ - @Generated - public static final KeyVaultDataAction GET_ROLE_ASSIGNMENT - = fromString("Microsoft.KeyVault/managedHsm/roleAssignments/read/action"); - - /** - * Create or update role assignment. - */ - @Generated - public static final KeyVaultDataAction WRITE_ROLE_ASSIGNMENT - = fromString("Microsoft.KeyVault/managedHsm/roleAssignments/write/action"); - - /** - * Get role definition. - */ - @Generated - public static final KeyVaultDataAction READ_ROLE_DEFINITION - = fromString("Microsoft.KeyVault/managedHsm/roleDefinitions/read/action"); - - /** - * Create or update role definition. - */ - @Generated - public static final KeyVaultDataAction WRITE_ROLE_DEFINITION - = fromString("Microsoft.KeyVault/managedHsm/roleDefinitions/write/action"); - - /** - * Delete role definition. - */ - @Generated - public static final KeyVaultDataAction DELETE_ROLE_DEFINITION - = fromString("Microsoft.KeyVault/managedHsm/roleDefinitions/delete/action"); - - /** - * Encrypt using an HSM key. - */ - @Generated - public static final KeyVaultDataAction ENCRYPT_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/encrypt/action"); - - /** - * Decrypt using an HSM key. - */ - @Generated - public static final KeyVaultDataAction DECRYPT_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/decrypt/action"); - - /** - * Wrap using an HSM key. - */ - @Generated - public static final KeyVaultDataAction WRAP_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/wrap/action"); - - /** - * Unwrap using an HSM key. - */ - @Generated - public static final KeyVaultDataAction UNWRAP_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/unwrap/action"); - - /** - * Sign using an HSM key. - */ - @Generated - public static final KeyVaultDataAction SIGN_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/sign/action"); - - /** - * Verify using an HSM key. - */ - @Generated - public static final KeyVaultDataAction VERIFY_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/verify/action"); - - /** - * Create an HSM key. - */ - @Generated - public static final KeyVaultDataAction CREATE_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/create"); - - /** - * Delete an HSM key. - */ - @Generated - public static final KeyVaultDataAction DELETE_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/delete"); - - /** - * Export an HSM key. - */ - @Generated - public static final KeyVaultDataAction EXPORT_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/export/action"); - - /** - * Release an HSM key using Secure Key Release. - */ - @Generated - public static final KeyVaultDataAction RELEASE_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/release/action"); - - /** - * Import an HSM key. - */ - @Generated - public static final KeyVaultDataAction IMPORT_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/import/action"); - - /** - * Purge a deleted HSM key. - */ - @Generated - public static final KeyVaultDataAction PURGE_DELETED_HSM_KEY - = fromString("Microsoft.KeyVault/managedHsm/keys/deletedKeys/delete"); - - /** - * Download an HSM security domain. - */ - @Generated - public static final KeyVaultDataAction DOWNLOAD_HSM_SECURITY_DOMAIN - = fromString("Microsoft.KeyVault/managedHsm/securitydomain/download/action"); - - /** - * Check status of HSM security domain download. - */ - @Generated - public static final KeyVaultDataAction DOWNLOAD_HSM_SECURITY_DOMAIN_STATUS - = fromString("Microsoft.KeyVault/managedHsm/securitydomain/download/read"); - - /** - * Upload an HSM security domain. - */ - @Generated - public static final KeyVaultDataAction UPLOAD_HSM_SECURITY_DOMAIN - = fromString("Microsoft.KeyVault/managedHsm/securitydomain/upload/action"); - - /** - * Check the status of the HSM security domain exchange file. - */ - @Generated - public static final KeyVaultDataAction READ_HSM_SECURITY_DOMAIN_STATUS - = fromString("Microsoft.KeyVault/managedHsm/securitydomain/upload/read"); - - /** - * Download an HSM security domain transfer key. - */ - @Generated - public static final KeyVaultDataAction READ_HSM_SECURITY_DOMAIN_TRANSFER_KEY - = fromString("Microsoft.KeyVault/managedHsm/securitydomain/transferkey/read"); - - /** - * Start an HSM backup. - */ - @Generated - public static final KeyVaultDataAction START_HSM_BACKUP - = fromString("Microsoft.KeyVault/managedHsm/backup/start/action"); - - /** - * Start an HSM restore. - */ - @Generated - public static final KeyVaultDataAction START_HSM_RESTORE - = fromString("Microsoft.KeyVault/managedHsm/restore/start/action"); - - /** - * Read an HSM backup status. - */ - @Generated - public static final KeyVaultDataAction READ_HSM_BACKUP_STATUS - = fromString("Microsoft.KeyVault/managedHsm/backup/status/action"); - - /** - * Read an HSM restore status. - */ - @Generated - public static final KeyVaultDataAction READ_HSM_RESTORE_STATUS - = fromString("Microsoft.KeyVault/managedHsm/restore/status/action"); - - /** - * Generate random numbers. - */ - @Generated - public static final KeyVaultDataAction RANDOM_NUMBERS_GENERATE - = fromString("Microsoft.KeyVault/managedHsm/rng/action"); - - /** - * Creates a new instance of KeyVaultDataAction value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public KeyVaultDataAction() { - } - - /** - * Creates or finds a KeyVaultDataAction from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyVaultDataAction. - */ - @Generated - public static KeyVaultDataAction fromString(String name) { - return fromString(name, KeyVaultDataAction.class); - } - - /** - * Gets known KeyVaultDataAction values. - * - * @return known KeyVaultDataAction values. - */ - @Generated - public static Collection values() { - return values(KeyVaultDataAction.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultGetSettingsResult.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultGetSettingsResult.java deleted file mode 100644 index 9f6e058ba68a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultGetSettingsResult.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -import java.util.List; - -/** - * A result model containing the {@link KeyVaultSetting settings} for a given account. - */ -@Immutable -public final class KeyVaultGetSettingsResult { - private final List settings; - - /** - * Creates an instance of {@link KeyVaultGetSettingsResult} class. - * - * @param settings The {@link KeyVaultSetting settings} for the account. - */ - public KeyVaultGetSettingsResult(List settings) { - this.settings = settings; - } - - /** - * Get the list of {@link KeyVaultSetting settings} for the account. - * - * @return The {@link KeyVaultSetting settings} for the account. - */ - public List getSettings() { - return this.settings; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultLongRunningOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultLongRunningOperation.java deleted file mode 100644 index b83d8261e2a9..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultLongRunningOperation.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -import java.time.OffsetDateTime; - -/** - * A class that contains the details of a long running operation. - */ -@Immutable -public class KeyVaultLongRunningOperation { - private final String status; - private final String statusDetails; - private final KeyVaultAdministrationError error; - private final String operationId; - private final OffsetDateTime startTime; - private final OffsetDateTime endTime; - - /** - * Creates an object containing the details of a {@link KeyVaultLongRunningOperation}. - * - * @param status Status of the {@link KeyVaultLongRunningOperation}. - * @param statusDetails The status details of the {@link KeyVaultLongRunningOperation}. - * @param operationId Identifier for the full {@link KeyVaultLongRunningOperation}. - * @param error Error encountered, if any, during the {@link KeyVaultLongRunningOperation}. - * @param startTime The start time of the {@link KeyVaultLongRunningOperation}. - * @param endTime The end time of the {@link KeyVaultLongRunningOperation}. - */ - public KeyVaultLongRunningOperation(String status, String statusDetails, KeyVaultAdministrationError error, - String operationId, OffsetDateTime startTime, OffsetDateTime endTime) { - this.status = status; - this.statusDetails = statusDetails; - this.error = error; - this.startTime = startTime; - this.endTime = endTime; - this.operationId = operationId; - } - - /** - * Get the status of the {@link KeyVaultLongRunningOperation}. - * - * @return The backup status. - */ - public String getStatus() { - return status; - } - - /** - * Get the status details of the {@link KeyVaultLongRunningOperation}. - * - * @return The backup status details. - */ - public String getStatusDetails() { - return statusDetails; - } - - /** - * Get the identifier for the {@link KeyVaultLongRunningOperation}. - * - * @return The operation ID. - */ - public String getOperationId() { - return operationId; - } - - /** - * Get the error encountered, if any, during the {@link KeyVaultLongRunningOperation}. - * - * @return The error. - */ - public KeyVaultAdministrationError getError() { - return error; - } - - /** - * Get the start time of the {@link KeyVaultLongRunningOperation}. - * - * @return The start time. - */ - public OffsetDateTime getStartTime() { - return startTime; - } - - /** - * Get the end time of the {@link KeyVaultLongRunningOperation}. - * - * @return The end time. - */ - public OffsetDateTime getEndTime() { - return endTime; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultPermission.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultPermission.java deleted file mode 100644 index 701ca621cc7c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultPermission.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -import java.util.List; - -/** - * A class describing allowed and forbidden actions and data actions of a {@link KeyVaultRoleDefinition}. - */ -@Immutable -public final class KeyVaultPermission { - private final List actions; - private final List notActions; - private final List dataActions; - private final List notDataActions; - - /** - * Creates a new {@link KeyVaultPermission} with the specified allowed and forbidden actions and data actions. - * - * @param actions Action permissions that are granted. - * @param notActions Action permissions that are excluded but not denied. They may be granted by other role - * definitions assigned to a principal. - * @param dataActions Data action permissions that are granted. - * @param notDataActions Data action permissions that are excluded but not denied. They may be granted by other role - * definitions assigned to a principal. - */ - public KeyVaultPermission(List actions, List notActions, List dataActions, - List notDataActions) { - this.actions = actions; - this.notActions = notActions; - this.dataActions = dataActions; - this.notDataActions = notDataActions; - } - - /** - * Get the action permissions that are granted. - * - * @return The action permissions that are granted. - */ - public List getActions() { - return actions; - } - - /** - * Get the action permissions that are excluded but not denied. They may be granted by other role definitions - * assigned to a principal - * - * @return The action permissions that are excluded but not denied. - */ - public List getNotActions() { - return notActions; - } - - /** - * Get the data action permissions that are granted. - * - * @return The data action permissions that are granted. - */ - public List getDataActions() { - return dataActions; - } - - /** - * Get the data action permissions that are excluded but not denied. - * - * @return The data action permissions that are excluded but not denied. - */ - public List getNotDataActions() { - return notDataActions; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRestoreOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRestoreOperation.java deleted file mode 100644 index 382c0931807b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRestoreOperation.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -import java.time.OffsetDateTime; - -/** - * A class that contains the details of a restore operation. - */ -@Immutable -public final class KeyVaultRestoreOperation extends KeyVaultLongRunningOperation { - /** - * Creates an object containing the details of a {@link KeyVaultRestoreOperation}. - * - * @param status Status of the {@link KeyVaultRestoreOperation}. - * @param statusDetails The status details of the {@link KeyVaultRestoreOperation}. - * @param error Error encountered, if any, during the {@link KeyVaultRestoreOperation}. - * @param startTime The start time of the {@link KeyVaultRestoreOperation}. - * @param endTime The end time of the {@link KeyVaultRestoreOperation}. - * @param operationId Identifier for the full {@link KeyVaultRestoreOperation}. - */ - public KeyVaultRestoreOperation(String status, String statusDetails, KeyVaultAdministrationError error, - String operationId, OffsetDateTime startTime, OffsetDateTime endTime) { - super(status, statusDetails, error, operationId, startTime, endTime); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRestoreResult.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRestoreResult.java deleted file mode 100644 index 4cad3b120fc4..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRestoreResult.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration.models; - -/** - * A class that represents the result of a Restore operation. - */ -public final class KeyVaultRestoreResult { - /** - * Creates an instance of {@link KeyVaultRestoreResult}. - */ - public KeyVaultRestoreResult() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleAssignment.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleAssignment.java deleted file mode 100644 index 787b3a86b80d..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleAssignment.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -/** - * A class that defines a role assignment. - */ -@Immutable -public final class KeyVaultRoleAssignment { - private final String id; - private final String name; - private final String type; - private final KeyVaultRoleAssignmentProperties properties; - - /** - * Creates a new {@link KeyVaultRoleAssignment role assignment} with the specified details. - * - * @param id The ID for this {@link KeyVaultRoleAssignment role assignment}. - * @param name The name of this {@link KeyVaultRoleAssignment role assignment}. - * @param type The type of this {@link KeyVaultRoleAssignment role assignment}. - * @param properties {@link KeyVaultRoleAssignmentProperties properties} of this {@link KeyVaultRoleAssignment - * role assignment}. - */ - public KeyVaultRoleAssignment(String id, String name, String type, KeyVaultRoleAssignmentProperties properties) { - this.id = id; - this.name = name; - this.type = type; - this.properties = properties; - } - - /** - * Get the {@link KeyVaultRoleAssignment role assignment} ID. - * - * @return The {@link KeyVaultRoleAssignment role assignment} ID. - */ - public String getId() { - return id; - } - - /** - * Get the {@link KeyVaultRoleAssignment role assignment} name. - * - * @return The {@link KeyVaultRoleAssignment role assignment} name. - */ - public String getName() { - return name; - } - - /** - * Get the {@link KeyVaultRoleAssignment role assignment} type. - * - * @return The {@link KeyVaultRoleAssignment role assignment} type. - */ - public String getType() { - return type; - } - - /** - * Get the {@link KeyVaultRoleAssignment role assignment} {@link KeyVaultRoleAssignmentProperties properties}. - * - * @return The {@link KeyVaultRoleAssignment role assignment} {@link KeyVaultRoleAssignmentProperties properties}. - */ - public KeyVaultRoleAssignmentProperties getProperties() { - return properties; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleAssignmentProperties.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleAssignmentProperties.java deleted file mode 100644 index 223ee401b050..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleAssignmentProperties.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -/** - * A class that defines a role assignment's properties. - */ -@Immutable -public final class KeyVaultRoleAssignmentProperties { - private final String roleDefinitionId; - private final String principalId; - private final KeyVaultRoleScope scope; - - /** - * Creates a new {@link KeyVaultRoleAssignmentProperties role assignment properties} object with the specified - * details. - * - * @param roleDefinitionId The {@link KeyVaultRoleDefinition role definition} ID used in the - * {@link KeyVaultRoleAssignment role assignment}. - * @param principalId The principal ID assigned to the role. This maps to the ID inside the Active Directory. - * It can point to a user, service principal, or security group.* - * @param scope The {@link KeyVaultRoleScope scope} of this {@link KeyVaultRoleAssignment role assignment}. - */ - public KeyVaultRoleAssignmentProperties(String roleDefinitionId, String principalId, KeyVaultRoleScope scope) { - this.roleDefinitionId = roleDefinitionId; - this.principalId = principalId; - this.scope = scope; - } - - /** - * Get the {@link KeyVaultRoleDefinition role definition} ID used in the {@link KeyVaultRoleAssignment role - * assignment}. - * - * @return The {@link KeyVaultRoleDefinition role definition} ID. - */ - public String getRoleDefinitionId() { - return roleDefinitionId; - } - - /** - * Get the principal ID assigned to the role. - * - * @return The principal ID. - */ - public String getPrincipalId() { - return principalId; - } - - /** - * Get the {@link KeyVaultRoleAssignment role assignment} {@link KeyVaultRoleScope scope}. - * - * @return The {@link KeyVaultRoleAssignment role assignment} {@link KeyVaultRoleScope scope}. - */ - public KeyVaultRoleScope getScope() { - return scope; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinition.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinition.java deleted file mode 100644 index ea4dae112b17..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinition.java +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -import java.util.List; - -/** - * A class that defines a role. - */ -@Immutable -public final class KeyVaultRoleDefinition { - private final String id; - private final String name; - private final KeyVaultRoleDefinitionType type; - private final String roleName; - private final String description; - private final KeyVaultRoleType roleType; - private final List permissions; - private final List assignableScopes; - - /** - * Creates a new {@link KeyVaultRoleDefinition role definition} with the specified details. - * - * @param id The ID for this {@link KeyVaultRoleDefinition role definition}. - * @param name The name for this {@link KeyVaultRoleDefinition role definition}. - * @param type The type of this {@link KeyVaultRoleDefinition role definition}. - * @param roleName The name of the role. - * @param description The description of this {@link KeyVaultRoleDefinition role definition}. - * @param roleType The type of the role. - * @param permissions The {@link KeyVaultPermission permissions} the {@link KeyVaultRoleDefinition role definition} - * has. - * @param assignableScopes The assignable scopes of the {@link KeyVaultRoleDefinition role definition}. - */ - public KeyVaultRoleDefinition(String id, String name, KeyVaultRoleDefinitionType type, String roleName, - String description, KeyVaultRoleType roleType, List permissions, - List assignableScopes) { - this.id = id; - this.name = name; - this.type = type; - this.roleName = roleName; - this.description = description; - this.roleType = roleType; - this.permissions = permissions; - this.assignableScopes = assignableScopes; - } - - /** - * Get the {@link KeyVaultRoleDefinition role definition} ID. - * - * @return The {@link KeyVaultRoleDefinition role definition} ID. - */ - public String getId() { - return id; - } - - /** - * Get the {@link KeyVaultRoleDefinition role definition} name. - * - * @return The {@link KeyVaultRoleDefinition role definition} name. - */ - public String getName() { - return name; - } - - /** - * Get the {@link KeyVaultRoleDefinitionType role definition type}. - * - * @return The {@link KeyVaultRoleDefinitionType role definition type}. - */ - public KeyVaultRoleDefinitionType getType() { - return type; - } - - /** - * Get the role name. - * - * @return The role name. - */ - public String getRoleName() { - return roleName; - } - - /** - * Get the role description. - * - * @return The role description. - */ - public String getDescription() { - return description; - } - - /** - * Get the role type. - * - * @return The role type. - */ - public KeyVaultRoleType getRoleType() { - return roleType; - } - - /** - * Get the {@link KeyVaultRoleDefinition role definition}'s {@link KeyVaultPermission permissions}. - * - * @return The {@link KeyVaultRoleDefinition role definition}'s {@link KeyVaultPermission permissions}. - */ - public List getPermissions() { - return permissions; - } - - /** - * Get the {@link KeyVaultRoleDefinition role definition}'s assignable scopes. - * - * @return The {@link KeyVaultRoleDefinition role definition}'s assignable scopes. - */ - public List getAssignableScopes() { - return assignableScopes; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinitionType.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinitionType.java deleted file mode 100644 index d07ae50971d6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinitionType.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The role definition type. - */ -public final class KeyVaultRoleDefinitionType extends ExpandableStringEnum { - - /** - * Microsoft-defined role definitions. - */ - @Generated - public static final KeyVaultRoleDefinitionType MICROSOFT_AUTHORIZATION_ROLE_DEFINITIONS - = fromString("Microsoft.Authorization/roleDefinitions"); - - /** - * Creates a new instance of KeyVaultRoleDefinitionType value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public KeyVaultRoleDefinitionType() { - } - - /** - * Creates or finds a KeyVaultRoleDefinitionType from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyVaultRoleDefinitionType. - */ - @Generated - public static KeyVaultRoleDefinitionType fromString(String name) { - return fromString(name, KeyVaultRoleDefinitionType.class); - } - - /** - * Gets known KeyVaultRoleDefinitionType values. - * - * @return known KeyVaultRoleDefinitionType values. - */ - @Generated - public static Collection values() { - return values(KeyVaultRoleDefinitionType.class); - } -} 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 deleted file mode 100644 index 0e9b2888b797..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleScope.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; - -/** - * The role scope. - */ -public final class KeyVaultRoleScope extends ExpandableStringEnum { - - /** - * Global scope. - */ - @Generated - public static final KeyVaultRoleScope GLOBAL = fromString("/"); - - /** - * Keys scope. - */ - @Generated - public static final KeyVaultRoleScope KEYS = fromString("/keys"); - - /** - * Creates a new instance of KeyVaultRoleScope value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public KeyVaultRoleScope() { - } - - /** - * Creates or finds a KeyVaultRoleScope from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyVaultRoleScope. - */ - @Generated - public static KeyVaultRoleScope fromString(String name) { - return fromString(name, KeyVaultRoleScope.class); - } - - /** - * Gets known KeyVaultRoleScope values. - * - * @return known KeyVaultRoleScope values. - */ - @Generated - public static Collection values() { - return values(KeyVaultRoleScope.class); - } - - /** - * /** - * Creates of finds a {@link KeyVaultRoleScope} from its string representation. - * - * @param url A string representing a URL containing the name of the scope to look for. - * @return The corresponding {@link KeyVaultRoleScope}. - * @throws IllegalArgumentException If the given {@code url} is malformed. - * / - */ - public static KeyVaultRoleScope fromUrl(String url) { - try { - return fromString(new URL(url).getPath()); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - } - - /** - * /** - * Creates of finds a {@link KeyVaultRoleScope} from its string representation. - * - * @param url A URL containing the name of the scope to look for. - * @return The corresponding {@link KeyVaultRoleScope}. - * / - */ - public static KeyVaultRoleScope fromUrl(URL url) { - return fromString(url.getPath()); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleType.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleType.java deleted file mode 100644 index 5ee5f40965f4..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleType.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The role type. - */ -public final class KeyVaultRoleType extends ExpandableStringEnum { - - /** - * Built in role. - */ - @Generated - public static final KeyVaultRoleType BUILT_IN_ROLE = fromString("AKVBuiltInRole"); - - /** - * Custom role. - */ - @Generated - public static final KeyVaultRoleType CUSTOM_ROLE = fromString("CustomRole"); - - /** - * Creates a new instance of KeyVaultRoleType value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public KeyVaultRoleType() { - } - - /** - * Creates or finds a KeyVaultRoleType from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyVaultRoleType. - */ - @Generated - public static KeyVaultRoleType fromString(String name) { - return fromString(name, KeyVaultRoleType.class); - } - - /** - * Gets known KeyVaultRoleType values. - * - * @return known KeyVaultRoleType values. - */ - @Generated - public static Collection values() { - return values(KeyVaultRoleType.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSelectiveKeyRestoreOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSelectiveKeyRestoreOperation.java deleted file mode 100644 index aa0ddd9b3192..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSelectiveKeyRestoreOperation.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; - -import java.time.OffsetDateTime; - -/** - * A class that contains the details of a selective key restore operation. - */ -@Immutable -public final class KeyVaultSelectiveKeyRestoreOperation extends KeyVaultLongRunningOperation { - /** - * Creates an object containing the details of a {@link KeyVaultSelectiveKeyRestoreOperation}. - * - * @param status Status of the {@link KeyVaultSelectiveKeyRestoreOperation}. - * @param statusDetails The status details of the {@link KeyVaultSelectiveKeyRestoreOperation}. - * @param error Error encountered, if any, during the {@link KeyVaultSelectiveKeyRestoreOperation}. - * @param startTime The start time of the {@link KeyVaultSelectiveKeyRestoreOperation}. - * @param endTime The end time of the {@link KeyVaultSelectiveKeyRestoreOperation}. - * @param operationId Identifier for the full {@link KeyVaultSelectiveKeyRestoreOperation}. - */ - public KeyVaultSelectiveKeyRestoreOperation(String status, String statusDetails, KeyVaultAdministrationError error, - String operationId, OffsetDateTime startTime, OffsetDateTime endTime) { - super(status, statusDetails, error, operationId, startTime, endTime); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSelectiveKeyRestoreResult.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSelectiveKeyRestoreResult.java deleted file mode 100644 index 8731a52bb84a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSelectiveKeyRestoreResult.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration.models; - -/** - * A class that represents the result of a SelectiveKeyRestore operation. - */ -public final class KeyVaultSelectiveKeyRestoreResult { - /** - * Creates an instance of {@link KeyVaultSelectiveKeyRestoreResult}. - */ - public KeyVaultSelectiveKeyRestoreResult() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSetting.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSetting.java deleted file mode 100644 index 1a24893c9511..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSetting.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; - -/** - * The {@link KeyVaultSetting} model. - */ -@Immutable -public final class KeyVaultSetting { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultSetting.class); - - private final String name; - private final Object value; - private final KeyVaultSettingType type; - - /** - * Creates a new {@link KeyVaultSetting setting} with the with the specified details. - * - * @param name The name of the {@link KeyVaultSetting setting}. - * @param value The value of the {@link KeyVaultSetting setting}. - */ - public KeyVaultSetting(String name, boolean value) { - if (CoreUtils.isNullOrEmpty(name)) { - throw LOGGER - .logExceptionAsError(new IllegalArgumentException("The 'name' parameter cannot be null or empty")); - } - - this.name = name; - this.value = value; - this.type = KeyVaultSettingType.BOOLEAN; - } - - /** - * Gets the name of the {@link KeyVaultSetting}. - * - * @return The name of the {@link KeyVaultSetting}. - */ - public String getName() { - return this.name; - } - - /** - * Get the value of the {@link KeyVaultSetting} as a {@code boolean}. - * - * @return The value of the {@link KeyVaultSetting} as a {@code boolean}. - */ - public boolean asBoolean() { - if (type != KeyVaultSettingType.BOOLEAN) { - throw LOGGER.logExceptionAsError(new UnsupportedOperationException( - String.format("Cannot get setting value as %s from setting value of " + "type %s", - KeyVaultSettingType.BOOLEAN, this.getType()))); - } - - return (Boolean) this.value; - } - - /** - * Get the type of the {@link KeyVaultSetting}'s value. - * - * @return The type of the {@link KeyVaultSetting}'s value. - */ - public KeyVaultSettingType getType() { - return this.type; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSettingType.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSettingType.java deleted file mode 100644 index 3ac0c0742a61..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSettingType.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The type specifier of the value. - */ -public final class KeyVaultSettingType extends ExpandableStringEnum { - - /** - * A boolean setting value. - */ - @Generated - public static final KeyVaultSettingType BOOLEAN = fromString("boolean"); - - /** - * Creates a new instance of KeyVaultSettingType value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public KeyVaultSettingType() { - } - - /** - * Creates or finds a KeyVaultSettingType from its string representation. - * - * @param name a name to look for. - * @return the corresponding KeyVaultSettingType. - */ - @Generated - public static KeyVaultSettingType fromString(String name) { - return fromString(name, KeyVaultSettingType.class); - } - - /** - * Gets known KeyVaultSettingType values. - * - * @return known KeyVaultSettingType values. - */ - @Generated - public static Collection values() { - return values(KeyVaultSettingType.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/SetRoleDefinitionOptions.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/SetRoleDefinitionOptions.java deleted file mode 100644 index 015c38929bad..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/SetRoleDefinitionOptions.java +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.models; - -import com.azure.core.annotation.Fluent; - -import java.util.List; -import java.util.UUID; - -/** - * Represents the configurable options to create or update a {@link KeyVaultRoleDefinition role definition}. - */ -@Fluent -public final class SetRoleDefinitionOptions { - private final KeyVaultRoleScope roleScope; - private final String roleDefinitionName; - private String roleName; - private String description; - private List permissions; - private List assignableScopes; - - /** - * Creates an instance of {@link SetRoleDefinitionOptions} with an automatically generated name. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition} to create. - * Managed HSM only supports '/'. - */ - public SetRoleDefinitionOptions(KeyVaultRoleScope roleScope) { - this(roleScope, UUID.randomUUID().toString()); - } - - /** - * Creates an instance of {@link SetRoleDefinitionOptions}. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition} to create. - * Managed HSM only supports '/'. - * @param roleDefinitionName The name of the {@link KeyVaultRoleDefinition}. It can be any valid UUID. - */ - public SetRoleDefinitionOptions(KeyVaultRoleScope roleScope, String roleDefinitionName) { - this.roleScope = roleScope; - this.roleDefinitionName = roleDefinitionName; - } - - /** - * Get the {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition} to create or update. - * - * @return The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition}. - */ - public KeyVaultRoleScope getRoleScope() { - return roleScope; - } - - /** - * Get the name of the {@link KeyVaultRoleDefinition} to create or update. - * - * @return The name of the {@link KeyVaultRoleDefinition}. - */ - public String getRoleDefinitionName() { - return roleDefinitionName; - } - - /** - * Get the role name. - * - * @return The role name. - */ - public String getRoleName() { - return roleName; - } - - /** - * Set the role name. - * - * @param roleName The role name to set. - * - * @return The updated {@link SetRoleDefinitionOptions} object. - */ - public SetRoleDefinitionOptions setRoleName(String roleName) { - this.roleName = roleName; - - return this; - } - - /** - * Get the role description. - * - * @return The role description. - */ - public String getDescription() { - return description; - } - - /** - * Set the role description. - * - * @param description The role description to set. - * - * @return The updated {@link SetRoleDefinitionOptions} object. - */ - public SetRoleDefinitionOptions setDescription(String description) { - this.description = description; - - return this; - } - - /** - * Get the {@link KeyVaultRoleDefinition role definition}'s {@link KeyVaultPermission permissions}. - * - * @return The {@link KeyVaultRoleDefinition role definition}'s {@link KeyVaultPermission permissions}. - */ - public List getPermissions() { - return permissions; - } - - /** - * Set the {@link KeyVaultRoleDefinition role definition}'s {@link KeyVaultPermission permissions}. - * - * @param permissions The {@link KeyVaultRoleDefinition role definition}'s {@link KeyVaultPermission permissions} - * to set. - * - * @return The updated {@link SetRoleDefinitionOptions} object. - */ - public SetRoleDefinitionOptions setPermissions(List permissions) { - this.permissions = permissions; - - return this; - } - - /** - * Get the {@link KeyVaultRoleDefinition role definition}'s assignable scopes. - * - * @return The {@link KeyVaultRoleDefinition role definition}'s assignable scopes. - */ - public List getAssignableScopes() { - return assignableScopes; - } - - /** - * Set the {@link KeyVaultRoleDefinition role definition}'s assignable scopes. - * - * @param assignableScopes The {@link KeyVaultRoleDefinition role definition}'s assignable scopes to set. - * - * @return The updated {@link SetRoleDefinitionOptions} object. - */ - public SetRoleDefinitionOptions setAssignableScopes(List assignableScopes) { - this.assignableScopes = assignableScopes; - - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/package-info.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/package-info.java deleted file mode 100644 index 3fc4d90fe609..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/package-info.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. -/** - * Package containing classes used by {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} and {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClient} to perform access control operations on Azure - * Key Vault resources, as well as classes used by {@link - * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient} and {@link - * com.azure.security.keyvault.administration.KeyVaultBackupClient} to perform backup and restore operations on Azure - * Key Vault keys. - */ -package com.azure.security.keyvault.administration.models; diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/package-info.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/package-info.java deleted file mode 100644 index 15a757e7787a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/package-info.java +++ /dev/null @@ -1,619 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * - * Azure Key Vault Managed HSM is a - * fully-managed, highly-available, single-tenant, standards-compliant cloud service that enables you to safeguard - * cryptographic keys for your cloud applications using FIPS 140-2 Level 3 validated HSMs. - * - *

- * The Azure Key Vault Administration client library allows developers to interact with the Azure Key Vault Managed - * HSM service from their applications. The library provides a set of APIs that enable developers to perform - * administrative tasks such as full backup/restore, key-level role-based access control (RBAC), and account settings - * management. - * - *

- * Key Concepts: - * - *

- * What is a Key Vault Access Control Client? - *

- * The Key Vault Access Control client performs the interactions with the Azure Key Vault service for getting, - * setting, deleting, and listing role assignments, as well as listing role definitions. Asynchronous - * (KeyVaultAccessControlAsyncClient) and synchronous (KeyVaultAccessControlClient) clients exist in the SDK allowing - * for the selection of a client based on an application's use case. Once you've initialized a role assignment, you can - * interact with the primary resource types in Key Vault. - * - *

- * What is a Role Definition? - *

- * A role definition is a collection of permissions. It defines the operations that can be performed, such as read, - * write, and delete. It can also define the operations that are excluded from allowed operations. - * - *

- * Role definitions can be listed and specified as part of a role assignment. - * - *

- * What is a Role Assignment? - *

- * A role assignment is the association of a role definition to a service principal. They can be created, listed, - * fetched individually, and deleted. - * - *

- * What is a Key Vault Backup Client - *

- * The Key Vault Backup Client provides both synchronous and asynchronous operations for performing full key backups, - * full key restores, and selective key restores. Asynchronous (KeyVaultBackupAsyncClient) and synchronous - * (KeyVaultBackupClient) clients exist in the SDK allowing for the selection of a client based on an application's use - * case. - * - *

- * 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. Alternatively, it is possible to - * generate a SAS token in Storage Explorer. - * - *

- * What is a Backup Operation? - *

- * A backup operation represents a long-running operation for a full key backup. - * - *

- * What is a Restore Operation - *

- * A restore operation represents a long-running operation for both a full key and selective key restore. - * - *

- * What is a Key Vault Settings Client? - *

- * The Key Vault Settings client allows manipulation of an Azure Key Vault account's settings, with operations - * such as: getting, updating, and listing. Asynchronous (KeyVaultSettingsAsyncClient) and synchronous - * (KeyVaultSettingsClient) clients exist in the SDK allowing for the selection of a client based on an application's - * use case. - * - *

Getting Started

- * - * In order to interact with the Azure Key Vault service, you will need to create an instance of the {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} class, a vault url and a credential - * object. - * - *

- * The examples shown in this document use a credential object named DefaultAzureCredential for authentication, which - * is appropriate for most scenarios, including local development and production environments. Additionally, we - * recommend using a - * managed identity for authentication in production environments. You can find more information on different ways - * of authenticating and their corresponding credential types in the Azure Identity - * documentation". - * - *

- * Sample: Construct Synchronous Access Control Client - * - *

- * The following code sample demonstrates the creation of a {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClient}, using the {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder} to configure it. - * - *

- * KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildClient();
- * 
- * - * - *

- * Sample: Construct Asynchronous Access Control Client - * - *

- * The following code sample demonstrates the creation of a {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}, using the {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder} to configure it. - * - *

- * KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder()
- *     .vaultUrl("<your-managed-hsm-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .buildAsyncClient();
- * 
- * - *
- *
- * - *

Set a Role Definition

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to set a role - * definition in the key vault. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to asynchronously create a role definition in the key vault, using the - * {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClient#setRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, - * java.lang.String) KeyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope, String)} API. - * - * - *

- * 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());
- * 
- * - * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.
- *


- * - *

Get a Role Definition

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to retrieve a role - * definition from the key vault. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using - * the {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClient#getRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, - * java.lang.String) KeyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope, String)} API. - * - * - *

- * 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());
- * 
- * - * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.
- *


- * - *

Delete a Role Definition

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to delete a role - * definition from the key vault. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using - * the {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClient#deleteRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, - * java.lang.String) KeyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope, String)} API. - * - * - *

- * String roleDefinitionName = "6a709e6e-8964-4012-a99b-6b0131e8ce40";
- *
- * keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);
- *
- * System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName);
- * 
- * - * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.
- *


- * - *

Create a Role Assignment

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to set a role - * assignment in the key vault. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to asynchronously create a role assignment in the key vault, using the - * {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClient#createRoleAssignment(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, - * java.lang.String, java.lang.String) KeyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope, String, - * String)} API. - * - * - *

- * 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());
- * 
- * - * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.
- *


- * - *

Get a Role Definition

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to retrieve a role - * definition from the key vault. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using - * the {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClient#getRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, - * java.lang.String) KeyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope, String)} API. - * - * - *

- * 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());
- * 
- * - * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.
- *


- * - *

Delete a Role Definition

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to delete a role - * definition from an Azure Key Vault account. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using - * the {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlClient#deleteRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, - * java.lang.String) KeyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope, String)} API. - * - * - *

- * String roleAssignmentName = "c3ed874a-64a9-4a87-8581-2a1ad84b9ddb";
- *
- * keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);
- *
- * System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName);
- * 
- * - * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.
- *


- * - *

Run Pre-Backup Check for a Collection of Keys

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to check if it is possible to - * back up the entire collection of keys from a key vault. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to synchronously check if it is possible to back up an entire collection - * of keys, using the - * {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginPreBackup(String, String)} API. - * - *

- * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
- * String sasToken = "<sas-token>";
- *
- * SyncPoller<KeyVaultBackupOperation, String> preBackupPoller = client.beginPreBackup(blobStorageUrl, sasToken);
- * PollResponse<KeyVaultBackupOperation> pollResponse = preBackupPoller.poll();
- *
- * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
- *
- * PollResponse<KeyVaultBackupOperation> finalPollResponse = preBackupPoller.waitForCompletion();
- *
- * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
- *     System.out.printf("Pre-backup check completed successfully.%n");
- * } else {
- *     KeyVaultBackupOperation operation = preBackupPoller.poll().getValue();
- *
- *     System.out.printf("Pre-backup check failed with error: %s.%n", operation.getError().getMessage());
- * }
- * 
- * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.
- *


- * - *

Back Up a Collection of Keys

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to back up the entire - * collection of keys from a key vault. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the - * {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginBackup(String, String)} API. - * - *

- * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
- * String sasToken = "<sas-token>";
- *
- * 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());
- * }
- * 
- * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.
- *


- * - *

Run Pre-Restore Check for a Collection of Keys

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to check if it is possible to - * restore an entire collection of keys from a backup. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to synchronously check if it is possible to restore an entire collection - * of keys from a backup, using the - * {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginPreRestore(String, String)} API. - * - *

- * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
- * String sasToken = "<sas-token>";
- *
- * SyncPoller<KeyVaultRestoreOperation, KeyVaultRestoreResult> preRestorePoller =
- *     client.beginPreRestore(folderUrl, sasToken);
- * PollResponse<KeyVaultRestoreOperation> pollResponse = preRestorePoller.poll();
- *
- * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
- *
- * PollResponse<KeyVaultRestoreOperation> finalPollResponse = preRestorePoller.waitForCompletion();
- *
- * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
- *     System.out.printf("Pre-restore check completed successfully.%n");
- * } else {
- *     KeyVaultRestoreOperation operation = preRestorePoller.poll().getValue();
- *
- *     System.out.printf("Pre-restore check failed with error: %s.%n", operation.getError().getMessage());
- * }
- * 
- * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.
- *


- * - *

Restore a Collection of Keys

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to restore an entire - * collection of keys from a backup. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup, - * using the {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginRestore(String, String)} API. - * - *

- * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
- * String sasToken = "<sas-token>";
- *
- * SyncPoller<KeyVaultRestoreOperation, KeyVaultRestoreResult> restorePoller =
- *     client.beginRestore(folderUrl, sasToken);
- * PollResponse<KeyVaultRestoreOperation> pollResponse = restorePoller.poll();
- *
- * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
- *
- * PollResponse<KeyVaultRestoreOperation> finalPollResponse = restorePoller.waitForCompletion();
- *
- * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
- *     System.out.printf("Backup restored successfully.%n");
- * } else {
- *     KeyVaultRestoreOperation operation = restorePoller.poll().getValue();
- *
- *     System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage());
- * }
- * 
- * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.
- *


- * - *

Selectively Restore a Key

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to restore a specific key - * from a backup. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to synchronously restore a specific key from a backup, using the {@link - * com.azure.security.keyvault.administration.KeyVaultBackupClient#beginSelectiveKeyRestore(String, String, String)} - * API. - * - * - *

- * 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());
- * }
- * 
- * - * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.
- *


- * - *

Get All Settings

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to list all the settings - * for an Azure Key Vault account. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the - * {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#getSettings()} API. - * - *

- * KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings();
- * List<KeyVaultSetting> settings = getSettingsResult.getSettings();
- *
- * settings.forEach(setting ->
- *     System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),
- *         setting.asBoolean()));
- * 
- * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.
- *


- * - *

Retrieve a Specific Setting

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to retrieve a specific - * setting. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup, - * using the {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#getSetting(String)} API. - * - *

- * KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName);
- *
- * System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean());
- * 
- * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.
- *


- * - *

Update a Specific Setting

- * - * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to restore a specific key - * from a backup. - * - *

- * Code Sample: - * - *

- * The following code sample demonstrates how to synchronously restore a specific key from a backup, using the {@link - * com.azure.security.keyvault.administration.KeyVaultSettingsClient#updateSetting(com.azure.security.keyvault.administration.models.KeyVaultSetting) - * KeyVaultSettingsClient.updateSetting(KeyVaultSetting)} - * - *

- * KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);
- * KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate);
- *
- * System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean());
- * 
- * - * - *

- * Note: For the asynchronous sample, refer to {@link - * com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.
- *


- * - * @see com.azure.security.keyvault.administration.KeyVaultAccessControlClient - * @see com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient - * @see com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder - * @see com.azure.security.keyvault.administration.KeyVaultBackupClient - * @see com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient - * @see com.azure.security.keyvault.administration.KeyVaultBackupClientBuilder - * @see com.azure.security.keyvault.administration.KeyVaultSettingsClient - * @see com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient - * @see com.azure.security.keyvault.administration.KeyVaultSettingsClientBuilder - */ -package com.azure.security.keyvault.administration; diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/module-info.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/module-info.java deleted file mode 100644 index dd114f04e740..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/module-info.java +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -module com.azure.security.keyvault.administration { - requires transitive com.azure.core; - requires transitive com.azure.json; - - exports com.azure.security.keyvault.administration; - exports com.azure.security.keyvault.administration.models; - - opens com.azure.security.keyvault.administration.models to com.azure.core; - opens com.azure.security.keyvault.administration.implementation.models to com.azure.core; - opens com.azure.security.keyvault.administration to com.azure.core; - opens com.azure.security.keyvault.administration.implementation to com.azure.core; -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/resources/azure-security-keyvault-administration.properties b/sdk/keyvault/azure-security-keyvault-administration/src/main/resources/azure-security-keyvault-administration.properties deleted file mode 100644 index ca812989b4f2..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/resources/azure-security-keyvault-administration.properties +++ /dev/null @@ -1,2 +0,0 @@ -name=${project.artifactId} -version=${project.version} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/README.md b/sdk/keyvault/azure-security-keyvault-administration/src/samples/README.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/AccessControlHelloWorld.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/AccessControlHelloWorld.java deleted file mode 100644 index c2d4218b541f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/AccessControlHelloWorld.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; - -import java.util.ArrayList; -import java.util.List; - -/** - * This sample demonstrates how to create, get, list and delete role assignments synchronously in the key vault. - */ -public class AccessControlHelloWorld { - /** - * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when an invalid key vault URL is passed. - */ - public static void main(String[] args) { - /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is - using default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) - for links and instructions. */ - KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - /* In order to assign a role to a service principal, we'll have to know which role definitions are available. - Let's get all of them. */ - List roleDefinitions = new ArrayList<>(); - - for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { - roleDefinitions.add(roleDefinition); - System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); - } - - // Before assigning any new roles, let's list all the current role assignments. - for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { - System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); - } - - /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service - principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions - returned from listRoleAssignments(). - - See the README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md#authenticate-the-client) - 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: - az ad signed-in-user show --query objectId */ - String servicePrincipalId = ""; - KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); - KeyVaultRoleAssignment createdRoleAssignment = - accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), - servicePrincipalId); - - System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); - - /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the - createdAssignment from the previous example. */ - KeyVaultRoleAssignment retrievedRoleAssignment = - accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); - - System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); - - /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the - createdAssignment from the previous example. */ - accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); - - System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); - } -} - diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/AccessControlHelloWorldAsync.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/AccessControlHelloWorldAsync.java deleted file mode 100644 index 627531c66b97..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/AccessControlHelloWorldAsync.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; - -import java.util.ArrayList; -import java.util.List; - -/** - * This sample demonstrates how to create, get, list and delete role assignments asynchronously in the Key Vault. - */ -public class AccessControlHelloWorldAsync { - /** - * Authenticates with the key vault and shows how to create, get, list and delete role assignments asynchronously. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when an invalid key vault URL is passed. - */ - public static void main(String[] args) throws InterruptedException { - /* Instantiate a KeyVaultAccessControlAsyncClient that will be used to call the service. Notice that the client - is using default Azure credentials. For more information on this and other types of credentials, see this - document: https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) - for links and instructions. */ - KeyVaultAccessControlAsyncClient accessControlAsyncClient = new KeyVaultAccessControlClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - /* In order to assign a role to a service principal, we'll have to know which role definitions are available. - Let's get all of them. */ - List roleDefinitions = new ArrayList<>(); - - accessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL) - .doOnNext((roleDefinition) -> { - roleDefinitions.add(roleDefinition); - System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); - }) - .blockLast(); - - // Before assigning any new roles, let's get all the current role assignments. - accessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL) - .doOnNext((roleAssignment -> - System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()))) - .blockLast(); - - /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service - principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions - returned from listRoleAssignments(). - - See the README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md#authenticate-the-client) - 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: - az ad signed-in-user show --query objectId */ - String servicePrincipalId = ""; - KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); - KeyVaultRoleAssignment createdRoleAssignment = - accessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), - servicePrincipalId).block(); - - /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the - createdAssignment from the previous example. */ - assert createdRoleAssignment != null; - - accessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()) - .doOnSuccess((retrievedRoleAssignment) -> - System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName())) - .block(); - - /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the - createdAssignment from the previous example. */ - accessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()) - .doOnSuccess((deletedRoleAssignment) -> - System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName())) - .block(); - - /* NOTE: block() and blockLast() will block until the above operations are completed. This is strongly - discouraged for use in production as it eliminates the benefits of asynchronous IO. It is used here to ensure - the sample runs to completion. */ - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/BackupAndRestoreHelloWorld.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/BackupAndRestoreHelloWorld.java deleted file mode 100644 index 631ce6e49752..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/BackupAndRestoreHelloWorld.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.util.polling.SyncPoller; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; - -/** - * This sample demonstrates how to fully backup and restore a key vault synchronously. - */ -public class BackupAndRestoreHelloWorld { - /** - * Authenticates with the key vault and shows how to fully backup and restore a key vault synchronously. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when an invalid key vault URL is passed. - */ - public static void main(String[] args) { - KeyVaultBackupClient backupClient = new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - /* Instantiate a KeyVaultBackupClient that will be used to call the service. Notice that the client is using - default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) - for links and instructions. */ - - /* Using the KeyVaultBackupClient, you can back up your entire collection of keys. The backing store for full - 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 (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-blob/README.md). - Alternatively, it is possible to generate a SAS token in Storage Explorer (https://docs.microsoft.com/azure/vs-azure-tools-storage-manage-with-storage-explorer?tabs=windows#generate-a-shared-access-signature-in-storage-explorer). - - To ensure you have some keys for backup, you may want to first create a key using the KeyClient. To create a - new KeyClient to create a key, see the 'Azure Key Vault Key client library for Java' README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md#create-key-client). - - In the sample below, you can set blobStorageUrl and sasToken based on environment variables, configuration - settings, or any way that works for your application. */ - String blobStorageUrl = ""; - String sasToken = ""; - SyncPoller backupPoller = backupClient.beginBackup(blobStorageUrl, sasToken); - - backupPoller.waitForCompletion(); - - /* Now let's restore the entire collection of keys from the backup. We will need the get the URI for the - location the backup, as well as Shared Access Signature for accessing it. */ - String backupFolderUrl = backupPoller.getFinalResult(); - - SyncPoller restorePoller = - backupClient.beginRestore(backupFolderUrl, sasToken); - - restorePoller.waitForCompletion(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/BackupAndRestoreHelloWorldAsync.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/BackupAndRestoreHelloWorldAsync.java deleted file mode 100644 index 6a790aede4fb..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/BackupAndRestoreHelloWorldAsync.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.util.polling.AsyncPollResponse; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; - -/** - * This sample demonstrates how to fully backup and restore a key vault synchronously. - */ -public class BackupAndRestoreHelloWorldAsync { - /** - * Authenticates with the key vault and shows how to fully backup and restore a key vault synchronously. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when an invalid key vault URL is passed. - */ - public static void main(String[] args) { - /* Instantiate a KeyVaultBackupAsyncClient that will be used to call the service. Notice that the client is - using default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) - for links and instructions. */ - KeyVaultBackupAsyncClient backupAsyncClient = new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - /* Using the KeyVaultBackupClient, you can back up your entire collection of keys. The backing store for full - 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 (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-blob/README.md). - Alternatively, it is possible to generate a SAS token in Storage Explorer (https://docs.microsoft.com/azure/vs-azure-tools-storage-manage-with-storage-explorer?tabs=windows#generate-a-shared-access-signature-in-storage-explorer). - - To ensure you have some keys for backup, you may want to first create a key using the KeyClient. To create a - new KeyClient to create a key, see the 'Azure Key Vault Key client library for Java' README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md#create-key-client). - - In the sample below, you can set blobStorageUrl and sasToken based on environment variables, configuration - settings, or any way that works for your application. */ - String blobStorageUrl = ""; - String sasToken = ""; - - AsyncPollResponse backupPollResponse = - backupAsyncClient.beginBackup(blobStorageUrl, sasToken).blockLast(); - - /* Now let's restore the entire collection of keys from the backup. We will need the get the URI for the - location the backup, as well as Shared Access Signature for accessing it. */ - String backupFolderUrl = backupPollResponse.getValue().getAzureStorageBlobContainerUrl(); - - backupAsyncClient.beginRestore(backupFolderUrl, sasToken).blockLast(); - - /* NOTE: blockLast() will block until all the above operations are completed. This is strongly discouraged for - use in production as it eliminates the benefits of asynchronous IO. It is used here to ensure the sample runs to - completion. */ - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/CreateRoleAssignmentsForDifferentScopes.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/CreateRoleAssignmentsForDifferentScopes.java deleted file mode 100644 index 649f4719be48..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/CreateRoleAssignmentsForDifferentScopes.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; - -/** - * This sample demonstrates how to create role assignments in the key vault for different scopes. - */ -public class CreateRoleAssignmentsForDifferentScopes { - /** - * Authenticates with the key vault and shows how to create role assignments in the key vault for different scopes - * synchronously. For examples of how to perform async operations, please refer to - * {@link AccessControlHelloWorldAsync the async client samples}. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when an invalid key vault URL is passed. - */ - public static void main(String[] args) { - /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is - using default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) - for links and instructions. */ - KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - /* By default role assignments apply to the global scope. It is also possible to be more specific by applying an - assignment to the all keys scope or a specific KeyVaultKey. - - Let's assign a role to a service principal so that it applies to all keys. To do this we'll need a service - principal object ID and a role definition ID. A role definition ID can be obtained from the 'id' property of one - of the role definitions returned from listRoleDefinitions(). Alternatively, you can use the following Azure CLI - command: az keyvault role definition list --hsm-name */ - String roleDefinitionId = ""; - String servicePrincipalId = ""; - - KeyVaultRoleAssignment roleAssignmentForAllKeys = - accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, servicePrincipalId); - - System.out.printf("Created role assignment with name: %s %n", roleAssignmentForAllKeys.getName()); - - /* Now let's assign a role to a service principal so that it applies to a specific KeyVaultKey. To do this we'll - use the role definition ID and a service principal object ID from the previous sample. We'll also need the ID of - an existing KeyVaultKey, which can be obtained from the service using a KeyClient. */ - String keyId = ""; - - KeyVaultRoleAssignment roleAssignmentForSingleKey = - accessControlClient.createRoleAssignment(KeyVaultRoleScope.fromString(keyId), roleDefinitionId, - servicePrincipalId); - - System.out.printf("Created role assignment with name: %s %n", roleAssignmentForSingleKey.getName()); - } -} 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 deleted file mode 100644 index f7d0108edc7a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/ReadmeSamples.java +++ /dev/null @@ -1,620 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -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; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; -import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; - -import java.time.Duration; - -/** - * 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 = - new KeyVaultAccessControlClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - private final KeyVaultBackupClient keyVaultBackupClient = - new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - private final KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = - new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - private final KeyVaultSettingsClient keyVaultSettingsClient = - new KeyVaultSettingsClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - private final KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = - new KeyVaultSettingsClientBuilder() - .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 = - 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()); - // 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 = ""; - - 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())); - // 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 pre-backup check}. - */ - public void beginPreBackup() { - // BEGIN: readme-sample-beginPreBackup - String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; - String sasToken = ""; - - SyncPoller preBackupPoller = - keyVaultBackupClient.beginPreBackup(blobStorageUrl, sasToken); - PollResponse pollResponse = preBackupPoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse finalPollResponse = preBackupPoller.waitForCompletion(); - - if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - String folderUrl = preBackupPoller.getFinalResult(); - - System.out.printf("Pre-backup check completed successfully.%n"); - } else { - KeyVaultBackupOperation operation = preBackupPoller.poll().getValue(); - - System.out.printf("Pre-backup check failed with error: %s.%n", operation.getError().getMessage()); - } - // END: readme-sample-beginPreBackup - } - - /** - * 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 = ""; - - SyncPoller backupPoller = - keyVaultBackupClient.beginBackup(blobStorageUrl, sasToken); - PollResponse pollResponse = backupPoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse 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()); - } - // END: readme-sample-beginBackup - } - - /** - * Code sample for starting a {@link KeyVaultRestoreOperation pre-restore check}. - */ - public void beginPreRestore() { - // BEGIN: readme-sample-beginPreRestore - String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; - String sasToken = ""; - - SyncPoller preRestorePoller = - keyVaultBackupClient.beginPreRestore(folderUrl, sasToken); - PollResponse pollResponse = preRestorePoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse finalPollResponse = preRestorePoller.waitForCompletion(); - - if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Pre-restore check completed successfully.%n"); - } else { - KeyVaultRestoreOperation operation = preRestorePoller.poll().getValue(); - - System.out.printf("Pre-restore check failed with error: %s.%n", operation.getError().getMessage()); - } - // END: readme-sample-beginPreRestore - } - - /** - * 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 = ""; - - SyncPoller restorePoller = - keyVaultBackupClient.beginRestore(folderUrl, sasToken); - PollResponse pollResponse = restorePoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse finalPollResponse = restorePoller.waitForCompletion(); - - if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Backup restored successfully.%n"); - } else { - KeyVaultRestoreOperation operation = restorePoller.poll().getValue(); - - 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 = ""; - String keyName = "myKey"; - - SyncPoller restorePoller = - keyVaultBackupClient.beginSelectiveKeyRestore(folderUrl, sasToken, keyName); - PollResponse pollResponse = restorePoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse finalPollResponse = restorePoller.waitForCompletion(); - - if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Key restored successfully.%n"); - } else { - KeyVaultSelectiveKeyRestoreOperation operation = restorePoller.poll().getValue(); - - System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage()); - } - // END: readme-sample-beginSelectiveKeyRestore - } - - /** - * Code sample for starting a {@link KeyVaultBackupOperation pre-backup check} asynchronously. - */ - public void beginPreBackupAsync() { - // BEGIN: readme-sample-beginPreBackupAsync - String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; - String sasToken = ""; - - keyVaultBackupAsyncClient.beginPreBackup(blobStorageUrl, sasToken) - .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. - .doOnError(e -> System.out.printf("Pre-backup check 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("Pre-backup check completed successfully.%n")); - // END: readme-sample-beginPreBackupAsync - } - - /** - * 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 = ""; - - keyVaultBackupAsyncClient.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)); - // END: readme-sample-beginBackupAsync - } - - /** - * Code sample for starting a {@link KeyVaultRestoreOperation pre-restore check} asynchronously. - */ - public void beginPreRestoreAsync() { - // BEGIN: readme-sample-beginPreRestoreAsync - String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; - String sasToken = ""; - - keyVaultBackupAsyncClient.beginPreRestore(folderUrl, sasToken) - .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. - .doOnError(e -> System.out.printf("Pre-restore check 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("Pre-restore check completed successfully.%n")); - // END: readme-sample-beginPreRestoreAsync - } - - /** - * 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 = ""; - - keyVaultBackupAsyncClient.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")); - // END: readme-sample-beginRestoreAsync - } - - /** - * Code sample for starting a {@link KeyVaultSelectiveKeyRestoreOperation selective key restore operation} - * asynchronously. - */ - public void beginSelectiveKeyRestoreAsync() { - // BEGIN: readme-sample-beginSelectiveKeyRestoreAsync - String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; - String sasToken = ""; - String keyName = "myKey"; - - keyVaultBackupAsyncClient.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")); - // 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 - } - - /** - * Code sample for updating a {@link KeyVaultSetting setting}. - */ - public void updateSetting() { - // BEGIN: readme-sample-updateSetting - String settingName = ""; - KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); - KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate); - - System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean()); - // END: readme-sample-updateSetting - } - - /** - * Code sample for retrieving a {@link KeyVaultSetting setting}. - */ - public void getSetting() { - // BEGIN: readme-sample-getSetting - String settingName = ""; - KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName); - - System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), - setting.asBoolean()); - // END: readme-sample-getSetting - } - - /** - * Code sample for retrieving an account's {@link KeyVaultSetting settings}. - */ - public void getSettings() { - // BEGIN: readme-sample-getSettings - KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings(); - - for (KeyVaultSetting setting : getSettingsResult.getSettings()) { - System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean()); - } - // END: readme-sample-getSettings - } - - /** - * Code sample for updating a {@link KeyVaultSetting setting} asynchronously. - */ - public void updateSettingAsync() { - // BEGIN: readme-sample-updateSettingAsync - String settingName = ""; - KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); - - keyVaultSettingsAsyncClient.updateSetting(settingToUpdate) - .subscribe(updatedSetting -> - System.out.printf("Updated setting with name '%s' and value '%s'.%n", updatedSetting.getName(), - updatedSetting.asBoolean())); - // END: readme-sample-updateSettingAsync - } - - /** - * Code sample for retrieving a {@link KeyVaultSetting setting} asynchronously. - */ - public void getSettingAsync() { - // BEGIN: readme-sample-getSettingAsync - String settingName = ""; - - keyVaultSettingsAsyncClient.getSetting(settingName) - .subscribe(setting -> - System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), - setting.asBoolean())); - // END: readme-sample-getSettingAsync - } - - /** - * Code sample for retrieving an account's {@link KeyVaultSetting settings} asynchronously. - */ - public void getSettingsAsync() { - // BEGIN: readme-sample-getSettingsAsync - keyVaultSettingsAsyncClient.getSettings() - .subscribe(settingsResult -> - settingsResult.getSettings().forEach(setting -> - System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), - setting.asBoolean()))); - // END: readme-sample-getSettingsAsync - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/SelectiveKeyRestore.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/SelectiveKeyRestore.java deleted file mode 100644 index dc475d132179..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/SelectiveKeyRestore.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.util.polling.SyncPoller; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; - -/** - * This sample demonstrates how to selectively restore a key from key vault backup. - */ -public class SelectiveKeyRestore { - /** - * Authenticates with the key vault and shows how to selectively restore a key from key vault backup synchronously. - * For examples of how to perform async operations, please refer to - * {@link BackupAndRestoreHelloWorldAsync the async client samples}. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when an invalid key vault URL is passed. - */ - public static void main(String[] args) { - /* Instantiate a KeyVaultBackupClient that will be used to call the service. Notice that the client is using - default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) - for links and instructions. */ - KeyVaultBackupClient backupClient = new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - /* Using the KeyVaultBackupClient, you can restore a single key from backup by key name. The data source for a - selective key restore is a storage blob accessed using Shared Access Signature authentication. */ - String keyName = ""; - String backupFolderUrl = ""; - String sasToken = ""; - - SyncPoller restorePoller = - backupClient.beginSelectiveKeyRestore(keyName, backupFolderUrl, sasToken); - - restorePoller.waitForCompletion(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/SettingsHelloWorld.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/SettingsHelloWorld.java deleted file mode 100644 index fd38aaebdfb0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/SettingsHelloWorld.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; - -import java.util.ArrayList; -import java.util.List; - -/** - * This sample demonstrates how to update, get, and lists settings synchronously for a Key Vault account. - */ -public class SettingsHelloWorld { - /** - * Authenticates with the key vault and shows how to update, get, and lists settings synchronously for a Key Vault - * account synchronously. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when an invalid key vault URL is passed. - */ - public static void main(String[] args) { - /* Instantiate a KeyVaultSettingsClient that will be used to call the service. Notice that the client is - using default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) - for links and instructions. */ - KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - /* In order to update a setting, we'll have to know which ones are available for the account. Let's get all of - them. */ - List settings = new ArrayList<>(); - KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings(); - - for (KeyVaultSetting setting : getSettingsResult.getSettings()) { - settings.add(setting); - - System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), - setting.asBoolean()); - } - - /* If you want to get only a specific setting and its value instead, you can do the following. */ - String settingName = settings.get(0).getName(); - KeyVaultSetting retrievedSetting = keyVaultSettingsClient.getSetting(settingName); - - System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", retrievedSetting.getName(), - retrievedSetting.asBoolean()); - - /* Now let's update the settings to hold a new value. Currently, only boolean values are supported. */ - KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); - KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate); - - System.out.printf("Updated setting with name '%s' to '%s'.%n", updatedSetting.getName(), - updatedSetting.asBoolean()); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/SettingsHelloWorldAsync.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/SettingsHelloWorldAsync.java deleted file mode 100644 index 2f687243c593..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/SettingsHelloWorldAsync.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; - -import java.util.ArrayList; -import java.util.List; - -/** - * This sample demonstrates how to update, get, and lists settings asynchronously for a Key Vault account. - */ -public class SettingsHelloWorldAsync { - /** - * Authenticates with the key vault and shows how to update, get, and lists settings synchronously for a Key Vault - * account asynchronously. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when an invalid key vault URL is passed. - */ - public static void main(String[] args) { - /* Instantiate a KeyVaultSettingsAsyncClient that will be used to call the service. Notice that the client is - using default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) - for links and instructions. */ - KeyVaultSettingsAsyncClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - /* In order to update a setting, we'll have to know which ones are available for the account. Let's get all of - them. */ - List settings = new ArrayList<>(); - - keyVaultSettingsClient.getSettings() - .subscribe(settingsResult -> - settingsResult.getSettings().forEach(setting -> { - settings.add(setting); - - System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), - setting.asBoolean()); - })); - - /* If you want to get only a specific setting and its value instead, you can do the following. */ - String settingName = settings.get(0).getName(); - - keyVaultSettingsClient.getSetting(settingName) - .subscribe(retrievedSetting -> { - System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", retrievedSetting.getName(), - retrievedSetting.asBoolean()); - - /* Now let's update the setting to hold a new value. Currently, only boolean values are supported. */ - KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); - - keyVaultSettingsClient.updateSetting(settingToUpdate).subscribe(updatedSetting -> - System.out.printf("Updated setting with name '%s' to '%s'.%n", updatedSetting.getName(), - updatedSetting.asBoolean())); - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultAccessControlAsyncClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultAccessControlAsyncClientJavaDocCodeSnippets.java deleted file mode 100644 index 903e4ef8fa15..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultAccessControlAsyncClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration.codesnippets; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient; -import com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultDataAction; -import com.azure.security.keyvault.administration.models.KeyVaultPermission; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.SetRoleDefinitionOptions; - -import java.util.ArrayList; -import java.util.List; - -/** - * This class contains code samples for generating javadocs through doclets for - * {@link KeyVaultAccessControlAsyncClient}. - */ -public class KeyVaultAccessControlAsyncClientJavaDocCodeSnippets { - /** - * Generates a code sample for creating a {@link KeyVaultAccessControlAsyncClient}. - * - * @return An instance of {@link KeyVaultAccessControlAsyncClient}. - */ - public KeyVaultAccessControlAsyncClient createAsyncClient() { - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.instantiation - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.instantiation - - return keyVaultAccessControlAsyncClient; - } - - /** - * Generates code sample for creating a {@link KeyVaultAccessControlAsyncClient} using a custom {@link HttpClient}. - * - * @return An instance of {@link KeyVaultAccessControlAsyncClient}. - */ - public KeyVaultAccessControlAsyncClient createAsyncClientWithHttpClient() { - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.instantiation.withHttpClient - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .httpClient(HttpClient.createDefault()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.instantiation.withHttpClient - return keyVaultAccessControlAsyncClient; - } - - /** - * Generates code samples for using {@link KeyVaultAccessControlAsyncClient#listRoleDefinitions(KeyVaultRoleScope)}. - */ - public void listRoleDefinitions() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = createAsyncClient(); - - // BEGIN: 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.listRoleDefinitions#KeyVaultRoleScope - } - - /** - * Generates code samples for using {@link KeyVaultAccessControlAsyncClient#setRoleDefinition(KeyVaultRoleScope)}, - * {@link KeyVaultAccessControlAsyncClient#setRoleDefinition(KeyVaultRoleScope, String)} and - * {@link KeyVaultAccessControlAsyncClient#setRoleDefinitionWithResponse(SetRoleDefinitionOptions)}. - */ - public void setRoleDefinition() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = createAsyncClient(); - - // BEGIN: 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.setRoleDefinition#KeyVaultRoleScope - - // BEGIN: 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.setRoleDefinition#KeyVaultRoleScope-String - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.setRoleDefinitionWithResponse#SetRoleDefinitionOptions - String roleDefinitionName = "9de303d3-6ea8-4b8f-a20b-18e67f77e42a"; - - List assignableScopes = new ArrayList<>(); - assignableScopes.add(KeyVaultRoleScope.GLOBAL); - assignableScopes.add(KeyVaultRoleScope.KEYS); - - List 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 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.setRoleDefinitionWithResponse#SetRoleDefinitionOptions - } - - /** - * Generates code samples for using - * {@link KeyVaultAccessControlAsyncClient#getRoleDefinition(KeyVaultRoleScope, String)} and - * {@link KeyVaultAccessControlAsyncClient#getRoleDefinitionWithResponse(KeyVaultRoleScope, String)}. - */ - public void getRoleDefinition() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = createAsyncClient(); - - // BEGIN: 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.getRoleDefinition#KeyVaultRoleScope-String - - // BEGIN: 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.getRoleDefinitionWithResponse#KeyVaultRoleScope-String - } - - /** - * Generates code samples for using - * {@link KeyVaultAccessControlAsyncClient#deleteRoleDefinition(KeyVaultRoleScope, String)} and - * {@link KeyVaultAccessControlAsyncClient#deleteRoleDefinitionWithResponse(KeyVaultRoleScope, String)}. - */ - public void deleteRoleDefinition() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = createAsyncClient(); - - // BEGIN: 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)); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.deleteRoleDefinition#KeyVaultRoleScope-String - - // BEGIN: 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)); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.deleteRoleDefinitionWithResponse#KeyVaultRoleScope-String - } - - /** - * Generates code samples for using {@link KeyVaultAccessControlAsyncClient#listRoleAssignments(KeyVaultRoleScope)}. - */ - public void listRoleAssignments() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.listRoleAssignments#KeyVaultRoleScope - keyVaultAccessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL) - .subscribe(roleAssignment -> - System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.listRoleAssignments#KeyVaultRoleScope - } - - /** - * Generates code samples for using - * {@link KeyVaultAccessControlAsyncClient#createRoleAssignment(KeyVaultRoleScope, String, String)}, - * {@link KeyVaultAccessControlAsyncClient#createRoleAssignment(KeyVaultRoleScope, String, String, String)} and - * {@link KeyVaultAccessControlAsyncClient#createRoleAssignmentWithResponse(KeyVaultRoleScope, String, String, String)}. - */ - public void createRoleAssignment() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = createAsyncClient(); - - // BEGIN: 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.createRoleAssignment#KeyVaultRoleScope-String-String - - // BEGIN: 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.createRoleAssignment#KeyVaultRoleScope-String-String-String - - // BEGIN: 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()); - }); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.createRoleAssignmentWithResponse#KeyVaultRoleScope-String-String-String - } - - /** - * Generates code samples for using - * {@link KeyVaultAccessControlAsyncClient#getRoleAssignment(KeyVaultRoleScope, String)} and - * {@link KeyVaultAccessControlAsyncClient#getRoleAssignmentWithResponse(KeyVaultRoleScope, String)}. - */ - public void getRoleAssignment() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = createAsyncClient(); - - // BEGIN: 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.getRoleAssignment#KeyVaultRoleScope-String - - // BEGIN: 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())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.getRoleAssignmentWithResponse#KeyVaultRoleScope-String - } - - /** - * Generates code samples for using - * {@link KeyVaultAccessControlAsyncClient#deleteRoleAssignment(KeyVaultRoleScope, String)} and - * {@link KeyVaultAccessControlAsyncClient#deleteRoleAssignmentWithResponse(KeyVaultRoleScope, String)}. - */ - public void deleteRoleAssignment() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = createAsyncClient(); - - // BEGIN: 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)); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.deleteRoleAssignment#KeyVaultRoleScope-String - - // BEGIN: 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)); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient.deleteRoleAssignmentWithResponse#KeyVaultRoleScope-String - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultAccessControlClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultAccessControlClientJavaDocCodeSnippets.java deleted file mode 100644 index eaf0674d3711..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultAccessControlClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration.codesnippets; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.KeyVaultAccessControlClient; -import com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultDataAction; -import com.azure.security.keyvault.administration.models.KeyVaultPermission; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.SetRoleDefinitionOptions; - -import java.util.ArrayList; -import java.util.List; - -/** - * This class contains code samples for generating javadocs through doclets for {@link KeyVaultAccessControlClient}. - */ -public class KeyVaultAccessControlClientJavaDocCodeSnippets { - /** - * Generates a code sample for creating a {@link KeyVaultAccessControlClient}. - * - * @return An instance of {@link KeyVaultAccessControlClient}. - */ - public KeyVaultAccessControlClient createClient() { - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.instantiation - KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.instantiation - - return keyVaultAccessControlClient; - } - - /** - * Generates code samples for using {@link KeyVaultAccessControlClient#listRoleDefinitions(KeyVaultRoleScope)} and - * {@link KeyVaultAccessControlClient#listRoleDefinitions(KeyVaultRoleScope, Context)}. - */ - public void listRoleDefinitions() { - KeyVaultAccessControlClient keyVaultAccessControlClient = createClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.listRoleDefinitions#KeyVaultRoleScope - PagedIterable roleDefinitions = - keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL); - - roleDefinitions.forEach(roleDefinition -> - System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.listRoleDefinitions#KeyVaultRoleScope - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.listRoleDefinitions#KeyVaultRoleScope-Context - PagedIterable keyVaultRoleDefinitions = - keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL, new Context("key1", "value1")); - - keyVaultRoleDefinitions.forEach(roleDefinition -> - System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.listRoleDefinitions#KeyVaultRoleScope-Context - } - - /** - * Generates code samples for using {@link KeyVaultAccessControlClient#setRoleDefinition(KeyVaultRoleScope)}, - * {@link KeyVaultAccessControlClient#setRoleDefinition(KeyVaultRoleScope, String)} and - * {@link KeyVaultAccessControlClient#setRoleDefinitionWithResponse(SetRoleDefinitionOptions, Context)}. - */ - public void setRoleDefinition() { - KeyVaultAccessControlClient keyVaultAccessControlClient = createClient(); - - // BEGIN: 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.setRoleDefinition#KeyVaultRoleScope - - // BEGIN: 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.setRoleDefinition#KeyVaultRoleScope-String - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.setRoleDefinitionWithResponse#SetRoleDefinitionOptions-Context - String roleDefinitionName = "a86990e4-2080-4666-bd36-6e1664d3706f"; - - List assignableScopes = new ArrayList<>(); - assignableScopes.add(KeyVaultRoleScope.GLOBAL); - assignableScopes.add(KeyVaultRoleScope.KEYS); - - List 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 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 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.setRoleDefinitionWithResponse#SetRoleDefinitionOptions-Context - } - - /** - * Generates code samples for using {@link KeyVaultAccessControlClient#getRoleDefinition(KeyVaultRoleScope, String)} - * and {@link KeyVaultAccessControlClient#getRoleDefinitionWithResponse(KeyVaultRoleScope, String, Context)}. - */ - public void getRoleDefinition() { - KeyVaultAccessControlClient keyVaultAccessControlClient = createClient(); - - // BEGIN: 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.getRoleDefinition#KeyVaultRoleScope-String - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.getRoleDefinitionWithResponse#KeyVaultRoleScope-String-Context - String myRoleDefinitionName = "cb15ef18-b32c-4224-b048-3a91cd68acc3"; - Response 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.getRoleDefinitionWithResponse#KeyVaultRoleScope-String-Context - } - - /** - * Generates code samples for using - * {@link KeyVaultAccessControlClient#deleteRoleDefinition(KeyVaultRoleScope, String)} and - * {@link KeyVaultAccessControlClient#deleteRoleDefinitionWithResponse(KeyVaultRoleScope, String, Context)}. - */ - public void deleteRoleDefinition() { - KeyVaultAccessControlClient keyVaultAccessControlClient = createClient(); - - // BEGIN: 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); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.deleteRoleDefinition#KeyVaultRoleScope-String - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.deleteRoleDefinitionWithResponse#KeyVaultRoleScope-String-Context - String myRoleDefinitionName = "6b2d0b58-4108-44d6-b7e0-4fd02f77fe7e"; - Response 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); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.deleteRoleDefinitionWithResponse#KeyVaultRoleScope-String-Context - } - - /** - * Generates code samples for using {@link KeyVaultAccessControlClient#listRoleAssignments(KeyVaultRoleScope)} and - * {@link KeyVaultAccessControlClient#listRoleAssignments(KeyVaultRoleScope, Context)}. - */ - public void listRoleAssignments() { - KeyVaultAccessControlClient keyVaultAccessControlClient = createClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.listRoleAssignments#KeyVaultRoleScope - PagedIterable roleAssignments = - keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL); - - roleAssignments.forEach(roleAssignment -> - System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.listRoleAssignments#KeyVaultRoleScope - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.listRoleAssignments#KeyVaultRoleScope-Context - PagedIterable keyVaultRoleAssignments = - keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL, new Context("key1", "value1")); - - keyVaultRoleAssignments.forEach(roleAssignment -> - System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.listRoleAssignments#KeyVaultRoleScope-Context - } - - /** - * Generates code samples for using - * {@link KeyVaultAccessControlClient#createRoleAssignment(KeyVaultRoleScope, String, String)}, - * {@link KeyVaultAccessControlClient#createRoleAssignment(KeyVaultRoleScope, String, String, String)} and - * {@link KeyVaultAccessControlClient#createRoleAssignmentWithResponse(KeyVaultRoleScope, String, String, String, Context)}. - */ - public void createRoleAssignment() { - KeyVaultAccessControlClient keyVaultAccessControlClient = createClient(); - - // BEGIN: 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.createRoleAssignment#KeyVaultRoleScope-String-String - - // BEGIN: 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.createRoleAssignment#KeyVaultRoleScope-String-String-String - - // BEGIN: 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 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.createRoleAssignmentWithResponse#KeyVaultRoleScope-String-String-String-Context - } - - /** - * Generates code samples for using {@link KeyVaultAccessControlClient#getRoleAssignment(KeyVaultRoleScope, String)} - * and {@link KeyVaultAccessControlClient#getRoleAssignmentWithResponse(KeyVaultRoleScope, String, Context)}. - */ - public void getRoleAssignment() { - KeyVaultAccessControlClient keyVaultAccessControlClient = createClient(); - - // BEGIN: 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.getRoleAssignment#KeyVaultRoleScope-String - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.getRoleAssignmentWithResponse#KeyVaultRoleScope-String-Context - String myRoleAssignmentName = "b4a970d5-c581-4760-bba5-61d3d5aa24f9"; - Response 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()); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.getRoleAssignmentWithResponse#KeyVaultRoleScope-String-Context - } - - /** - * Generates code samples for using - * {@link KeyVaultAccessControlClient#deleteRoleAssignment(KeyVaultRoleScope, String)} and - * {@link KeyVaultAccessControlClient#deleteRoleAssignmentWithResponse(KeyVaultRoleScope, String, Context)}. - */ - public void deleteRoleAssignment() { - KeyVaultAccessControlClient keyVaultAccessControlClient = createClient(); - - // BEGIN: 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); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.deleteRoleAssignment#KeyVaultRoleScope-String - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.deleteRoleAssignmentWithResponse#KeyVaultRoleScope-String-Context - String myRoleAssignmentName = "8ac293e1-1ac8-4a71-b254-7caf9f7c2646"; - Response 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); - // END: com.azure.security.keyvault.administration.KeyVaultAccessControlClient.deleteRoleAssignmentWithResponse#KeyVaultRoleScope-String-Context - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultBackupAsyncClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultBackupAsyncClientJavaDocCodeSnippets.java deleted file mode 100644 index 158569649064..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultBackupAsyncClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration.codesnippets; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.util.polling.AsyncPollResponse; -import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient; -import com.azure.security.keyvault.administration.KeyVaultBackupClientBuilder; - -import java.time.Duration; - -/** - * This class contains code samples for generating javadocs through doclets for {@link KeyVaultBackupAsyncClient}. - */ -public class KeyVaultBackupAsyncClientJavaDocCodeSnippets { - /** - * Generates a code sample for creating a {@link KeyVaultBackupAsyncClient}. - * - * @return An instance of {@link KeyVaultBackupAsyncClient}. - */ - public KeyVaultBackupAsyncClient createAsyncClient() { - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.instantiation - KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.instantiation - - return keyVaultBackupAsyncClient; - } - - /** - * Generates code sample for creating a {@link KeyVaultBackupAsyncClient} using a custom {@link HttpClient}. - * - * @return An instance of {@link KeyVaultBackupAsyncClient}. - */ - public KeyVaultBackupAsyncClient createAsyncClientWithHttpClient() { - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.instantiation.withHttpClient - KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .httpClient(HttpClient.createDefault()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.instantiation.withHttpClient - return keyVaultBackupAsyncClient; - } - - /** - * Generates code samples for using {@link KeyVaultBackupAsyncClient#beginPreBackup(String, String)}. - */ - public void beginPreBackup() { - KeyVaultBackupAsyncClient client = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginPreBackup#String-String - String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; - String sasToken = ""; - - client.beginPreBackup(blobStorageUrl, sasToken) - .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. - .doOnError(e -> System.out.printf("Pre-backup check 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("Pre-backup check completed successfully.%n")); - // END: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginPreBackup#String-String - } - - /** - * Generates code samples for using {@link KeyVaultBackupAsyncClient#beginBackup(String, String)}. - */ - public void beginBackup() { - KeyVaultBackupAsyncClient client = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginBackup#String-String - String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; - String sasToken = ""; - - 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)); - // END: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginBackup#String-String - } - - /** - * Generates code samples for using {@link KeyVaultBackupAsyncClient#beginPreRestore(String, String)}. - */ - public void beginPreRestore() { - KeyVaultBackupAsyncClient client = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginPreRestore#String-String - String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; - String sasToken = ""; - - client.beginPreRestore(folderUrl, sasToken) - .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. - .doOnError(e -> System.out.printf("Pre-restore check 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("Pre-restore check completed successfully.%n")); - // END: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginPreRestore#String-String - } - - /** - * Generates code samples for using {@link KeyVaultBackupAsyncClient#beginRestore(String, String)}. - */ - public void beginRestore() { - KeyVaultBackupAsyncClient client = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginRestore#String-String - String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; - String sasToken = ""; - - 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")); - // END: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginRestore#String-String - } - - /** - * Generates code samples for using - * {@link KeyVaultBackupAsyncClient#beginSelectiveKeyRestore(String, String, String)}. - */ - public void beginSelectiveKeyRestore() { - KeyVaultBackupAsyncClient client = createAsyncClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginSelectiveKeyRestore#String-String-String - String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; - String sasToken = ""; - 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")); - // END: com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.beginSelectiveKeyRestore#String-String-String - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultBackupClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultBackupClientJavaDocCodeSnippets.java deleted file mode 100644 index 1c0788b0b3c2..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultBackupClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration.codesnippets; - -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.administration.KeyVaultBackupClient; -import com.azure.security.keyvault.administration.KeyVaultBackupClientBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; - -/** - * This class contains code samples for generating javadocs through doclets for {@link KeyVaultBackupClient}. - */ -public class KeyVaultBackupClientJavaDocCodeSnippets { - /** - * Generates a code sample for creating a {@link KeyVaultBackupClient}. - * - * @return An instance of {@link KeyVaultBackupClient}. - */ - public KeyVaultBackupClient createClient() { - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupClient.instantiation - KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - // END: com.azure.security.keyvault.administration.KeyVaultBackupClient.instantiation - - return keyVaultBackupClient; - } - - /** - * Generates code samples for using {@link KeyVaultBackupClient#beginPreBackup(String, String)}. - */ - public void beginPreBackup() { - KeyVaultBackupClient client = createClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginPreBackup#String-String - String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; - String sasToken = ""; - - SyncPoller preBackupPoller = client.beginPreBackup(blobStorageUrl, sasToken); - PollResponse pollResponse = preBackupPoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse finalPollResponse = preBackupPoller.waitForCompletion(); - - if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Pre-backup check completed successfully.%n"); - } else { - KeyVaultBackupOperation operation = preBackupPoller.poll().getValue(); - - System.out.printf("Pre-backup check failed with error: %s.%n", operation.getError().getMessage()); - } - // END: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginPreBackup#String-String - } - - /** - * Generates code samples for using {@link KeyVaultBackupClient#beginBackup(String, String)}. - */ - public void beginBackup() { - KeyVaultBackupClient client = createClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginBackup#String-String - String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; - String sasToken = ""; - - SyncPoller backupPoller = client.beginBackup(blobStorageUrl, sasToken); - PollResponse pollResponse = backupPoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse 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()); - } - // END: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginBackup#String-String - } - - /** - * Generates code samples for using {@link KeyVaultBackupClient#beginPreRestore(String, String)}. - */ - public void beginPreRestore() { - KeyVaultBackupClient client = createClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginPreRestore#String-String - String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; - String sasToken = ""; - - SyncPoller preRestorePoller = - client.beginPreRestore(folderUrl, sasToken); - PollResponse pollResponse = preRestorePoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse finalPollResponse = preRestorePoller.waitForCompletion(); - - if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Pre-restore check completed successfully.%n"); - } else { - KeyVaultRestoreOperation operation = preRestorePoller.poll().getValue(); - - System.out.printf("Pre-restore check failed with error: %s.%n", operation.getError().getMessage()); - } - // END: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginPreRestore#String-String - } - - /** - * Generates code samples for using {@link KeyVaultBackupClient#beginRestore(String, String)}. - */ - public void beginRestore() { - KeyVaultBackupClient client = createClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginRestore#String-String - String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; - String sasToken = ""; - - SyncPoller restorePoller = - client.beginRestore(folderUrl, sasToken); - PollResponse pollResponse = restorePoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse finalPollResponse = restorePoller.waitForCompletion(); - - if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Backup restored successfully.%n"); - } else { - KeyVaultRestoreOperation operation = restorePoller.poll().getValue(); - - System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage()); - } - // END: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginRestore#String-String - } - - /** - * Generates code samples for using {@link KeyVaultBackupClient#beginSelectiveKeyRestore(String, String, String)}. - */ - public void beginSelectiveKeyRestore() { - KeyVaultBackupClient client = createClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginSelectiveKeyRestore#String-String-String - String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; - String sasToken = ""; - String keyName = "myKey"; - - SyncPoller restorePoller = - client.beginSelectiveKeyRestore(folderUrl, sasToken, keyName); - PollResponse pollResponse = restorePoller.poll(); - - System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); - - PollResponse finalPollResponse = restorePoller.waitForCompletion(); - - if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - System.out.printf("Key restored successfully.%n"); - } else { - KeyVaultSelectiveKeyRestoreOperation operation = restorePoller.poll().getValue(); - - System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage()); - } - // END: com.azure.security.keyvault.administration.KeyVaultBackupClient.beginSelectiveKeyRestore#String-String-String - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultSettingsAsyncClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultSettingsAsyncClientJavaDocCodeSnippets.java deleted file mode 100644 index d8975f560a9f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultSettingsAsyncClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.codesnippets; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient; -import com.azure.security.keyvault.administration.KeyVaultSettingsClientBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; - -import java.util.List; - -/** - * This class contains code samples for generating javadocs through doclets for {@link KeyVaultSettingsAsyncClient}. - */ -public class KeyVaultSettingsAsyncClientJavaDocCodeSnippets { - /** - * Generates a code sample for creating a {@link KeyVaultSettingsAsyncClient}. - * - * @return An instance of {@link KeyVaultSettingsAsyncClient}. - */ - public KeyVaultSettingsAsyncClient createClient() { - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.instantiation - KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = new KeyVaultSettingsClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.instantiation - - return keyVaultSettingsAsyncClient; - } - - /** - * Generates code sample for creating a {@link KeyVaultSettingsAsyncClient} using a custom {@link HttpClient}. - * - * @return An instance of {@link KeyVaultSettingsAsyncClient}. - */ - public KeyVaultSettingsAsyncClient createAsyncClientWithHttpClient() { - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.instantiation.withHttpClient - KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = new KeyVaultSettingsClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .httpClient(HttpClient.createDefault()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.instantiation.withHttpClient - return keyVaultSettingsAsyncClient; - } - - /** - * Generates code samples for using {@link KeyVaultSettingsAsyncClient#updateSetting(KeyVaultSetting)} and - * {@link KeyVaultSettingsAsyncClient#updateSettingWithResponse(KeyVaultSetting)} . - */ - public void updateSetting() { - KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = createClient(); - String settingName = ""; - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.updateSetting#KeyVaultSetting - KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); - - keyVaultSettingsAsyncClient.updateSetting(settingToUpdate) - .subscribe(updatedSetting -> - System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), - updatedSetting.asBoolean())); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.updateSetting#KeyVaultSetting - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.updateSettingWithResponse#KeyVaultSetting - KeyVaultSetting mySettingToUpdate = new KeyVaultSetting(settingName, true); - - keyVaultSettingsAsyncClient.updateSettingWithResponse(mySettingToUpdate) - .subscribe(response -> - System.out.printf("Response successful with status code: %d. Updated setting '%s' to '%s'.%n", - response.getStatusCode(), response.getValue().getName(), response.getValue().asBoolean())); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.updateSettingWithResponse#KeyVaultSetting - } - - /** - * Generates code samples for using {@link KeyVaultSettingsAsyncClient#getSetting(String)} - * and {@link KeyVaultSettingsAsyncClient#getSettingWithResponse(String)}. - */ - public void getSetting() { - KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = createClient(); - String settingName = ""; - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.getSetting#String - keyVaultSettingsAsyncClient.getSetting(settingName) - .subscribe(setting -> - System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean())); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.getSetting#String - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.getSettingWithResponse#String - keyVaultSettingsAsyncClient.getSettingWithResponse(settingName) - .subscribe(response -> - System.out.printf("Response successful with status code: %d. Retrieved setting '%s' with value '%s'.%n", - response.getStatusCode(), response.getValue().getName(), response.getValue().asBoolean())); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.getSettingWithResponse#String - } - - /** - * Generates code samples for using {@link KeyVaultSettingsAsyncClient#getSettings()} and - * {@link KeyVaultSettingsAsyncClient#getSettingsWithResponse()}. - */ - public void getSettings() { - KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = createClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.getSettings - keyVaultSettingsAsyncClient.getSettings().subscribe(getSettingsResult -> - getSettingsResult.getSettings().forEach(setting -> - System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(), - setting.asBoolean()))); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.getSettings - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.getSettingsWithResponse - keyVaultSettingsAsyncClient.getSettingsWithResponse() - .subscribe(response -> { - System.out.printf("Response successful with status code: %d.", response.getStatusCode()); - - KeyVaultGetSettingsResult getSettingsResult = response.getValue(); - List settings = getSettingsResult.getSettings(); - - settings.forEach(setting -> - System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(), - setting.asBoolean())); - }); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient.getSettingsWithResponse - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultSettingsClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultSettingsClientJavaDocCodeSnippets.java deleted file mode 100644 index bb3d90ec353b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/samples/java/com/azure/security/keyvault/administration/codesnippets/KeyVaultSettingsClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.codesnippets; - -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.KeyVaultSettingsClient; -import com.azure.security.keyvault.administration.KeyVaultSettingsClientBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; - -import java.util.List; - -/** - * This class contains code samples for generating javadocs through doclets for {@link KeyVaultSettingsClient}. - */ -public class KeyVaultSettingsClientJavaDocCodeSnippets { - /** - * Generates a code sample for creating a {@link KeyVaultSettingsClient}. - * - * @return An instance of {@link KeyVaultSettingsClient}. - */ - public KeyVaultSettingsClient createClient() { - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsClient.instantiation - KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsClient.instantiation - - return keyVaultSettingsClient; - } - - /** - * Generates code samples for using {@link KeyVaultSettingsClient#updateSetting(KeyVaultSetting)} and - * {@link KeyVaultSettingsClient#updateSettingWithResponse(KeyVaultSetting, Context)} . - */ - public void updateSetting() { - KeyVaultSettingsClient keyVaultSettingsClient = createClient(); - String settingName = ""; - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsClient.updateSetting#KeyVaultSetting - KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); - KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate); - - System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean()); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsClient.updateSetting#KeyVaultSetting - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsClient.updateSettingWithResponse#KeyVaultSetting-Context - KeyVaultSetting mySettingToUpdate = new KeyVaultSetting(settingName, true); - Response response = - keyVaultSettingsClient.updateSettingWithResponse(mySettingToUpdate, new Context("key1", "value1")); - - System.out.printf("Response successful with status code: %d. Updated setting '%s' to '%s'.%n", - response.getStatusCode(), response.getValue().getName(), response.getValue().asBoolean()); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsClient.updateSettingWithResponse#KeyVaultSetting-Context - } - - /** - * Generates code samples for using {@link KeyVaultSettingsClient#getSetting(String)} - * and {@link KeyVaultSettingsClient#getSettingWithResponse(String, Context)}. - */ - public void getSetting() { - KeyVaultSettingsClient keyVaultSettingsClient = createClient(); - String settingName = ""; - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsClient.getSetting#String - KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName); - - System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean()); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsClient.getSetting#String - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsClient.getSettingWithResponse#String-Context - Response response = - keyVaultSettingsClient.getSettingWithResponse(settingName, new Context("key1", "value1")); - - System.out.printf("Response successful with status code: %d. Retrieved setting '%s' with value '%s'.%n", - response.getStatusCode(), response.getValue().getName(), response.getValue().asBoolean()); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsClient.getSettingWithResponse#String-Context - } - - /** - * Generates code samples for using {@link KeyVaultSettingsClient#getSettings()} and - * {@link KeyVaultSettingsClient#getSettingsWithResponse(Context)}. - */ - public void getSettings() { - KeyVaultSettingsClient keyVaultSettingsClient = createClient(); - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsClient.getSettings - KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings(); - List settings = getSettingsResult.getSettings(); - - settings.forEach(setting -> - System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(), - setting.asBoolean())); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsClient.getSettings - - // BEGIN: com.azure.security.keyvault.administration.KeyVaultSettingsClient.getSettingsWithResponse#Context - Response response = - keyVaultSettingsClient.getSettingsWithResponse(new Context("key1", "value1")); - - System.out.printf("Response successful with status code: %d.", response.getStatusCode()); - - KeyVaultGetSettingsResult myGetSettingsResult = response.getValue(); - List mySettings = myGetSettingsResult.getSettings(); - - mySettings.forEach(setting -> - System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(), - setting.asBoolean())); - // END: com.azure.security.keyvault.administration.KeyVaultSettingsClient.getSettingsWithResponse#Context - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClientTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClientTest.java deleted file mode 100644 index f262f66e84f5..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClientTest.java +++ /dev/null @@ -1,360 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.http.HttpClient; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignmentProperties; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinitionType; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.KeyVaultRoleType; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.time.Duration; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultAccessControlAsyncClientTest extends KeyVaultAccessControlClientTestBase { - private KeyVaultAccessControlAsyncClient asyncClient; - - private void getClient(HttpClient httpClient, boolean forCleanup) { - asyncClient - = getClientBuilder( - buildAsyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - forCleanup).buildAsyncClient(); - - if (!interceptorManager.isLiveMode()) { - // Remove `id` and `name` sanitizers from the list of common sanitizers. - interceptorManager.removeSanitizers("AZSDK3430", "AZSDK3493"); - } - } - - private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertAsync().build(); - } - - /** - * Tests that existing {@link KeyVaultRoleDefinition role definitions} can be retrieved from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void listRoleDefinitions(HttpClient httpClient) { - getClient(httpClient, false); - - StepVerifier.create(asyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) - .thenConsumeWhile(roleDefinition -> { - assertNotNull(roleDefinition.getId()); - assertNotNull(roleDefinition.getName()); - assertNotNull(roleDefinition.getType()); - assertNotNull(roleDefinition.getRoleName()); - assertNotNull(roleDefinition.getDescription()); - assertNotNull(roleDefinition.getRoleType()); - assertNotNull(roleDefinition.getAssignableScopes()); - assertNotNull(roleDefinition.getPermissions()); - - return true; - }) - .expectComplete() - .verify(); - } - - /** - * Tests that a {@link KeyVaultRoleDefinition role definition} can be created in the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void setRoleDefinition(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - - try { - // Create a role definition. - StepVerifier - .create(asyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO)) - .assertNext(roleDefinition -> { - assertNotNull(roleDefinition.getId()); - assertEquals(roleDefinitionName, roleDefinition.getName()); - assertEquals(KeyVaultRoleDefinitionType.MICROSOFT_AUTHORIZATION_ROLE_DEFINITIONS, - roleDefinition.getType()); - assertTrue(roleDefinition.getAssignableScopes().contains(KeyVaultRoleScope.GLOBAL)); - assertEquals(KeyVaultRoleType.CUSTOM_ROLE, roleDefinition.getRoleType()); - assertEquals(roleDefinitionName, roleDefinition.getRoleName()); - }) - .expectComplete() - .verify(); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, null); - } - } - } - - /** - * Tests that an existing {@link KeyVaultRoleDefinition role definition} can be retrieved from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void getRoleDefinition(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - - try { - // Create a role definition to retrieve, then get the role assignment. - StepVerifier - .create(asyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO) - .flatMap(createdRoleDefinition -> Mono.zip(Mono.just(createdRoleDefinition), - asyncClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, createdRoleDefinition.getName())))) - .assertNext(tuple -> { - KeyVaultRoleDefinition createdRoleDefinition = tuple.getT1(); - KeyVaultRoleDefinition retrievedRoleDefinition = tuple.getT2(); - - assertNotNull(retrievedRoleDefinition); - assertRoleDefinitionEquals(createdRoleDefinition, retrievedRoleDefinition); - }) - .expectComplete() - .verify(); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, null); - } - } - } - - /** - * Tests that an existing {@link KeyVaultRoleDefinition role definition} can be deleted from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void deleteRoleDefinition(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - - // Create a role definition to delete, then delete the role definition. - StepVerifier - .create(asyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO) - .flatMap(createdRoleDefinition -> asyncClient.deleteRoleDefinitionWithResponse(KeyVaultRoleScope.GLOBAL, - createdRoleDefinition.getName()))) - .assertNext(deleteResponse -> assertEquals(200, deleteResponse.getStatusCode())) - .expectComplete() - .verify(); - } - - /** - * Tests that an exception is thrown when trying to delete a non-existent - * {@link KeyVaultRoleDefinition role definition} from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void deleteNonExistingRoleDefinitionDoesNotThrow(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - - // Try to delete a non-existent role definition. - StepVerifier.create(asyncClient.deleteRoleDefinitionWithResponse(KeyVaultRoleScope.GLOBAL, roleDefinitionName)) - .assertNext(deleteResponse -> assertEquals(404, deleteResponse.getStatusCode())) - .expectComplete() - .verify(); - } - - /** - * Tests that existing {@link KeyVaultRoleAssignment role assignments} can be retrieved from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void listRoleAssignments(HttpClient httpClient) { - asyncClient = getClientBuilder(httpClient, false).buildAsyncClient(); - - StepVerifier.create(asyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) - .thenConsumeWhile(roleAssignment -> { - assertNotNull(roleAssignment.getId()); - assertNotNull(roleAssignment.getName()); - assertNotNull(roleAssignment.getType()); - - KeyVaultRoleAssignmentProperties properties = roleAssignment.getProperties(); - - assertNotNull(properties); - assertNotNull(properties.getRoleDefinitionId()); - assertNotNull(properties.getPrincipalId()); - assertEquals(KeyVaultRoleScope.GLOBAL, properties.getScope()); - - return true; - }) - .expectComplete() - .verify(); - } - - /** - * Tests that a {@link KeyVaultRoleAssignment role assignment} can be created in the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void createRoleAssignment(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - String roleAssignmentName = testResourceNamer.randomUuid(); - - try { - // Create a role assignment to delete. - StepVerifier - .create(asyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO) - .flatMap(roleDefinition -> Mono.zip(Mono.just(roleDefinition), - asyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), - servicePrincipalId, roleAssignmentName))) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO)) - .assertNext(tuple -> { - KeyVaultRoleAssignment roleAssignment = tuple.getT2(); - - assertNotNull(roleAssignment); - assertNotNull(roleAssignment.getId()); - assertEquals(roleAssignmentName, roleAssignment.getName()); - assertNotNull(roleAssignment.getType()); - - KeyVaultRoleAssignmentProperties properties = roleAssignment.getProperties(); - - assertNotNull(properties); - assertNotNull(properties.getPrincipalId()); - assertEquals(KeyVaultRoleScope.GLOBAL, properties.getScope()); - - KeyVaultRoleDefinition roleDefinition = tuple.getT1(); - - assertEquals(roleDefinition.getId(), properties.getRoleDefinitionId()); - }) - .expectComplete() - .verify(); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, - roleAssignmentName); - } - } - } - - /** - * Tests that a {@link KeyVaultRoleAssignment role assignment} that already exists in the Key Vault cannot be - * created again. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void createExistingRoleAssignmentThrows(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - String roleAssignmentName = testResourceNamer.randomUuid(); - - try { - // Create a role assignment to delete. - StepVerifier - .create(asyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO) - .flatMap(roleDefinition -> asyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, - roleDefinition.getId(), servicePrincipalId, roleAssignmentName)) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO) - .flatMap(roleAssignment -> asyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, - roleAssignment.getProperties().getRoleDefinitionId(), servicePrincipalId, roleAssignmentName))) - .expectError(KeyVaultAdministrationException.class) - .verify(); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, - roleAssignmentName); - } - } - } - - /** - * Tests that an existing {@link KeyVaultRoleAssignment role assignment} can be retrieved from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void getRoleAssignment(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - String roleAssignmentName = testResourceNamer.randomUuid(); - - try { - // Create a role assignment to delete. - StepVerifier - .create(asyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO) - .flatMap(roleDefinition -> asyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, - roleDefinition.getId(), servicePrincipalId, roleAssignmentName)) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO) - .flatMap(roleAssignment -> Mono.zip(Mono.just(roleAssignment), - asyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignment.getName())))) - .assertNext(tuple -> { - KeyVaultRoleAssignment createdRoleAssignment = tuple.getT1(); - KeyVaultRoleAssignment retrievedRoleAssignment = tuple.getT2(); - - assertNotNull(retrievedRoleAssignment); - assertRoleAssignmentEquals(createdRoleAssignment, retrievedRoleAssignment); - }) - .expectComplete() - .verify(); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, - roleAssignmentName); - } - } - } - - /** - * Tests that an existing {@link KeyVaultRoleAssignment role assignment} can be deleted from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void deleteRoleAssignment(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - String roleAssignmentName = testResourceNamer.randomUuid(); - - try { - // Create a role assignment to delete. - StepVerifier - .create(asyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO) - .flatMap(roleDefinition -> asyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, - roleDefinition.getId(), servicePrincipalId, roleAssignmentName)) - .delayElement(!interceptorManager.isPlaybackMode() ? Duration.ofSeconds(5) : Duration.ZERO) - .flatMap(roleAssignment -> asyncClient.deleteRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL, - roleAssignment.getName()))) - .assertNext(deleteResponse -> assertEquals(200, deleteResponse.getStatusCode())) - .expectComplete() - .verify(); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, - roleAssignmentName); - } - } - } - - /** - * Tests that an exception is thrown when trying to delete a non-existent - * {@link KeyVaultRoleAssignment role assignment} from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void deleteNonExistingRoleAssignmentDoesNotThrow(HttpClient httpClient) { - getClient(httpClient, false); - String roleAssignmentName = testResourceNamer.randomUuid(); - - // Try to delete a non-existent role assignment. - StepVerifier.create(asyncClient.deleteRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL, roleAssignmentName)) - .assertNext(deleteResponse -> assertEquals(404, deleteResponse.getStatusCode())) - .expectComplete() - .verify(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilderTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilderTest.java deleted file mode 100644 index c3162b1a6acd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilderTest.java +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Header; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -import java.time.Duration; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultAccessControlClientBuilderTest { - private String vaultUrl; - private String roleDefinitionId; - private String principalId; - private KeyVaultAdministrationServiceVersion serviceVersion; - - @BeforeEach - public void setUp() { - vaultUrl = "https://key-vault-url.vault.azure.net/"; - roleDefinitionId = "RoleDefinitionId"; - principalId = "PrincipalId"; - serviceVersion = KeyVaultAdministrationServiceVersion.getLatest(); - } - - @Test - public void buildSyncClientTest() { - KeyVaultAccessControlClient keyVaultAccessControlClient - = new KeyVaultAccessControlClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(keyVaultAccessControlClient); - assertEquals(KeyVaultAccessControlClient.class.getSimpleName(), - keyVaultAccessControlClient.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientUsingDefaultApiVersionTest() { - KeyVaultAccessControlClient keyVaultAccessControlClient - = new KeyVaultAccessControlClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(keyVaultAccessControlClient); - assertEquals(KeyVaultAccessControlClient.class.getSimpleName(), - keyVaultAccessControlClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientTest() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient - = new KeyVaultAccessControlClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(keyVaultAccessControlAsyncClient); - assertEquals(KeyVaultAccessControlAsyncClient.class.getSimpleName(), - keyVaultAccessControlAsyncClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientUsingDefaultApiVersionTest() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient - = new KeyVaultAccessControlClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(keyVaultAccessControlAsyncClient); - assertEquals(KeyVaultAccessControlAsyncClient.class.getSimpleName(), - keyVaultAccessControlAsyncClient.getClass().getSimpleName()); - } - - @Test - public void emptyVaultUrlThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new KeyVaultAccessControlClientBuilder().vaultUrl("")); - } - - @Test - public void nullCredentialThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> new KeyVaultAccessControlClientBuilder().credential(null)); - } - - @Test - public void clientOptionsIsPreferredOverLogOptions() { - KeyVaultAccessControlClient keyVaultAccessControlClient - = new KeyVaultAccessControlClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) - .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ZERO))) - .httpClient(httpRequest -> { - assertTrue( - httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("aNewApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> keyVaultAccessControlClient - .createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, principalId)); - } - - @Test - public void applicationIdFallsBackToLogOptions() { - KeyVaultAccessControlClient keyVaultAccessControlClient - = new KeyVaultAccessControlClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ZERO))) - .httpClient(httpRequest -> { - assertTrue( - httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("anOldApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> keyVaultAccessControlClient - .createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, principalId)); - } - - @Test - public void clientOptionHeadersAreAddedLast() { - KeyVaultAccessControlClient keyVaultAccessControlClient - = new KeyVaultAccessControlClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .clientOptions( - new ClientOptions().setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) - .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ZERO))) - .httpClient(httpRequest -> { - assertEquals("custom", httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT)); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> keyVaultAccessControlClient - .createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, principalId)); - } - - @Test - public void bothRetryOptionsAndRetryPolicySpecified() { - assertThrows(RuntimeException.class, - () -> new KeyVaultAccessControlClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient()); - } - - // This tests the policy is in the right place because if it were added per retry, it would be after the credentials - // and auth would fail because we changed a signed header. - @Test - public void addPerCallPolicy() { - KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient - = new KeyVaultAccessControlClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .addPolicy(new TestUtils.PerCallPolicy()) - .addPolicy(new TestUtils.PerRetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - HttpPipeline pipeline = keyVaultAccessControlAsyncClient.getHttpPipeline(); - - int retryPolicyPosition = -1, perCallPolicyPosition = -1, perRetryPolicyPosition = -1; - - for (int i = 0; i < pipeline.getPolicyCount(); i++) { - if (pipeline.getPolicy(i).getClass() == RetryPolicy.class) { - retryPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerCallPolicy.class) { - perCallPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerRetryPolicy.class) { - perRetryPolicyPosition = i; - } - } - - assertTrue(perCallPolicyPosition != -1); - assertTrue(perCallPolicyPosition < retryPolicyPosition); - assertTrue(retryPolicyPosition < perRetryPolicyPosition); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientTest.java deleted file mode 100644 index ed9e3adcaac3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientTest.java +++ /dev/null @@ -1,349 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.core.util.Context; -import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignmentProperties; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinitionType; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.KeyVaultRoleType; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultAccessControlClientTest extends KeyVaultAccessControlClientTestBase { - private KeyVaultAccessControlClient client; - - private void getClient(HttpClient httpClient, boolean forCleanup) { - client - = getClientBuilder( - buildSyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - forCleanup).buildClient(); - if (!interceptorManager.isLiveMode()) { - // Remove `id` and `name` sanitizers from the list of common sanitizers. - interceptorManager.removeSanitizers("AZSDK3430", "AZSDK3493"); - } - } - - private HttpClient buildSyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertSync().build(); - } - - /** - * Tests that existing {@link KeyVaultRoleDefinition role definitions} can be retrieved from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void listRoleDefinitions(HttpClient httpClient) { - getClient(httpClient, false); - PagedIterable roleDefinitions = client.listRoleDefinitions(KeyVaultRoleScope.GLOBAL); - - assertTrue(roleDefinitions.iterator().hasNext()); - - for (KeyVaultRoleDefinition roleDefinition : roleDefinitions) { - assertNotNull(roleDefinition.getId()); - assertNotNull(roleDefinition.getName()); - assertNotNull(roleDefinition.getType()); - assertNotNull(roleDefinition.getRoleName()); - assertNotNull(roleDefinition.getDescription()); - assertNotNull(roleDefinition.getRoleType()); - assertNotNull(roleDefinition.getAssignableScopes()); - assertNotNull(roleDefinition.getPermissions()); - } - } - - /** - * Tests that a {@link KeyVaultRoleDefinition role definition} can be created in the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void setRoleDefinition(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - - try { - // Create a role definition. - KeyVaultRoleDefinition roleDefinition - = client.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - - assertNotNull(roleDefinition); - assertNotNull(roleDefinition.getId()); - assertEquals(roleDefinitionName, roleDefinition.getName()); - assertEquals(KeyVaultRoleDefinitionType.MICROSOFT_AUTHORIZATION_ROLE_DEFINITIONS, roleDefinition.getType()); - assertTrue(roleDefinition.getAssignableScopes().contains(KeyVaultRoleScope.GLOBAL)); - assertEquals(KeyVaultRoleType.CUSTOM_ROLE, roleDefinition.getRoleType()); - assertEquals(roleDefinitionName, roleDefinition.getRoleName()); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, null); - } - } - } - - /** - * Tests that an existing {@link KeyVaultRoleDefinition role definition} can be retrieved from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void getRoleDefinition(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - - try { - // Create a role definition to retrieve. - KeyVaultRoleDefinition createdRoleDefinition - = client.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - - assertNotNull(createdRoleDefinition); - - // Get the role assignment. - KeyVaultRoleDefinition retrievedRoleDefinition - = client.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - - assertNotNull(retrievedRoleDefinition); - assertRoleDefinitionEquals(createdRoleDefinition, retrievedRoleDefinition); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, null); - } - } - } - - /** - * Tests that an existing {@link KeyVaultRoleDefinition role definition} can be deleted from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void deleteRoleDefinition(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - - // Create a role definition to delete. - KeyVaultRoleDefinition createdRoleDefinition - = client.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - - assertNotNull(createdRoleDefinition); - - // Delete the role definition. - Response deleteResponse - = client.deleteRoleDefinitionWithResponse(KeyVaultRoleScope.GLOBAL, roleDefinitionName, Context.NONE); - - assertNotNull(deleteResponse); - assertEquals(200, deleteResponse.getStatusCode()); - } - - /** - * Tests that an exception is thrown when trying to delete a non-existent - * {@link KeyVaultRoleDefinition role definition} from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void deleteNonExistingRoleDefinitionDoesNotThrow(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - // Try to delete a non-existent role definition. - Response deleteResponse - = client.deleteRoleDefinitionWithResponse(KeyVaultRoleScope.GLOBAL, roleDefinitionName, Context.NONE); - - assertNotNull(deleteResponse); - assertEquals(404, deleteResponse.getStatusCode()); - } - - /** - * Tests that existing {@link KeyVaultRoleAssignment role assignments} can be retrieved from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void listRoleAssignments(HttpClient httpClient) { - getClient(httpClient, false); - PagedIterable roleAssignments = client.listRoleAssignments(KeyVaultRoleScope.GLOBAL); - - assertTrue(roleAssignments.iterator().hasNext()); - - for (KeyVaultRoleAssignment roleAssignment : roleAssignments) { - assertNotNull(roleAssignment.getId()); - assertNotNull(roleAssignment.getName()); - assertNotNull(roleAssignment.getType()); - - KeyVaultRoleAssignmentProperties properties = roleAssignment.getProperties(); - - assertNotNull(properties); - assertNotNull(properties.getRoleDefinitionId()); - assertNotNull(properties.getPrincipalId()); - assertEquals(KeyVaultRoleScope.GLOBAL, properties.getScope()); - } - } - - /** - * Tests that a {@link KeyVaultRoleAssignment role assignment} can be created in the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void createRoleAssignment(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - String roleAssignmentName = testResourceNamer.randomUuid(); - - try { - KeyVaultRoleDefinition createdRoleDefinition - = client.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - - assertNotNull(createdRoleDefinition); - - // Create a role assignment. - KeyVaultRoleAssignment createdRoleAssignment = client.createRoleAssignment(KeyVaultRoleScope.GLOBAL, - createdRoleDefinition.getId(), servicePrincipalId, roleAssignmentName); - - assertNotNull(createdRoleAssignment); - assertNotNull(createdRoleAssignment.getId()); - assertEquals(roleAssignmentName, createdRoleAssignment.getName()); - assertNotNull(createdRoleAssignment.getType()); - - KeyVaultRoleAssignmentProperties properties = createdRoleAssignment.getProperties(); - - assertNotNull(properties); - assertNotNull(properties.getPrincipalId()); - assertEquals(createdRoleDefinition.getId(), properties.getRoleDefinitionId()); - assertEquals(KeyVaultRoleScope.GLOBAL, properties.getScope()); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, - roleAssignmentName); - } - } - } - - /** - * Tests that a {@link KeyVaultRoleAssignment role assignment} that already exists in the Key Vault cannot be - * created again. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void createExistingRoleAssignmentThrows(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - String roleAssignmentName = testResourceNamer.randomUuid(); - - try { - KeyVaultRoleDefinition createdRoleDefinition - = client.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - - assertNotNull(createdRoleDefinition); - - // Create a role assignment. - client.createRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleDefinition.getId(), servicePrincipalId, - roleAssignmentName); - - // Attempt to create a role assignment with the same name and scope. - assertThrows(KeyVaultAdministrationException.class, - () -> client.createRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleDefinition.getId(), - servicePrincipalId, roleAssignmentName)); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, - roleAssignmentName); - } - } - } - - /** - * Tests that an existing {@link KeyVaultRoleAssignment role assignment} can be retrieved from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void getRoleAssignment(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - String roleAssignmentName = testResourceNamer.randomUuid(); - - try { - KeyVaultRoleDefinition createdRoleDefinition - = client.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - - assertNotNull(createdRoleDefinition); - - // Create a role assignment to retrieve. - KeyVaultRoleAssignment createdRoleAssignment = client.createRoleAssignment(KeyVaultRoleScope.GLOBAL, - createdRoleDefinition.getId(), servicePrincipalId, roleAssignmentName); - - assertNotNull(createdRoleAssignment); - - // Get the role assignment. - KeyVaultRoleAssignment retrievedRoleAssignment - = client.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); - - assertNotNull(retrievedRoleAssignment); - assertRoleAssignmentEquals(createdRoleAssignment, retrievedRoleAssignment); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, - roleAssignmentName); - } - } - } - - /** - * Tests that an existing {@link KeyVaultRoleAssignment role assignment} can be deleted from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void deleteRoleAssignment(HttpClient httpClient) { - getClient(httpClient, false); - String roleDefinitionName = testResourceNamer.randomUuid(); - String roleAssignmentName = testResourceNamer.randomUuid(); - - try { - KeyVaultRoleDefinition createdRoleDefinition - = client.setRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - - assertNotNull(createdRoleDefinition); - - // Create a role assignment to delete. - KeyVaultRoleAssignment createdRoleAssignment = client.createRoleAssignment(KeyVaultRoleScope.GLOBAL, - createdRoleDefinition.getId(), servicePrincipalId, roleAssignmentName); - - assertNotNull(createdRoleAssignment); - - // Delete the role assignment. - Response deleteResponse - = client.deleteRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL, roleAssignmentName, Context.NONE); - - assertNotNull(deleteResponse); - assertEquals(200, deleteResponse.getStatusCode()); - } finally { - if (!interceptorManager.isPlaybackMode()) { - cleanUpResources(getClientBuilder(httpClient, true).buildClient(), roleDefinitionName, - roleAssignmentName); - } - } - } - - /** - * Tests that an exception is thrown when trying to delete a non-existent - * {@link KeyVaultRoleAssignment role assignment} from the Key Vault. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void deleteNonExistingRoleAssignmentDoesNotThrow(HttpClient httpClient) { - getClient(httpClient, false); - String roleAssignmentName = testResourceNamer.randomUuid(); - // Try to delete a non-existent role assignment. - Response deleteResponse - = client.deleteRoleAssignmentWithResponse(KeyVaultRoleScope.GLOBAL, roleAssignmentName, Context.NONE); - - assertNotNull(deleteResponse); - assertEquals(404, deleteResponse.getStatusCode()); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientTestBase.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientTestBase.java deleted file mode 100644 index 40c8d924bfe0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientTestBase.java +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpClient; -import com.azure.core.util.Configuration; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.administration.models.KeyVaultPermission; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; -import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignmentProperties; -import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public abstract class KeyVaultAccessControlClientTestBase extends KeyVaultAdministrationClientTestBase { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultAccessControlClientTestBase.class); - - protected final String servicePrincipalId - = Configuration.getGlobalConfiguration().get("CLIENT_OBJECTID", "f84ae8f9-c979-4750-a2fe-b350a00bebff"); - - KeyVaultAccessControlClientBuilder getClientBuilder(HttpClient httpClient, boolean forCleanup) { - return new KeyVaultAccessControlClientBuilder().vaultUrl(getEndpoint()) - .pipeline(getPipeline(httpClient, forCleanup)); - } - - @Test - public abstract void listRoleDefinitions(HttpClient httpClient); - - @Test - public abstract void setRoleDefinition(HttpClient httpClient); - - @Test - public abstract void getRoleDefinition(HttpClient httpClient); - - @Test - public abstract void deleteRoleDefinition(HttpClient httpClient); - - @Test - public abstract void deleteNonExistingRoleDefinitionDoesNotThrow(HttpClient httpClient); - - @Test - public abstract void listRoleAssignments(HttpClient httpClient); - - @Test - public abstract void createRoleAssignment(HttpClient httpClient); - - @Test - public abstract void createExistingRoleAssignmentThrows(HttpClient httpClient); - - @Test - public abstract void getRoleAssignment(HttpClient httpClient); - - @Test - public abstract void deleteRoleAssignment(HttpClient httpClient); - - @Test - public abstract void deleteNonExistingRoleAssignmentDoesNotThrow(HttpClient httpClient); - - static void assertRoleAssignmentEquals(KeyVaultRoleAssignment roleAssignment1, - KeyVaultRoleAssignment roleAssignment2) { - assertEquals(roleAssignment1.getId(), roleAssignment2.getId()); - assertEquals(roleAssignment1.getName(), roleAssignment2.getName()); - assertEquals(roleAssignment1.getType(), roleAssignment2.getType()); - - KeyVaultRoleAssignmentProperties properties1 = roleAssignment1.getProperties(); - KeyVaultRoleAssignmentProperties properties2 = roleAssignment2.getProperties(); - - if (properties1 == null && properties2 == null) { - return; - } - - assertNotNull(properties1); - assertNotNull(properties2); - assertEquals(properties1.getPrincipalId(), properties2.getPrincipalId()); - assertEquals(properties1.getRoleDefinitionId(), properties2.getRoleDefinitionId()); - assertEquals(properties1.getScope(), properties2.getScope()); - } - - static void assertRoleDefinitionEquals(KeyVaultRoleDefinition roleDefinition1, - KeyVaultRoleDefinition roleDefinition2) { - assertEquals(roleDefinition1.getId(), roleDefinition2.getId()); - assertEquals(roleDefinition1.getName(), roleDefinition2.getName()); - assertEquals(roleDefinition1.getType(), roleDefinition2.getType()); - assertEquals(roleDefinition1.getRoleName(), roleDefinition2.getRoleName()); - assertEquals(roleDefinition1.getRoleType(), roleDefinition2.getRoleType()); - assertEquals(roleDefinition1.getDescription(), roleDefinition2.getDescription()); - - List assignableScopes1 = roleDefinition1.getAssignableScopes(); - List assignableScopes2 = roleDefinition2.getAssignableScopes(); - - if (assignableScopes1 == null && assignableScopes2 == null) { - return; - } - - assertNotNull(assignableScopes1); - assertNotNull(assignableScopes2); - - assertEquals(assignableScopes1.size(), assignableScopes2.size()); - assertTrue(assignableScopes1.containsAll(assignableScopes2)); - - List permissions1 = roleDefinition1.getPermissions(); - List permissions2 = roleDefinition2.getPermissions(); - - if (permissions1 == null && permissions2 == null) { - return; - } - - assertNotNull(permissions1); - assertNotNull(permissions2); - - assertEquals(permissions1.size(), permissions2.size()); - } - - static void cleanUpResources(KeyVaultAccessControlClient cleanupClient, String roleDefinitionName, - String roleAssignmentName) { - if (roleDefinitionName != null) { - try { - cleanupClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); - } catch (HttpResponseException e) { - if (e.getResponse().getStatusCode() == 404) { - LOGGER.info("Ignored 404 produced when trying to delete role definition."); - } - } - } - - if (roleAssignmentName != null) { - try { - cleanupClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); - } catch (HttpResponseException e) { - if (e.getResponse().getStatusCode() == 404) { - LOGGER.info("Ignored 404 produced when trying to delete role assignment."); - } - } - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAdministrationClientTestBase.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAdministrationClientTestBase.java deleted file mode 100644 index e893b3f8a821..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultAdministrationClientTestBase.java +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.ExponentialBackoff; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.HttpPolicyProviders; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.RetryStrategy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.test.TestMode; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.models.CustomMatcher; -import com.azure.core.test.models.TestProxyRequestMatcher; -import com.azure.core.test.models.TestProxySanitizer; -import com.azure.core.test.models.TestProxySanitizerType; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.Configuration; -import com.azure.identity.AzurePowerShellCredentialBuilder; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.administration.implementation.KeyVaultCredentialPolicy; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.params.provider.Arguments; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.stream.Stream; - -public abstract class KeyVaultAdministrationClientTestBase extends TestProxyTestBase { - private static final String SDK_NAME = "client_name"; - private static final String SDK_VERSION = "client_version"; - protected static final boolean IS_MANAGED_HSM_DEPLOYED - = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; - static final String DISPLAY_NAME = "{displayName}"; - - @Override - protected void beforeTest() { - super.beforeTest(); - Assumptions.assumeTrue(IS_MANAGED_HSM_DEPLOYED || getTestMode() == TestMode.PLAYBACK); - KeyVaultCredentialPolicy.clearCache(); - } - - @Override - protected String getTestName() { - return ""; - } - - HttpPipeline getPipeline(HttpClient httpClient, boolean forCleanup) { - TokenCredential credential; - if (interceptorManager.isLiveMode()) { - credential = new AzurePowerShellCredentialBuilder().additionallyAllowedTenants("*").build(); - } else if (interceptorManager.isRecordMode()) { - credential = new DefaultAzureCredentialBuilder().additionallyAllowedTenants("*").build(); - List customSanitizers = new ArrayList<>(); - customSanitizers.add(new TestProxySanitizer("token", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); - interceptorManager.addSanitizers(customSanitizers); - } else { - credential = new MockTokenCredential(); - - List customMatchers = new ArrayList<>(); - customMatchers.add(new CustomMatcher().setComparingBodies(false) - .setHeadersKeyOnlyMatch(Collections.singletonList("Accept")) - .setExcludedHeaders(Arrays.asList("Authorization", "Accept-Language"))); - interceptorManager.addMatchers(customMatchers); - } - - // Closest to API goes first, closest to wire goes last. - final List policies = new ArrayList<>(); - - policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); - HttpPolicyProviders.addBeforeRetryPolicies(policies); - - RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); - policies.add(new RetryPolicy(strategy)); - - if (credential != null) { - // If in playback mode, disable the challenge resource verification. - policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); - } - - HttpPolicyProviders.addAfterRetryPolicies(policies); - policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); - - if (interceptorManager.isRecordMode() && !forCleanup) { - policies.add(interceptorManager.getRecordPolicy()); - } - - return new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) - .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) - .build(); - } - - public String getEndpoint() { - final String endpoint = interceptorManager.isPlaybackMode() - ? "https://localhost:8080" - : Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT"); - - Objects.requireNonNull(endpoint); - - return endpoint; - } - - /** - * Returns a stream of arguments that includes all eligible {@link HttpClient HttpClients}. - * - * @return A stream of {@link HttpClient HTTP clients} to test. - */ - static Stream createHttpClients() { - return TestProxyTestBase.getHttpClients().map(Arguments::of); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClientTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClientTest.java deleted file mode 100644 index 3adcb76bcc04..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClientTest.java +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.http.HttpClient; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.core.util.polling.AsyncPollResponse; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.KeyClientBuilder; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.test.StepVerifier; - -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultBackupAsyncClientTest extends KeyVaultBackupClientTestBase { - private KeyVaultBackupAsyncClient asyncClient; - - private void getAsyncClient(HttpClient httpClient, boolean forCleanup) { - asyncClient - = getClientBuilder( - buildAsyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - forCleanup).buildAsyncClient(); - } - - private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertAsync().build(); - } - - /** - * Tests that a Key Vault or MHSM can be backed up. - */ - @SuppressWarnings("ConstantConditions") - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginBackup(HttpClient httpClient) { - getAsyncClient(httpClient, false); - - StepVerifier.create(setPlaybackPollerFluxPollInterval(asyncClient.beginBackup(blobStorageUrl, sasToken)).last() - .flatMap(AsyncPollResponse::getFinalResult)).assertNext(backupBlobUri -> { - assertNotNull(backupBlobUri); - assertTrue(backupBlobUri.startsWith(blobStorageUrl)); - }).verifyComplete(); - } - - /** - * Tests that a Key Vault or MHSM can be pre-backed up. - */ - @SuppressWarnings("ConstantConditions") - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginPreBackup(HttpClient httpClient) { - getAsyncClient(httpClient, false); - - StepVerifier - .create(setPlaybackPollerFluxPollInterval(asyncClient.beginPreBackup(blobStorageUrl, sasToken)).last() - .flatMap(AsyncPollResponse::getFinalResult) - .mapNotNull(backupBlobUri -> { - assertNull(backupBlobUri); - - return backupBlobUri; - })) - .verifyComplete(); - } - - /** - * Tests that a Key Vault can be restored from a backup. - */ - @SuppressWarnings("ConstantConditions") - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginRestore(HttpClient httpClient) { - getAsyncClient(httpClient, false); - - StepVerifier.create(setPlaybackPollerFluxPollInterval(asyncClient.beginBackup(blobStorageUrl, sasToken)).last() - .flatMap(AsyncPollResponse::getFinalResult) - .map(backupBlobUri -> { - assertNotNull(backupBlobUri); - assertTrue(backupBlobUri.startsWith(blobStorageUrl)); - - return backupBlobUri; - }) - .map(backupBlobUri -> asyncClient.beginRestore(backupBlobUri, sasToken) - .last() - .map(AsyncPollResponse::getValue))) - .assertNext(Assertions::assertNotNull) - .verifyComplete(); - - // For some reason, the service might still think a restore operation is running even after returning a success - // signal. This gives it some time to "clear" the operation. - sleepIfRunningAgainstService(30000); - } - - /** - * Tests that a Key Vault can be pre-restored from a backup. - */ - @SuppressWarnings("ConstantConditions") - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginPreRestore(HttpClient httpClient) { - getAsyncClient(httpClient, false); - - StepVerifier.create(setPlaybackPollerFluxPollInterval(asyncClient.beginBackup(blobStorageUrl, sasToken)).last() - .flatMap(AsyncPollResponse::getFinalResult) - .map(backupBlobUri -> { - assertNotNull(backupBlobUri); - assertTrue(backupBlobUri.startsWith(blobStorageUrl)); - - return backupBlobUri; - }) - .map(backupBlobUri -> asyncClient.beginPreRestore(backupBlobUri, sasToken) - .last() - .map(AsyncPollResponse::getValue))) - .assertNext(Assertions::assertNotNull) - .verifyComplete(); - - // For some reason, the service might still think a restore operation is running even after returning a success - // signal. This gives it some time to "clear" the operation. - sleepIfRunningAgainstService(30000); - } - - /** - * Tests that a key can be restored from a backup. - */ - @SuppressWarnings("ConstantConditions") - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginSelectiveKeyRestore(HttpClient httpClient) { - KeyClient keyClient - = new KeyClientBuilder().vaultUrl(getEndpoint()).pipeline(getPipeline(httpClient, false)).buildClient(); - - String keyName = testResourceNamer.randomName("backupKey", 20); - CreateRsaKeyOptions rsaKeyOptions - = new CreateRsaKeyOptions(keyName).setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) - .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)); - - KeyVaultKey createdKey = keyClient.createRsaKey(rsaKeyOptions); - - getAsyncClient(httpClient, false); - - StepVerifier.create(setPlaybackPollerFluxPollInterval(asyncClient.beginBackup(blobStorageUrl, sasToken)).last() - .flatMap(AsyncPollResponse::getFinalResult) - .map(backupBlobUri -> { - assertNotNull(backupBlobUri); - assertTrue(backupBlobUri.startsWith(blobStorageUrl)); - - return backupBlobUri; - }) - .map(backupBlobUri -> asyncClient.beginSelectiveKeyRestore(createdKey.getName(), backupBlobUri, sasToken) - .last() - .map(AsyncPollResponse::getValue))) - .assertNext(Assertions::assertNotNull) - .verifyComplete(); - - // For some reason, the service might still think a restore operation is running even after returning a success - // signal. This gives it some time to "clear" the operation. - sleepIfRunningAgainstService(30000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilderTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilderTest.java deleted file mode 100644 index 41c900890a81..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilderTest.java +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Header; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -import java.time.Duration; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultBackupClientBuilderTest { - private String vaultUrl; - private String blobStorageUrl; - private String sasToken; - private KeyVaultAdministrationServiceVersion serviceVersion; - - @BeforeEach - public void setUp() { - vaultUrl = "https://key-vault-url.vault.azure.net/"; - blobStorageUrl = "https://testaccount.blob.core.windows.net/backup"; - sasToken = "someSasToken"; - serviceVersion = KeyVaultAdministrationServiceVersion.getLatest(); - } - - @Test - public void buildSyncClientTest() { - KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(keyVaultBackupClient); - assertEquals(KeyVaultBackupClient.class.getSimpleName(), keyVaultBackupClient.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientUsingDefaultApiVersionTest() { - KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(keyVaultBackupClient); - assertEquals(KeyVaultBackupClient.class.getSimpleName(), keyVaultBackupClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientTest() { - KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(keyVaultBackupAsyncClient); - assertEquals(KeyVaultBackupAsyncClient.class.getSimpleName(), - keyVaultBackupAsyncClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientUsingDefaultApiVersionTest() { - KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(keyVaultBackupAsyncClient); - assertEquals(KeyVaultBackupAsyncClient.class.getSimpleName(), - keyVaultBackupAsyncClient.getClass().getSimpleName()); - } - - @Test - public void emptyVaultUrlThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new KeyVaultBackupClientBuilder().vaultUrl("")); - } - - @Test - public void nullCredentialThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> new KeyVaultBackupClientBuilder().credential(null)); - } - - @Test - public void clientOptionsIsPreferredOverLogOptions() { - KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) - .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ZERO))) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("aNewApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> keyVaultBackupClient.beginBackup(blobStorageUrl, sasToken)); - } - - @Test - public void applicationIdFallsBackToLogOptions() { - KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ZERO))) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("anOldApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> keyVaultBackupClient.beginBackup(blobStorageUrl, sasToken)); - } - - @Test - public void clientOptionHeadersAreAddedLast() { - KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .clientOptions( - new ClientOptions().setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) - .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ZERO))) - .httpClient(httpRequest -> { - assertEquals("custom", httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT)); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> keyVaultBackupClient.beginBackup(blobStorageUrl, sasToken)); - } - - @Test - public void bothRetryOptionsAndRetryPolicySet() { - assertThrows(IllegalStateException.class, - () -> new KeyVaultBackupClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient()); - } - - // This tests the policy is in the right place because if it were added per retry, it would be after the credentials - // and auth would fail because we changed a signed header. - @Test - public void addPerCallPolicy() { - KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = new KeyVaultBackupClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .addPolicy(new TestUtils.PerCallPolicy()) - .addPolicy(new TestUtils.PerRetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - HttpPipeline pipeline = keyVaultBackupAsyncClient.getHttpPipeline(); - - int retryPolicyPosition = -1, perCallPolicyPosition = -1, perRetryPolicyPosition = -1; - - for (int i = 0; i < pipeline.getPolicyCount(); i++) { - if (pipeline.getPolicy(i).getClass() == RetryPolicy.class) { - retryPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerCallPolicy.class) { - perCallPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerRetryPolicy.class) { - perRetryPolicyPosition = i; - } - } - - assertTrue(perCallPolicyPosition != -1); - assertTrue(perCallPolicyPosition < retryPolicyPosition); - assertTrue(retryPolicyPosition < perRetryPolicyPosition); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupClientTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupClientTest.java deleted file mode 100644 index 4de7d51be529..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupClientTest.java +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.http.HttpClient; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; -import com.azure.security.keyvault.keys.KeyClient; -import com.azure.security.keyvault.keys.KeyClientBuilder; -import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; -import com.azure.security.keyvault.keys.models.KeyVaultKey; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultBackupClientTest extends KeyVaultBackupClientTestBase { - private KeyVaultBackupClient client; - - private void getClient(HttpClient httpClient, boolean forCleanup) { - client - = getClientBuilder( - buildSyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - forCleanup).buildClient(); - } - - private HttpClient buildSyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertSync().build(); - } - - /** - * Tests that a Key Vault can be backed up. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginBackup(HttpClient httpClient) { - getClient(httpClient, false); - - SyncPoller backupPoller - = setPlaybackSyncPollerPollInterval(client.beginBackup(blobStorageUrl, sasToken)); - PollResponse pollResponse = backupPoller.waitForCompletion(); - - assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); - - String backupBlobUri = backupPoller.getFinalResult(); - - assertNotNull(backupBlobUri); - assertTrue(backupBlobUri.startsWith(blobStorageUrl)); - } - - /** - * Tests that a Key Vault can be pre-backed up. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginPreBackup(HttpClient httpClient) { - getClient(httpClient, false); - - SyncPoller backupPoller - = setPlaybackSyncPollerPollInterval(client.beginPreBackup(blobStorageUrl, sasToken)); - PollResponse pollResponse = backupPoller.waitForCompletion(); - - assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); - - String backupBlobUri = backupPoller.getFinalResult(); - - assertNull(backupBlobUri); - } - - /** - * Tests that a Key Vault can be restored from a backup. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginRestore(HttpClient httpClient) { - getClient(httpClient, false); - - // Create a backup - SyncPoller backupPoller - = setPlaybackSyncPollerPollInterval(client.beginBackup(blobStorageUrl, sasToken)); - PollResponse pollResponse = backupPoller.waitForCompletion(); - - assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); - - // Restore the backup - String backupFolderUrl = backupPoller.getFinalResult(); - SyncPoller restorePoller - = setPlaybackSyncPollerPollInterval(client.beginRestore(backupFolderUrl, sasToken)); - - restorePoller.waitForCompletion(); - - PollResponse restoreResponse = restorePoller.poll(); - - assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, restoreResponse.getStatus()); - - // For some reason, the service might still think a restore operation is running even after returning a success - // signal. This gives it some time to "clear" the operation. - sleepIfRunningAgainstService(30000); - } - - /** - * Tests that a Key Vault can be pre-restored from a backup. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginPreRestore(HttpClient httpClient) { - getClient(httpClient, false); - - // Create a backup - SyncPoller backupPoller - = setPlaybackSyncPollerPollInterval(client.beginBackup(blobStorageUrl, sasToken)); - PollResponse backupPollResponse = backupPoller.waitForCompletion(); - - assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, backupPollResponse.getStatus()); - - // Restore the backup - String backupFolderUrl = backupPoller.getFinalResult(); - SyncPoller restorePoller - = setPlaybackSyncPollerPollInterval(client.beginPreRestore(backupFolderUrl, sasToken)); - PollResponse restorePollResponse = restorePoller.waitForCompletion(); - - assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, restorePollResponse.getStatus()); - - // For some reason, the service might still think a restore operation is running even after returning a success - // signal. This gives it some time to "clear" the operation. - sleepIfRunningAgainstService(30000); - } - - /** - * Tests that a key can be restored from a backup. - */ - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void beginSelectiveKeyRestore(HttpClient httpClient) { - KeyClient keyClient - = new KeyClientBuilder().vaultUrl(getEndpoint()).pipeline(getPipeline(httpClient, false)).buildClient(); - - String keyName = testResourceNamer.randomName("backupKey", 20); - CreateRsaKeyOptions rsaKeyOptions - = new CreateRsaKeyOptions(keyName).setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) - .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)); - - KeyVaultKey createdKey = keyClient.createRsaKey(rsaKeyOptions); - - getClient(httpClient, false); - - // Create a backup - SyncPoller backupPoller - = setPlaybackSyncPollerPollInterval(client.beginBackup(blobStorageUrl, sasToken)); - PollResponse backupPollResponse = backupPoller.waitForCompletion(); - - assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, backupPollResponse.getStatus()); - - // Restore one key from said backup - String backupFolderUrl = backupPoller.getFinalResult(); - SyncPoller selectiveKeyRestorePoller - = setPlaybackSyncPollerPollInterval( - client.beginSelectiveKeyRestore(createdKey.getName(), backupFolderUrl, sasToken)); - PollResponse restorePollResponse - = selectiveKeyRestorePoller.waitForCompletion(); - - assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, restorePollResponse.getStatus()); - - // For some reason, the service might still think a restore operation is running even after returning a success - // signal. This gives it some time to "clear" the operation. - sleepIfRunningAgainstService(30000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupClientTestBase.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupClientTestBase.java deleted file mode 100644 index 5270a92f83a2..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultBackupClientTestBase.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.http.HttpClient; -import com.azure.core.util.Configuration; -import com.azure.storage.blob.BlobServiceClient; -import com.azure.storage.blob.BlobServiceClientBuilder; -import com.azure.storage.common.StorageSharedKeyCredential; -import com.azure.storage.common.sas.AccountSasPermission; -import com.azure.storage.common.sas.AccountSasResourceType; -import com.azure.storage.common.sas.AccountSasService; -import com.azure.storage.common.sas.AccountSasSignatureValues; -import org.junit.jupiter.api.Test; - -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -public abstract class KeyVaultBackupClientTestBase extends KeyVaultAdministrationClientTestBase { - protected final String blobStorageUrl = IS_MANAGED_HSM_DEPLOYED - ? getStorageEndpoint() + Configuration.getGlobalConfiguration().get("BLOB_CONTAINER_NAME") - : "https://tb5d8675f0aa83a18prim.blob.core.windows.net/backup"; - protected final String sasToken = IS_MANAGED_HSM_DEPLOYED ? generateSasToken() : "REDACTED"; - - KeyVaultBackupClientBuilder getClientBuilder(HttpClient httpClient, boolean forCleanup) { - return new KeyVaultBackupClientBuilder().vaultUrl(getEndpoint()).pipeline(getPipeline(httpClient, forCleanup)); - } - - @Test - public abstract void beginBackup(HttpClient httpClient); - - @Test - public abstract void beginPreBackup(HttpClient httpClient); - - @Test - public abstract void beginRestore(HttpClient httpClient); - - @Test - public abstract void beginPreRestore(HttpClient httpClient); - - @Test - public abstract void beginSelectiveKeyRestore(HttpClient httpClient); - - private static String getStorageEndpoint() { - String accountName = Configuration.getGlobalConfiguration().get("BLOB_STORAGE_ACCOUNT_NAME"); - - return "https://" + accountName + ".blob." - + Configuration.getGlobalConfiguration().get("KEYVAULT_STORAGE_ENDPOINT_SUFFIX") + "/"; - } - - private static String generateSasToken() { - String accountName = Configuration.getGlobalConfiguration().get("BLOB_STORAGE_ACCOUNT_NAME"); - String accountKey = Configuration.getGlobalConfiguration().get("BLOB_PRIMARY_STORAGE_ACCOUNT_KEY"); - - BlobServiceClient blobServiceClient - = new BlobServiceClientBuilder().credential(new StorageSharedKeyCredential(accountName, accountKey)) - .endpoint(getStorageEndpoint()) - .buildClient(); - - AccountSasSignatureValues accountSasSignatureValues = new AccountSasSignatureValues( - OffsetDateTime.of(2050, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC), AccountSasPermission.parse("rwdlacuptfx"), - AccountSasService.parse("b"), AccountSasResourceType.parse("sco")); - - return blobServiceClient.generateAccountSas(accountSasSignatureValues); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java deleted file mode 100644 index 3b4a377a0613..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java +++ /dev/null @@ -1,661 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration; - -import com.azure.core.credential.AccessToken; -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.TokenRequestContext; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpMethod; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.test.SyncAsyncExtension; -import com.azure.core.test.annotation.SyncAsyncTest; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.Base64Util; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.security.keyvault.administration.implementation.KeyVaultCredentialPolicy; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; -import java.util.stream.Stream; - -import static com.azure.core.http.HttpHeaderName.AUTHORIZATION; -import static com.azure.core.util.CoreUtils.isNullOrEmpty; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.SAME_THREAD) -public class KeyVaultCredentialPolicyTest { - private static final String AUTHENTICATE_HEADER - = "Bearer authorization=\"https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd022db57\", " - + "resource=\"https://vault.azure.net\""; - private static final String AUTHENTICATE_HEADER_WITH_CLAIMS - = "Bearer realm=\"\", authorization_uri=\"https://login.microsoftonline.com/common/oauth2/authorize\", " - + "error=\"insufficient_claims\", " - + "claims=\"eyJhY2Nlc3NfdG9rZW4iOnsiYWNycyI6eyJlc3NlbnRpYWwiOnRydWUsInZhbHVlIjoiY3AxIn19fQ==\""; - private static final String DECODED_CLAIMS = "{\"access_token\":{\"acrs\":{\"essential\":true,\"value\":\"cp1\"}}}"; - private static final String BEARER = "Bearer"; - private static final String BODY = "this is a sample body"; - private static final Flux BODY_FLUX = Flux.defer( - () -> Flux.fromStream(Stream.of(BODY.split("")).map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))))); - private static final String FAKE_ENCODED_CREDENTIAL - = Base64Util.encodeToString("user:fakePasswordPlaceholder".getBytes(StandardCharsets.UTF_8)); - private static final List> BASE_ASSERTIONS = Arrays.asList( - tokenRequestContext -> !tokenRequestContext.getScopes().isEmpty(), - tokenRequestContext -> !isNullOrEmpty(tokenRequestContext.getTenantId()), TokenRequestContext::isCaeEnabled); - - private HttpResponse simpleResponse; - private HttpResponse unauthorizedHttpResponseWithWrongStatusCode; - private HttpResponse unauthorizedHttpResponseWithHeader; - private HttpResponse unauthorizedHttpResponseWithoutHeader; - private HttpResponse unauthorizedHttpResponseWithHeaderAndClaims; - private HttpPipelineCallContext callContext; - private HttpPipelineCallContext differentScopeContext; - private HttpPipelineCallContext testContext; - private HttpPipelineCallContext bodyContext; - private HttpPipelineCallContext bodyFluxContext; - private TokenCredential credential; - - private static HttpPipelineCallContext createCallContext(HttpRequest request, Context context) { - AtomicReference callContextReference = new AtomicReference<>(); - - HttpPipeline callContextCreator = new HttpPipelineBuilder().policies((callContext, next) -> { - callContextReference.set(callContext); - - return next.process(); - }).httpClient(ignored -> Mono.empty()).build(); - - callContextCreator.sendSync(request, context); - - return callContextReference.get(); - } - - @BeforeEach - public void setup() { - HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net"); - HttpRequest requestWithDifferentScope = new HttpRequest(HttpMethod.GET, "https://mytest.azurecr.io"); - - Context bodyContextContext = new Context("KeyVaultCredentialPolicyStashedBody", BinaryData.fromString(BODY)) - .addData("KeyVaultCredentialPolicyStashedContentLength", "21"); - - Context bodyFluxContextContext = new Context("KeyVaultCredentialPolicyStashedBody", BODY_FLUX) - .addData("KeyVaultCredentialPolicyStashedContentLength", "21"); - - MockHttpResponse simpleResponse - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 200); - - MockHttpResponse unauthorizedResponseWithWrongStatusCode - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 500); - - MockHttpResponse unauthorizedResponseWithoutHeader - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 401); - - MockHttpResponse unauthorizedResponseWithHeader - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 401, - new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, AUTHENTICATE_HEADER)); - - MockHttpResponse unauthorizedResponseWithHeaderAndClaims - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 401, - new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, AUTHENTICATE_HEADER_WITH_CLAIMS)); - - this.simpleResponse = simpleResponse; - this.unauthorizedHttpResponseWithWrongStatusCode = unauthorizedResponseWithWrongStatusCode; - this.unauthorizedHttpResponseWithHeader = unauthorizedResponseWithHeader; - this.unauthorizedHttpResponseWithoutHeader = unauthorizedResponseWithoutHeader; - this.unauthorizedHttpResponseWithHeaderAndClaims = unauthorizedResponseWithHeaderAndClaims; - this.callContext = createCallContext(request, Context.NONE); - this.differentScopeContext = createCallContext(requestWithDifferentScope, Context.NONE); - this.testContext = createCallContext(request, Context.NONE); - this.bodyContext = createCallContext(request, bodyContextContext); - this.bodyFluxContext = createCallContext(request, bodyFluxContextContext); - // Can't use BasicAuthenticationCredential until the following PR is merged: - // https://github.com/Azure/azure-sdk-for-java/pull/42238 - this.credential = tokenRequestContext -> Mono - .fromCallable(() -> new AccessToken(FAKE_ENCODED_CREDENTIAL, OffsetDateTime.MAX.minusYears(1))); - } - - @AfterEach - public void cleanup() { - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void onNon401ErrorResponse() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(unauthorizedHttpResponseWithWrongStatusCode)) - .build(); - - SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - assertNull(this.callContext.getHttpRequest().getHeaders().get(AUTHORIZATION)); - - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void on401UnauthorizedResponseWithHeader() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(unauthorizedHttpResponseWithHeader)) - .build(); - - SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - assertNotNull(this.callContext.getHttpRequest().getHeaders().get(AUTHORIZATION)); - - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void onChallengeCredentialPolicy() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.callContext, this.unauthorizedHttpResponseWithHeader), - () -> onChallengeAndClearCache(policy, this.callContext, this.unauthorizedHttpResponseWithHeader)); - - // Validate that the onChallengeSync ran successfully. - assertTrue(onChallenge); - - String tokenValue = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - } - - @Test - public void onAuthorizeRequestChallengeCachePresent() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - StepVerifier.create(onChallengeAndClearCache(policy, this.callContext, unauthorizedHttpResponseWithHeader) // Challenge cache created - .then(policy.authorizeRequest(this.testContext))) // Challenge cache used - .verifyComplete(); - - String tokenValue = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - } - - @Test - public void onAuthorizeRequestChallengeCachePresentSync() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - // Challenge cache created - onChallengeAndClearCacheSync(policy, this.callContext, unauthorizedHttpResponseWithHeader); - // Challenge cache used - policy.authorizeRequestSync(this.testContext); - - String tokenValue = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - } - - @Test - public void onAuthorizeRequestChallengeCachePresentWithClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - StepVerifier.create(policy.authorizeRequestOnChallenge(this.callContext, // Challenge cache created - this.unauthorizedHttpResponseWithHeader).flatMap(authorized -> { - if (authorized) { - String firstToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(firstToken.isEmpty()); - assertTrue(firstToken.startsWith(BEARER)); - - testCredential.replaceAssertion( - tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), 3); - - return policy.authorizeRequestOnChallenge(this.callContext, // Challenge with claims received - this.unauthorizedHttpResponseWithHeaderAndClaims).map(ignored -> firstToken); - } else { - return Mono.just(""); - } - })).assertNext(firstToken -> { - String newToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(newToken.isEmpty()); - assertTrue(newToken.startsWith(BEARER)); - - assertNotEquals(firstToken, newToken); - }).verifyComplete(); - - KeyVaultCredentialPolicy.clearCache(); - } - - @Test - public void onAuthorizeRequestChallengeNoCachePresentWithClaims() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - StepVerifier.create(policy.authorizeRequestOnChallenge(this.callContext, // Challenge cache created - this.unauthorizedHttpResponseWithHeaderAndClaims)).assertNext(result -> { - assertFalse(result); - assertNull(this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); - }).verifyComplete(); - - KeyVaultCredentialPolicy.clearCache(); - } - - @Test - public void onAuthorizeRequestChallengeCachePresentWithClaimsSync() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - // Challenge cache created - assertTrue(policy.authorizeRequestOnChallengeSync(this.callContext, this.unauthorizedHttpResponseWithHeader)); - - String firstToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(firstToken.isEmpty()); - assertTrue(firstToken.startsWith(BEARER)); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - // Challenge with claims received - assertTrue( - policy.authorizeRequestOnChallengeSync(this.callContext, this.unauthorizedHttpResponseWithHeaderAndClaims)); - - String newToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(newToken.isEmpty()); - assertTrue(newToken.startsWith(BEARER)); - - assertNotEquals(firstToken, newToken); - - KeyVaultCredentialPolicy.clearCache(); - } - - @Test - public void onAuthorizeRequestChallengeNoCachePresentWithClaimsSync() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - // Challenge with claims received - assertFalse( - policy.authorizeRequestOnChallengeSync(this.callContext, this.unauthorizedHttpResponseWithHeaderAndClaims)); - assertNull(this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); - - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void onAuthorizeRequestNoCache() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - // No challenge cache to use - SyncAsyncExtension.execute(() -> policy.authorizeRequestSync(this.callContext), - () -> policy.authorizeRequest(this.callContext)); - - assertNull(this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); - } - - @SyncAsyncTest - public void testSetContentLengthHeader() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.bodyContext, this.unauthorizedHttpResponseWithHeader), - () -> onChallengeAndClearCache(policy, this.bodyFluxContext, this.unauthorizedHttpResponseWithHeader)); - - // Validate that the onChallengeSync ran successfully. - assertTrue(onChallenge); - - HttpHeaders headers = this.bodyFluxContext.getHttpRequest().getHeaders(); - String tokenValue = headers.getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - assertEquals("21", headers.getValue(HttpHeaderName.CONTENT_LENGTH)); - - HttpHeaders syncHeaders = this.bodyContext.getHttpRequest().getHeaders(); - String syncTokenValue = headers.getValue(AUTHORIZATION); - assertFalse(syncTokenValue.isEmpty()); - assertTrue(syncTokenValue.startsWith(BEARER)); - assertEquals("21", syncHeaders.getValue(HttpHeaderName.CONTENT_LENGTH)); - } - - @SyncAsyncTest - public void onAuthorizeRequestNoScope() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.callContext, this.unauthorizedHttpResponseWithoutHeader), - () -> onChallengeAndClearCache(policy, this.callContext, this.unauthorizedHttpResponseWithoutHeader)); - - assertFalse(onChallenge); - } - - @Test - public void onAuthorizeRequestDifferentScope() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - assertThrows(RuntimeException.class, () -> onChallengeAndClearCacheSync(policy, this.differentScopeContext, - this.unauthorizedHttpResponseWithHeader)); - - StepVerifier - .create( - onChallengeAndClearCache(policy, this.differentScopeContext, this.unauthorizedHttpResponseWithHeader)) - .verifyErrorMessage("The challenge resource 'https://vault.azure.net/.default' does not match the " - + "requested domain. If you wish to disable this check for your client, pass 'true' to the " - + "SecretClientBuilder.disableChallengeResourceVerification() method when building it. See " - + "https://aka.ms/azsdk/blog/vault-uri for more information."); - } - - @SyncAsyncTest - public void onAuthorizeRequestDifferentScopeVerifyFalse() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, true); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.differentScopeContext, - this.unauthorizedHttpResponseWithHeader), - () -> onChallengeAndClearCache(policy, this.differentScopeContext, - this.unauthorizedHttpResponseWithHeader)); - - assertTrue(onChallenge); - } - - // Normal flow: 401 Unauthorized -> 200 OK -> 401 Unauthorized with claims -> 200 OK - @SyncAsyncTest - public void processMultipleResponses() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - simpleResponse, - unauthorizedHttpResponseWithHeaderAndClaims, - simpleResponse }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String firstToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first response was unauthorized and a token was set on the request. - assertNotNull(firstToken); - // On a second attempt, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - // On receiving an unauthorized response with claims, the token should be updated and a new attempt to make the - // original request should be made. - - HttpResponse newResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // A new token was fetched using the response with claims and set on the request. - assertNotNull(newToken); - // The token was updated. - assertNotEquals(firstToken, newToken); - // A subsequent request was successful. - assertEquals(simpleResponse, newResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - // Edge case: 401 Unauthorized -> 200 OK -> 401 Unauthorized with claims -> 401 Unauthorized with claims - @SyncAsyncTest - public void processConsecutiveResponsesWithClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - simpleResponse, - unauthorizedHttpResponseWithHeaderAndClaims, - // If a second consecutive unauthorized response with claims is received, it shall be returned as is. - unauthorizedHttpResponseWithHeaderAndClaims, }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String firstToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first response was unauthorized and a token was set on the request - assertNotNull(firstToken); - // On a second attempt, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - HttpResponse newResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // A new token was fetched using the first response with claims and set on the request - assertNotEquals(firstToken, newToken); - // A subsequent request was unsuccessful. - assertEquals(unauthorizedHttpResponseWithHeaderAndClaims, newResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - // Edge case: 401 Unauthorized -> 200 OK -> 401 Unauthorized with claims -> 401 Unauthorized - @SyncAsyncTest - public void process401WithoutClaimsAfter401WithClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - simpleResponse, - unauthorizedHttpResponseWithHeaderAndClaims, - // If a second consecutive unauthorized response is received, it shall be returned as is. - unauthorizedHttpResponseWithHeader }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String firstToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first response was unauthorized and a token was set on the request - assertNotNull(firstToken); - // On a second attempt, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - HttpResponse newResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // A new token was fetched using the first response with claims and set on the request - assertNotEquals(firstToken, newToken); - // A subsequent request was unsuccessful. - assertEquals(unauthorizedHttpResponseWithHeader, newResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - // Edge case: 401 Unauthorized -> 401 Unauthorized with claims -> 200 OK - @SyncAsyncTest - public void process401WithClaimsAfter401WithoutClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)); - final String[] firstToken = new String[1]; - - testCredential.addAssertion(tokenRequestContext -> { - // This will ensure that that the first request does not contains claims, but the second does after - // receiving a 401 response with a challenge with claims. - testCredential.replaceAssertion( - anotherTokenRequestContext -> DECODED_CLAIMS.equals(anotherTokenRequestContext.getClaims()), 3); - - // We will also store the value of the first credential before it changes on a second call - firstToken[0] = Base64Util.encodeToString(testCredential.getCredential().getBytes(StandardCharsets.UTF_8)); - - assertNotNull(firstToken[0]); - - return tokenRequestContext.getClaims() == null; - }); - - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - unauthorizedHttpResponseWithHeaderAndClaims, - simpleResponse }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first unauthorized response caused a token to be set on the request, then the token was updated on a - // subsequent unauthorized response with claims. - assertNotEquals(firstToken[0], newToken); - // Finally, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - private Mono onChallengeAndClearCache(KeyVaultCredentialPolicy policy, HttpPipelineCallContext callContext, - HttpResponse unauthorizedHttpResponse) { - Mono onChallenge = policy.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponse); - - KeyVaultCredentialPolicy.clearCache(); - - return onChallenge; - } - - private boolean onChallengeAndClearCacheSync(KeyVaultCredentialPolicy policy, HttpPipelineCallContext callContext, - HttpResponse unauthorizedHttpResponse) { - boolean onChallengeSync = policy.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponse); - - KeyVaultCredentialPolicy.clearCache(); - - return onChallengeSync; - } - - private static final class MutableTestCredential implements TokenCredential { - private String credential; - private List> assertions; - - private MutableTestCredential(List> assertions) { - this.credential = new Random().toString(); - this.assertions = assertions; - } - - /** - * @throws RuntimeException if any of the assertions fail. - */ - @Override - public Mono getToken(TokenRequestContext requestContext) { - if (requestContext.isCaeEnabled() && requestContext.getClaims() != null) { - credential = new Random().toString(); - } - - String encodedCredential = Base64Util.encodeToString(credential.getBytes(StandardCharsets.UTF_8)); - - for (int i = 0; i < assertions.size(); i++) { - if (!assertions.get(i).apply(requestContext)) { - return Mono.error(new RuntimeException(String.format("Assertion number %d failed", i))); - } - } - - return Mono.fromCallable(() -> new AccessToken(encodedCredential, OffsetDateTime.MAX.minusYears(1))); - } - - private MutableTestCredential setAssertions(List> assertions) { - this.assertions = assertions; - - return this; - } - - private MutableTestCredential addAssertion(Function assertion) { - assertions.add(assertion); - - return this; - } - - private MutableTestCredential replaceAssertion(Function assertion, int index) { - assertions.set(index, assertion); - - return this; - } - - private String getCredential() { - return this.credential; - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClientTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClientTest.java deleted file mode 100644 index 635ef690983c..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClientTest.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.http.HttpClient; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.test.StepVerifier; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultSettingsAsyncClientTest extends KeyVaultSettingsClientTestBase { - private KeyVaultSettingsAsyncClient asyncClient; - - private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertAsync().build(); - } - - private void getClient(HttpClient httpClient, boolean forCleanup) { - asyncClient - = getClientBuilder( - buildAsyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - forCleanup).buildAsyncClient(); - if (!interceptorManager.isLiveMode()) { - // Remove `id` and `name` sanitizers from the list of common sanitizers. - interceptorManager.removeSanitizers("AZSDK3430", "AZSDK3493"); - } - } - - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void getSettings(HttpClient httpClient) { - getClient(httpClient, false); - - StepVerifier.create(asyncClient.getSettings()).assertNext(getSettingsResult -> { - assertNotNull(getSettingsResult); - assertTrue(getSettingsResult.getSettings().size() > 0); - - for (KeyVaultSetting setting : getSettingsResult.getSettings()) { - assertNotNull(setting); - assertNotNull(setting.getName()); - assertNotNull(setting.getType()); - } - }).verifyComplete(); - } - - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void getSetting(HttpClient httpClient) { - getClient(httpClient, false); - - String settingName = "AllowKeyManagementOperationsThroughARM"; - - StepVerifier.create(asyncClient.getSetting(settingName)).assertNext(setting -> { - assertNotNull(setting); - assertNotNull(setting.getName()); - assertNotNull(setting.getType()); - }).verifyComplete(); - } - - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void updateSetting(HttpClient httpClient) { - getClient(httpClient, false); - - String settingName = "AllowKeyManagementOperationsThroughARM"; - KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); - - StepVerifier.create(asyncClient.getSetting(settingName).flatMap(setting -> { - assertNotNull(setting); - - @SuppressWarnings("ConstantConditions") - boolean originalSettingValue = setting.asBoolean(); - - return asyncClient.updateSetting(settingToUpdate) - .doOnSuccess(updatedSetting -> assertSettingEquals(settingToUpdate, updatedSetting)) - .then(asyncClient.updateSetting(new KeyVaultSetting(settingName, originalSettingValue))); - })).assertNext(Assertions::assertNotNull).verifyComplete(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilderTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilderTest.java deleted file mode 100644 index 846b90fce5b9..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilderTest.java +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Header; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultSettingsClientBuilderTest { - private String vaultUrl; - private KeyVaultAdministrationServiceVersion serviceVersion; - - @BeforeEach - public void setUp() { - vaultUrl = "https://key-vault-url.vault.azure.net/"; - serviceVersion = KeyVaultAdministrationServiceVersion.getLatest(); - } - - @Test - public void buildSyncClientTest() { - KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(keyVaultSettingsClient); - assertEquals(KeyVaultSettingsClient.class.getSimpleName(), keyVaultSettingsClient.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientUsingDefaultApiVersionTest() { - KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(keyVaultSettingsClient); - assertEquals(KeyVaultSettingsClient.class.getSimpleName(), keyVaultSettingsClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientTest() { - KeyVaultSettingsAsyncClient keyVaultAccessControlAsyncClient - = new KeyVaultSettingsClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(keyVaultAccessControlAsyncClient); - assertEquals(KeyVaultSettingsAsyncClient.class.getSimpleName(), - keyVaultAccessControlAsyncClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientUsingDefaultApiVersionTest() { - KeyVaultSettingsAsyncClient keyVaultAccessControlAsyncClient - = new KeyVaultSettingsClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(keyVaultAccessControlAsyncClient); - assertEquals(KeyVaultSettingsAsyncClient.class.getSimpleName(), - keyVaultAccessControlAsyncClient.getClass().getSimpleName()); - } - - @Test - public void emptyVaultUrlThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new KeyVaultSettingsClientBuilder().vaultUrl("")); - } - - @Test - public void nullCredentialThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> new KeyVaultSettingsClientBuilder().credential(null)); - } - - @Test - public void clientOptionsIsPreferredOverLogOptions() { - KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("aNewApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, keyVaultSettingsClient::getSettings); - } - - @Test - public void applicationIdFallsBackToLogOptions() { - KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("anOldApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, keyVaultSettingsClient::getSettings); - } - - @Test - public void clientOptionHeadersAreAddedLast() { - KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .clientOptions( - new ClientOptions().setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) - .httpClient(httpRequest -> { - assertEquals("custom", httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT)); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, keyVaultSettingsClient::getSettings); - } - - @Test - public void bothRetryOptionsAndRetryPolicySpecified() { - assertThrows(RuntimeException.class, - () -> new KeyVaultSettingsClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient()); - } - - // This tests the policy is in the right place because if it were added per retry, it would be after the credentials - // and auth would fail because we changed a signed header. - @Test - public void addPerCallPolicy() { - KeyVaultSettingsAsyncClient keyVaultAccessControlAsyncClient - = new KeyVaultSettingsClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .addPolicy(new TestUtils.PerCallPolicy()) - .addPolicy(new TestUtils.PerRetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - HttpPipeline pipeline = keyVaultAccessControlAsyncClient.getHttpPipeline(); - - int retryPolicyPosition = -1, perCallPolicyPosition = -1, perRetryPolicyPosition = -1; - - for (int i = 0; i < pipeline.getPolicyCount(); i++) { - if (pipeline.getPolicy(i).getClass() == RetryPolicy.class) { - retryPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerCallPolicy.class) { - perCallPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerRetryPolicy.class) { - perRetryPolicyPosition = i; - } - } - - assertTrue(perCallPolicyPosition != -1); - assertTrue(perCallPolicyPosition < retryPolicyPosition); - assertTrue(retryPolicyPosition < perRetryPolicyPosition); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientTest.java deleted file mode 100644 index c4ad89398c2a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientTest.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.http.HttpClient; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultSettingsClientTest extends KeyVaultSettingsClientTestBase { - private KeyVaultSettingsClient client; - - private HttpClient buildSyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertSync().build(); - } - - private void getClient(HttpClient httpClient, boolean forCleanup) { - client - = getClientBuilder( - buildSyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - forCleanup).buildClient(); - if (!interceptorManager.isLiveMode()) { - // Remove `id` and `name` sanitizers from the list of common sanitizers. - interceptorManager.removeSanitizers("AZSDK3430", "AZSDK3493"); - } - } - - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void getSettings(HttpClient httpClient) { - getClient(httpClient, false); - - KeyVaultGetSettingsResult getSettingsResult = client.getSettings(); - - assertNotNull(getSettingsResult); - assertTrue(getSettingsResult.getSettings().size() > 0); - - for (KeyVaultSetting setting : getSettingsResult.getSettings()) { - assertNotNull(setting); - assertNotNull(setting.getName()); - assertNotNull(setting.getType()); - } - } - - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void getSetting(HttpClient httpClient) { - getClient(httpClient, false); - - String settingName = "AllowKeyManagementOperationsThroughARM"; - KeyVaultSetting setting = client.getSetting(settingName); - - assertNotNull(setting); - assertNotNull(setting.getName()); - assertNotNull(setting.getType()); - } - - @ParameterizedTest(name = DISPLAY_NAME) - @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase#createHttpClients") - public void updateSetting(HttpClient httpClient) { - getClient(httpClient, false); - - String settingName = "AllowKeyManagementOperationsThroughARM"; - KeyVaultSetting setting = client.getSetting(settingName); - - assertNotNull(setting); - - @SuppressWarnings("ConstantConditions") - boolean originalSettingValue = setting.asBoolean(); - - KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); - KeyVaultSetting updatedSetting = client.updateSetting(settingToUpdate); - - assertSettingEquals(settingToUpdate, updatedSetting); - - // Cleanup - client.updateSetting(new KeyVaultSetting(settingName, originalSettingValue)); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientTestBase.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientTestBase.java deleted file mode 100644 index 92a00df72556..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientTestBase.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.http.HttpClient; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.administration.models.KeyVaultSetting; -import com.azure.security.keyvault.administration.models.KeyVaultSettingType; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public abstract class KeyVaultSettingsClientTestBase extends KeyVaultAdministrationClientTestBase { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultSettingsClientTestBase.class); - - KeyVaultSettingsClientBuilder getClientBuilder(HttpClient httpClient, boolean forCleanup) { - return new KeyVaultSettingsClientBuilder().vaultUrl(getEndpoint()) - .pipeline(getPipeline(httpClient, forCleanup)); - } - - @Test - public abstract void getSettings(HttpClient httpClient); - - @Test - public abstract void getSetting(HttpClient httpClient); - - @Test - public abstract void updateSetting(HttpClient httpClient); - - static void assertSettingEquals(KeyVaultSetting keyVaultSetting1, KeyVaultSetting keyVaultSetting2) { - assertEquals(keyVaultSetting1.getName(), keyVaultSetting2.getName()); - assertEquals(keyVaultSetting1.getType(), keyVaultSetting2.getType()); - - if (keyVaultSetting1.getType() == KeyVaultSettingType.BOOLEAN) { - assertEquals(keyVaultSetting1.asBoolean(), keyVaultSetting2.asBoolean()); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/TestUtils.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/TestUtils.java deleted file mode 100644 index 9761a9a70185..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/TestUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.administration; - -import com.azure.core.credential.AccessToken; -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.TokenRequestContext; -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpPipelineNextPolicy; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.HttpPipelinePolicy; -import reactor.core.publisher.Mono; - -import java.time.OffsetDateTime; - -/** - * Common test utilities. - */ -public final class TestUtils { - /** - * Private constructor so this class cannot be instantiated. - */ - private TestUtils() { - } - - static class PerCallPolicy implements HttpPipelinePolicy { - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - context.getHttpRequest().setHeader("Custom-Header", "Some Value"); - return next.process(); - } - - @Override - public HttpPipelinePosition getPipelinePosition() { - return HttpPipelinePosition.PER_CALL; - } - } - - static class PerRetryPolicy implements HttpPipelinePolicy { - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - context.getHttpRequest().setHeader("Custom-Header", "Some Value"); - return next.process(); - } - } - - static class TestCredential implements TokenCredential { - @Override - public Mono getToken(TokenRequestContext request) { - return Mono.just(new AccessToken("TestAccessToken", OffsetDateTime.now().plusHours(1))); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/sdk/keyvault/azure-security-keyvault-administration/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker deleted file mode 100644 index 1f0955d450f0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker +++ /dev/null @@ -1 +0,0 @@ -mock-maker-inline diff --git a/sdk/keyvault/azure-security-keyvault-administration/swagger/Update-Codegeneration-disabled.ps1 b/sdk/keyvault/azure-security-keyvault-administration/swagger/Update-Codegeneration-disabled.ps1 deleted file mode 100644 index 38b200a8b3cd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/swagger/Update-Codegeneration-disabled.ps1 +++ /dev/null @@ -1,3 +0,0 @@ -& (Join-Path $PSScriptRoot ".." ".." ".." ".." eng scripts Invoke-Codegeneration.ps1) -Directory $PSScriptRoot -AutorestOptions '--tag=rbac' -& (Join-Path $PSScriptRoot ".." ".." ".." ".." eng scripts Invoke-Codegeneration.ps1) -Directory $PSScriptRoot -AutorestOptions '--tag=backuprestore' -& (Join-Path $PSScriptRoot ".." ".." ".." ".." eng scripts Invoke-Codegeneration.ps1) -Directory $PSScriptRoot -AutorestOptions '--tag=settings' diff --git a/sdk/keyvault/azure-security-keyvault-administration/swagger/autorest.md b/sdk/keyvault/azure-security-keyvault-administration/swagger/autorest.md deleted file mode 100644 index 009d9bd050fc..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/swagger/autorest.md +++ /dev/null @@ -1,115 +0,0 @@ -# Azure Key Vault Administration for Java - -> see https://aka.ms/autorest - -This is the Autorest configuration file for KeyVault Administration. - ---- -## Getting Started -To build the SDK for KeyVault Administration, simply [Install Autorest](https://aka.ms/autorest) and -in this folder, run: - -> `autorest --tag={swagger specification}` - -To see additional help and options, run: - -> `autorest --help` - -### Setup -```ps -npm install -g autorest -``` - -### Generation - -There are three swagger specifications for KeyVault Administration: `rbac`, `backuprestore` and `settings`. -They use the following tags respectively: `--tag=rbac`, `--tag=backuprestore`, `--tag=settings`. - -```ps -cd -autorest --tag={swagger specification} -``` - -e.g. -```ps -cd -autorest --tag=rbac -autorest --tag=backuprestore -autorest --tag=settings -``` - -## Configuration -```yaml -use: '@autorest/java@4.1.42' -output-folder: ../ -java: true -namespace: com.azure.security.keyvault.administration -models-subpackage: implementation.models -custom-types-subpackage: models -enable-sync-stack: true -generate-client-as-impl: true -license-header: MICROSOFT_MIT_SMALL -disable-client-builder: true -required-fields-as-ctor-args: true -include-read-only-in-constructor-args: true -partial-update: true -``` - -### Tag: rbac -These settings apply only when `--tag=rbac` is specified on the command line. - -``` yaml $(tag) == 'rbac' -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af9817c15d688c941cda106758045b5deb9a069/specification/keyvault/data-plane/Microsoft.KeyVault/preview/7.6-preview.1/rbac.json -title: KeyVaultAccessControlClient -custom-types: KeyVaultDataAction,KeyVaultRoleDefinitionType,KeyVaultRoleScope,KeyVaultRoleType -customization-class: src/main/java/RbacCustomizations.java -``` - -#### Enum Renames -``` yaml $(tag) == 'rbac' -directive: - - from: swagger-document - where: $.definitions - transform: > - $.DataAction["x-ms-enum"].name = "KeyVaultDataAction"; - $.RoleDefinitionProperties.properties.type["x-ms-enum"].name = "KeyVaultRoleType"; - $.RoleScope["x-ms-enum"].name = "KeyVaultRoleScope"; - $.RoleDefinition.properties.type["x-ms-enum"].name = "KeyVaultRoleDefinitionType"; -``` - -### Tag: backuprestore -These settings apply only when `--tag=backuprestore` is specified on the command line. - -``` yaml $(tag) == 'backuprestore' -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af9817c15d688c941cda106758045b5deb9a069/specification/keyvault/data-plane/Microsoft.KeyVault/preview/7.6-preview.1/backuprestore.json -title: KeyVaultBackupClient -customization-class: src/main/java/BackupRestoreCustomizations.java -``` - -### Tag: settings -These settings apply only when `--tag=settings` is specified on the command line. - -``` yaml $(tag) == 'settings' -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af9817c15d688c941cda106758045b5deb9a069/specification/keyvault/data-plane/Microsoft.KeyVault/preview/7.6-preview.1/settings.json -title: KeyVaultSettingsClient -custom-types: KeyVaultSettingType -customization-class: src/main/java/SettingsCustomizations.java -``` - -#### Rename SettingTypeEnum to KeyVaultSettingType -``` yaml $(tag) == 'settings' -directive: - - from: swagger-document - where: $.definitions.Setting - transform: > - $.properties.type["x-ms-enum"].name = "KeyVaultSettingType"; -``` - -#### Bug in Autorest Java for required properties that are flattened in operation definition -``` yaml $(tag) == 'settings' -directive: - - from: swagger-document - where: $.definitions.UpdateSettingRequest - transform: > - delete $.required; -``` diff --git a/sdk/keyvault/azure-security-keyvault-administration/swagger/pom.xml b/sdk/keyvault/azure-security-keyvault-administration/swagger/pom.xml deleted file mode 100644 index 1dd3db19a4ae..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/swagger/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - - - com.azure - azure-code-customization-parent - 1.0.0-beta.1 - ../../../parents/azure-code-customization-parent - - - Microsoft Azure Security Key Vault Administration code generation customization - This package contains code generation customization for Microsoft Azure Security Key Vault Administration - - com.azure.tools - azure-security-administration-autorest-customization - 1.0.0-beta.1 - jar - diff --git a/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/AdministrationCustomizations.java b/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/AdministrationCustomizations.java deleted file mode 100644 index 0023a0500015..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/AdministrationCustomizations.java +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -import com.azure.autorest.customization.ClassCustomization; -import com.azure.autorest.customization.Customization; -import com.azure.autorest.customization.Editor; -import com.azure.autorest.customization.LibraryCustomization; -import com.azure.autorest.customization.PackageCustomization; -import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ast.Modifier; -import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; -import org.slf4j.Logger; - -import java.net.MalformedURLException; -import java.net.URL; - -/** - * Contains customizations for Azure Key Vault Administration code generation. - */ -public class AdministrationCustomizations extends Customization { - @Override - public void customize(LibraryCustomization libraryCustomization, Logger logger) { - Editor rawEditor = libraryCustomization.getRawEditor(); - - // Remove unnecessary files. - removeFiles(rawEditor); - - // Customize the client impl classes. - PackageCustomization implPackageCustomization = libraryCustomization.getPackage( - "com.azure.security.keyvault.administration.implementation"); - String implPath = "src/main/java/com/azure/security/keyvault/administration/implementation/"; - - replaceInFile(implPackageCustomization.getClass("KeyVaultClientImpl"), implPath + "KeyVaultClientImpl.java", - new String[] { - "KeyVault", - "private Mono> fullBackupWithResponseAsync", - "private Response fullBackupWithResponse", - "private Mono> preFullBackupWithResponseAsync", - "private Response preFullBackupWithResponse", - "private Mono> preFullRestoreOperationWithResponseAsync", - "private Response preFullRestoreOperationWithResponse", - "private Mono> fullRestoreOperationWithResponseAsync", - "private Response fullRestoreOperationWithResponse", - "private Mono> selectiveKeyRestoreOperationWithResponseAsync", - "private Response selectiveKeyRestoreOperationWithResponse" }, new String[] { - "KeyVaultAdministration", - "public Mono> fullBackupWithResponseAsync", - "public Response fullBackupWithResponse", - "public Mono> preFullBackupWithResponseAsync", - "public Response preFullBackupWithResponse", - "public Mono> preFullRestoreOperationWithResponseAsync", - "public Response preFullRestoreOperationWithResponse", - "public Mono> fullRestoreOperationWithResponseAsync", - "public Response fullRestoreOperationWithResponse", - "public Mono> selectiveKeyRestoreOperationWithResponseAsync", - "public Response selectiveKeyRestoreOperationWithResponse" }); - replaceInFile(implPackageCustomization.getClass("RoleAssignmentsImpl"), implPath + "RoleAssignmentsImpl.java", - new String[] { - "KeyVault", - "private Mono> listForScopeSinglePageAsync", - "private Mono> listForScopeNextSinglePageAsync" }, new String[] { - "KeyVaultAdministration", - "public Mono> listForScopeSinglePageAsync", - "public Mono> listForScopeNextSinglePageAsync" }); - replaceInFile(implPackageCustomization.getClass("RoleDefinitionsImpl"), implPath + "RoleDefinitionsImpl.java", - new String[] { - "KeyVault", - "private Mono> listSinglePageAsync", - "private Mono> listNextSinglePageAsync" }, new String[] { - "KeyVaultAdministration", - "public Mono> listSinglePageAsync", - "public Mono> listNextSinglePageAsync" }); - - // Rename base client impl. - rawEditor.renameFile(implPath + "KeyVaultClientImpl.java", implPath + "KeyVaultAdministrationClientImpl.java"); - - // Change the names of generated - ClassCustomization keyVaultRoleScopeCustomization = libraryCustomization.getPackage( - "com.azure.security.keyvault.administration.models").getClass("KeyVaultRoleScope"); - - customizeKeyVaultRoleScope(keyVaultRoleScopeCustomization); - } - - private static void removeFiles(Editor editor) { - // Remove the next line in favor of renaming to KeyServiceVersion once the TSP spec includes all service - // versions. - editor.removeFile("src/main/java/com/azure/security/keyvault/administration/KeyVaultServiceVersion.java"); - editor.removeFile("src/main/java/com/azure/security/keyvault/administration/KeyVaultAsyncClient.java"); - editor.removeFile("src/main/java/com/azure/security/keyvault/administration/KeyVaultClient.java"); - editor.removeFile("src/main/java/com/azure/security/keyvault/administration/KeyVaultClientBuilder.java"); - editor.removeFile("src/main/java/com/azure/security/keyvault/administration/RoleAssignmentsAsyncClient.java"); - editor.removeFile("src/main/java/com/azure/security/keyvault/administration/RoleAssignmentsClient.java"); - editor.removeFile("src/main/java/com/azure/security/keyvault/administration/RoleDefinitionsAsyncClient.java"); - editor.removeFile("src/main/java/com/azure/security/keyvault/administration/RoleDefinitionsClient.java"); - } - - private static void customizeKeyVaultRoleScope(ClassCustomization classCustomization) { - classCustomization.customizeAst(ast -> { - ast.addImport(IllegalArgumentException.class).addImport(URL.class).addImport(MalformedURLException.class); - - ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get(); - - clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) - .setType("KeyVaultRoleScope") - .addParameter("String", "url") - .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline("/**", - " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", - " * @param url A string representing a URL containing the name of the scope to look for.", - " * @return The corresponding {@link KeyVaultRoleScope}.", - " * @throws IllegalArgumentException If the given {@code url} is malformed.", " */"))) - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", "try {", " return fromString(new URL(url).getPath());", - "} catch (MalformedURLException e) {", " throw new IllegalArgumentException(e);", "}", - "}"))); - - clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) - .setType("KeyVaultRoleScope") - .addParameter("URL", "url") - .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline("/**", - " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", - " * @param url A URL containing the name of the scope to look for.", - " * @return The corresponding {@link KeyVaultRoleScope}.", " */"))) - .setBody(StaticJavaParser.parseBlock("{return fromString(url.getPath());}")); - }); - } - - /** - * This method replaces all the provided strings in the specified file with new strings provided in the latter half - * of the 'strings' parameter. - * - * @param classCustomization The class customization to use to edit the file. - * @param classPath The path to the file to edit. - * @param stringsToReplace The strings to replace. - * @param replacementStrings The strings to replace with. - */ - private static void replaceInFile(ClassCustomization classCustomization, String classPath, - String[] stringsToReplace, String[] replacementStrings) { - - if (stringsToReplace != null && replacementStrings != null) { - // Replace all instances of KeyVaultServiceVersion with KeyVaultAdministrationServiceVersion. We'll remove this - // once the TSP spec includes all service versions. - Editor editor = classCustomization.getEditor(); - String fileContent = editor.getFileContent(classPath); - - // Ensure names has an even length. - if (stringsToReplace.length != replacementStrings.length) { - throw new IllegalArgumentException( - "'stringsToReplace' must have the same number of elements as 'replacementStrings'."); - } - - for (int i = 0; i < stringsToReplace.length; i++) { - fileContent = fileContent.replace(stringsToReplace[i], replacementStrings[i]); - } - - editor.replaceFile(classPath, fileContent); - } else if (stringsToReplace != null || replacementStrings != null) { - throw new IllegalArgumentException( - "'stringsToReplace' must have the same number of elements as 'replacementStrings'."); - } - } - - private static String joinWithNewline(String... lines) { - return String.join("\n", lines); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/tsp-location.yaml b/sdk/keyvault/azure-security-keyvault-administration/tsp-location.yaml index 9ac5ab99988b..3a2d140b1dad 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/tsp-location.yaml +++ b/sdk/keyvault/azure-security-keyvault-administration/tsp-location.yaml @@ -1,9 +1,4 @@ directory: specification/keyvault/Security.KeyVault.Administration -commit: 70672ea0a1a550ee608aa4718598b71550d361df +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 repo: Azure/azure-rest-api-specs -additionalDirectories: -- specification/keyvault/Security.KeyVault.BackupRestore/ -- specification/keyvault/Security.KeyVault.Common/ -- specification/keyvault/Security.KeyVault.RBAC/ -- specification/keyvault/Security.KeyVault.Settings/ -cleanup: true +additionalDirectories: