comment stringlengths 1 45k | method_body stringlengths 23 281k | target_code stringlengths 0 5.16k | method_body_after stringlengths 12 281k | context_before stringlengths 8 543k | context_after stringlengths 8 543k |
|---|---|---|---|---|---|
Same question | public URL getShareUrl() {
String shareURLString = String.format("%s/%s", azureFileStorageClient.getUrl(), shareName);
if (snapshot != null) {
shareURLString = String.format("%s?snapshot=%s", shareURLString, snapshot);
}
try {
return new URL(shareURLString);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), shareURLString), e));
}
} | String shareURLString = String.format("%s/%s", azureFileStorageClient.getUrl(), shareName); | public URL getShareUrl() {
StringBuilder shareURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/").append(shareName);
if (snapshot != null) {
shareURLString.append("?snapshot=").append(snapshot);
}
try {
return new URL(shareURLString.toString());
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), shareURLString), e));
}
} | class ShareAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String snapshot;
/**
* Creates a ShareAsyncClient that sends requests to the storage share at {@link AzureFileStorageImpl
* endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the
* {@code azureFileStorageClient}.
*
* @param client Client that interacts with the service interfaces
* @param shareName Name of the share
*/
ShareAsyncClient(AzureFileStorageImpl client, String shareName, String snapshot) {
Objects.requireNonNull(shareName);
this.shareName = shareName;
this.snapshot = snapshot;
this.azureFileStorageClient = client;
}
/**
* Get the url of the storage share client.
*
* @return the url of the Storage Share.
* @throws RuntimeException If the share is using a malformed URL.
*/
/**
* Constructs a {@link DirectoryAsyncClient} that interacts with the root directory in the share.
*
* <p>If the directory doesn't exist in the share {@link DirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @return a {@link DirectoryAsyncClient} that interacts with the root directory in the share
*/
public DirectoryAsyncClient getRootDirectoryClient() {
return getDirectoryClient("");
}
/**
* Constructs a {@link DirectoryAsyncClient} that interacts with the specified directory.
*
* <p>If the directory doesn't exist in the share {@link DirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @param directoryName Name of the directory
* @return a {@link DirectoryAsyncClient} that interacts with the directory in the share
*/
public DirectoryAsyncClient getDirectoryClient(String directoryName) {
return new DirectoryAsyncClient(azureFileStorageClient, shareName, directoryName, snapshot);
}
/**
* Constructs a {@link FileAsyncClient} that interacts with the specified file.
*
* <p>If the file doesn't exist in the share {@link FileAsyncClient | class ShareAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String snapshot;
/**
* Creates a ShareAsyncClient that sends requests to the storage share at {@link AzureFileStorageImpl
* endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the
* {@code azureFileStorageClient}.
*
* @param client Client that interacts with the service interfaces
* @param shareName Name of the share
*/
ShareAsyncClient(AzureFileStorageImpl client, String shareName, String snapshot) {
Objects.requireNonNull(shareName);
this.shareName = shareName;
this.snapshot = snapshot;
this.azureFileStorageClient = client;
}
/**
* Get the url of the storage share client.
*
* @return the url of the Storage Share.
* @throws RuntimeException If the share is using a malformed URL.
*/
/**
* Constructs a {@link DirectoryAsyncClient} that interacts with the root directory in the share.
*
* <p>If the directory doesn't exist in the share {@link DirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @return a {@link DirectoryAsyncClient} that interacts with the root directory in the share
*/
public DirectoryAsyncClient getRootDirectoryClient() {
return getDirectoryClient("");
}
/**
* Constructs a {@link DirectoryAsyncClient} that interacts with the specified directory.
*
* <p>If the directory doesn't exist in the share {@link DirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @param directoryName Name of the directory
* @return a {@link DirectoryAsyncClient} that interacts with the directory in the share
*/
public DirectoryAsyncClient getDirectoryClient(String directoryName) {
return new DirectoryAsyncClient(azureFileStorageClient, shareName, directoryName, snapshot);
}
/**
* Constructs a {@link FileAsyncClient} that interacts with the specified file.
*
* <p>If the file doesn't exist in the share {@link FileAsyncClient |
The format is like `https://sima.file.core.windows.net/sharename/directoryPath` | public URL getDirectoryUrl() {
String directoryURLString = String.format("%s/%s/%s", azureFileStorageClient.getUrl(),
shareName, directoryPath);
if (snapshot != null) {
directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot);
}
try {
return new URL(directoryURLString);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
}
} | String directoryURLString = String.format("%s/%s/%s", azureFileStorageClient.getUrl(), | public URL getDirectoryUrl() {
StringBuilder directoryURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryURLString.append("?snapshot=").append(snapshot);
}
try {
return new URL(directoryURLString.toString());
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
}
} | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
* @throws RuntimeException If the directory is using a malformed URL.
*/
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
* @throws RuntimeException If the directory is using a malformed URL.
*/
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient |
Instead of doing multiple String::format calls across if statements, why not use a string builder? | public URL getDirectoryUrl() {
String directoryURLString = String.format("%s/%s/%s", azureFileStorageClient.getUrl(),
shareName, directoryPath);
if (snapshot != null) {
directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot);
}
try {
return new URL(directoryURLString);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
}
} | directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot); | public URL getDirectoryUrl() {
StringBuilder directoryURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryURLString.append("?snapshot=").append(snapshot);
}
try {
return new URL(directoryURLString.toString());
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
}
} | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
* @throws RuntimeException If the directory is using a malformed URL.
*/
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
* @throws RuntimeException If the directory is using a malformed URL.
*/
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient |
StringBuilder comment. | public URL getFileUrl() {
String fileURLString = String.format("%s/%s/%s", azureFileStorageClient.getUrl(), shareName, filePath);
if (snapshot != null) {
fileURLString = String.format("%s?snapshot=%s", fileURLString, snapshot);
}
try {
return new URL(fileURLString);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), fileURLString), e));
}
} | fileURLString = String.format("%s?snapshot=%s", fileURLString, snapshot); | public URL getFileUrl() {
StringBuilder fileURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(filePath);
if (snapshot != null) {
fileURLString.append("?snapshot=").append(snapshot);
}
try {
return new URL(fileURLString.toString());
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), fileURLString), e));
}
} | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String filePath;
private final String snapshot;
/**
* Creates a FileAsyncClient that sends requests to the storage file at {@link AzureFileStorageImpl
* endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param filePath Path to the file
* @param snapshot The snapshot of the share
*/
FileAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String filePath, String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(filePath);
this.shareName = shareName;
this.filePath = filePath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage file client.
*
* @return the URL of the storage file client
* @throws RuntimeException If the file is using a malformed URL.
*/
/**
* Creates a file in the storage account and returns a response of {@link FileInfo} to interact with it.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create the file with size 1KB.</p>
*
* {@codesnippet com.azure.storage.file.fileClient.create}
*
* <p>For more information, see the
* <a href="https:
*
* @param maxSize The maximum size in bytes for the file, up to 1 TiB.
* @return A response containing the file info and the status of creating the file.
* @throws StorageException If the file has already existed, the parent directory does not exist or fileName is an
* invalid resource name.
*/
public Mono<FileInfo> create(long maxSize) {
return createWithResponse(maxSize, null, null, null, null).flatMap(FluxUtil::toMono);
}
/**
* Creates a file in the storage account and returns a response of FileInfo to interact with it.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create the file with length of 1024 bytes, some headers, file smb properties and metadata.</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.createWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param maxSize The maximum size in bytes for the file, up to 1 TiB.
* @param httpHeaders The user settable file http headers.
* @param smbProperties The user settable file smb properties.
* @param filePermission The file permission of the file.
* @param metadata Optional name-value pairs associated with the file as metadata.
* @return A response containing the {@link FileInfo file info} and the status of creating the file.
* @throws StorageException If the directory has already existed, the parent directory does not exist or directory
* is an invalid resource name.
*/
public Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders,
FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata) {
return withContext(context ->
createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, metadata, context));
}
Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders,
FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) {
smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties;
filePermissionAndKeyHelper(filePermission, smbProperties.getFilePermissionKey());
filePermission = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT);
String filePermissionKey = smbProperties.getFilePermissionKey();
String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE);
String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW);
String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW);
return postProcessResponse(azureFileStorageClient.files()
.createWithRestResponseAsync(shareName, filePath, maxSize, fileAttributes, fileCreationTime,
fileLastWriteTime, null, metadata, filePermission, filePermissionKey, httpHeaders, context))
.map(this::createFileInfoResponse);
}
/**
* Copies a blob or file to a destination file within the storage account.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Copy file from source url to the {@code resourcePath} </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.startCopy
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length.
* @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the
* naming rules.
* @return The {@link FileCopyInfo file copy info}.
* @see <a href="https:
*/
public Mono<FileCopyInfo> startCopy(String sourceUrl, Map<String, String> metadata) {
return startCopyWithResponse(sourceUrl, metadata).flatMap(FluxUtil::toMono);
}
/**
* Copies a blob or file to a destination file within the storage account.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Copy file from source url to the {@code resourcePath} </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.startCopyWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length.
* @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the
* naming rules.
* @return A response containing the {@link FileCopyInfo file copy info} and the status of copying the file.
* @see <a href="https:
*/
public Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata) {
return withContext(context -> startCopyWithResponse(sourceUrl, metadata, context));
}
Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata,
Context context) {
return postProcessResponse(azureFileStorageClient.files()
.startCopyWithRestResponseAsync(shareName, filePath, sourceUrl, null, metadata, context))
.map(this::startCopyResponse);
}
/**
* Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Abort copy file from copy id("someCopyId") </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopy
*
* <p>For more information, see the
* <a href="https:
*
* @param copyId Specifies the copy id which has copying pending status associate with it.
* @return An empty response.
*/
public Mono<Void> abortCopy(String copyId) {
return abortCopyWithResponse(copyId).flatMap(FluxUtil::toMono);
}
/**
* Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Abort copy file from copy id("someCopyId") </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopyWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param copyId Specifies the copy id which has copying pending status associate with it.
* @return A response containing the status of aborting copy the file.
*/
public Mono<Response<Void>> abortCopyWithResponse(String copyId) {
return withContext(context -> abortCopyWithResponse(copyId, context));
}
Mono<Response<Void>> abortCopyWithResponse(String copyId, Context context) {
return postProcessResponse(azureFileStorageClient.files()
.abortCopyWithRestResponseAsync(shareName, filePath, copyId, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Downloads a file from the system, including its metadata and properties into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Download the file to current folder. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFile
*
* <p>For more information, see the
* <a href="https:
*
* @param downloadFilePath The path where store the downloaded file
* @return An empty response.
*/
public Mono<FileProperties> downloadToFile(String downloadFilePath) {
return downloadToFileWithResponse(downloadFilePath, null).flatMap(FluxUtil::toMono);
}
/**
* Downloads a file from the system, including its metadata and properties into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Download the file from 1024 to 2048 bytes to current folder. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFileWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param downloadFilePath The path where store the downloaded file
* @param range Optional byte range which returns file data only from the specified range.
* @return An empty response.
*/
public Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range) {
return withContext(context -> downloadToFileWithResponse(downloadFilePath, range, context));
}
Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range,
Context context) {
return Mono.using(() -> channelSetup(downloadFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW),
channel -> getPropertiesWithResponse(context).flatMap(response ->
downloadResponseInChunk(response, channel, range, context)), this::channelCleanUp);
}
private Mono<Response<FileProperties>> downloadResponseInChunk(Response<FileProperties> response,
AsynchronousFileChannel channel,
FileRange range, Context context) {
return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new FileRange(0, response.getValue()
.getContentLength())))
.map(currentRange -> {
List<FileRange> chunks = new ArrayList<>();
for (long pos = currentRange.getStart(); pos < currentRange.getEnd(); pos += FILE_DEFAULT_BLOCK_SIZE) {
long count = FILE_DEFAULT_BLOCK_SIZE;
if (pos + count > currentRange.getEnd()) {
count = currentRange.getEnd() - pos;
}
chunks.add(new FileRange(pos, pos + count - 1));
}
return chunks;
}).flatMapMany(Flux::fromIterable).flatMap(chunk ->
downloadWithPropertiesWithResponse(chunk, false, context)
.map(dar -> dar.getValue().getBody())
.subscribeOn(Schedulers.elastic())
.flatMap(fbb -> FluxUtil
.writeFile(fbb, channel, chunk.getStart() - (range == null ? 0 : range.getStart()))
.subscribeOn(Schedulers.elastic())
.timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT))
.retry(3, throwable -> throwable instanceof IOException
|| throwable instanceof TimeoutException)))
.then(Mono.just(response));
}
private AsynchronousFileChannel channelSetup(String filePath, OpenOption... options) {
try {
return AsynchronousFileChannel.open(Paths.get(filePath), options);
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private void channelCleanUp(AsynchronousFileChannel channel) {
try {
channel.close();
} catch (IOException e) {
throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(e)));
}
}
/**
* Downloads a file from the system, including its metadata and properties
*
* <p><strong>Code Samples</strong></p>
*
* <p>Download the file with its metadata and properties. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return The {@link FileDownloadInfo file download Info}
*/
public Mono<FileDownloadInfo> downloadWithProperties() {
return downloadWithPropertiesWithResponse(null, null).flatMap(FluxUtil::toMono);
}
/**
* Downloads a file from the system, including its metadata and properties
*
* <p><strong>Code Samples</strong></p>
*
* <p>Download the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param range Optional byte range which returns file data only from the specified range.
* @param rangeGetContentMD5 Optional boolean which the service returns the MD5 hash for the range when it sets to
* true, as long as the range is less than or equal to 4 MB in size.
* @return A response containing the {@link FileDownloadInfo file download Info} with headers and response status
* code
*/
public Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range,
Boolean rangeGetContentMD5) {
return withContext(context -> downloadWithPropertiesWithResponse(range, rangeGetContentMD5, context));
}
Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5,
Context context) {
String rangeString = range == null ? null : range.toString();
return postProcessResponse(azureFileStorageClient.files()
.downloadWithRestResponseAsync(shareName, filePath, null, rangeString, rangeGetContentMD5, context))
.map(this::downloadWithPropertiesResponse);
}
/**
* Deletes the file associate with the client.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the file</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the directory doesn't exist or the file doesn't exist.
*/
public Mono<Void> delete() {
return deleteWithResponse(null).flatMap(FluxUtil::toMono);
}
/**
* Deletes the file associate with the client.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the file</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.deleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the directory doesn't exist or the file doesn't exist.
*/
public Mono<Response<Void>> deleteWithResponse() {
return withContext(this::deleteWithResponse);
}
Mono<Response<Void>> deleteWithResponse(Context context) {
return postProcessResponse(azureFileStorageClient.files()
.deleteWithRestResponseAsync(shareName, filePath, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves the properties of the storage account's file. The properties includes file metadata, last modified
* date, is server encrypted, and eTag.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve file properties</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return {@link FileProperties Storage file properties}
*/
public Mono<FileProperties> getProperties() {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Retrieves the properties of the storage account's file. The properties includes file metadata, last modified
* date, is server encrypted, and eTag.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve file properties</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.getPropertiesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing the {@link FileProperties storage file properties} and response status code
*/
public Mono<Response<FileProperties>> getPropertiesWithResponse() {
return withContext(this::getPropertiesWithResponse);
}
Mono<Response<FileProperties>> getPropertiesWithResponse(Context context) {
return postProcessResponse(azureFileStorageClient.files()
.getPropertiesWithRestResponseAsync(shareName, filePath, snapshot, null, context))
.map(this::getPropertiesResponse);
}
/**
* Sets the user-defined file properties to associate to the file.
*
* <p>If {@code null} is passed for the fileProperties.httpHeaders it will clear the httpHeaders associated to the
* file.
* If {@code null} is passed for the fileProperties.filesmbproperties it will preserve the filesmb properties
* associated with the file.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the httpHeaders of contentType of "text/plain"</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties
*
* <p>Clear the metadata of the file and preserve the SMB properties</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties
*
* <p>For more information, see the
* <a href="https:
*
* @param newFileSize New file size of the file
* @param httpHeaders The user settable file http headers.
* @param smbProperties The user settable file smb properties.
* @param filePermission The file permission of the file
* @return The {@link FileInfo file info}
* @throws IllegalArgumentException thrown if parameters fail the validation.
*/
public Mono<FileInfo> setProperties(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties,
String filePermission) {
return setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission)
.flatMap(FluxUtil::toMono);
}
/**
* Sets the user-defined file properties to associate to the file.
*
* <p>If {@code null} is passed for the httpHeaders it will clear the httpHeaders associated to the file.
* If {@code null} is passed for the filesmbproperties it will preserve the filesmbproperties associated with the
* file.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the httpHeaders of contentType of "text/plain"</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse
*
* <p>Clear the metadata of the file and preserve the SMB properties</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param newFileSize New file size of the file.
* @param httpHeaders The user settable file http headers.
* @param smbProperties The user settable file smb properties.
* @param filePermission The file permission of the file.
* @return Response containing the {@link FileInfo file info} and response status code.
* @throws IllegalArgumentException thrown if parameters fail the validation.
*/
public Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders,
FileSmbProperties smbProperties, String filePermission) {
return withContext(context ->
setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission, context));
}
Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders,
FileSmbProperties smbProperties, String filePermission, Context context) {
smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties;
filePermissionAndKeyHelper(filePermission, smbProperties.getFilePermissionKey());
filePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE);
String filePermissionKey = smbProperties.getFilePermissionKey();
String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE);
String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE);
String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE);
return postProcessResponse(azureFileStorageClient.files()
.setHTTPHeadersWithRestResponseAsync(shareName, filePath, fileAttributes, fileCreationTime,
fileLastWriteTime, null, newFileSize, filePermission, filePermissionKey, httpHeaders, context))
.map(this::setPropertiesResponse);
}
/**
* Sets the user-defined metadata to associate to the file.
*
* <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the metadata to "file:updatedMetadata"</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadata
*
* <p>Clear the metadata of the file</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared
* @return {@link FileMetadataInfo file meta info}
* @throws StorageException If the file doesn't exist or the metadata contains invalid keys
*/
public Mono<FileMetadataInfo> setMetadata(Map<String, String> metadata) {
return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono);
}
/**
* Sets the user-defined metadata to associate to the file.
*
* <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the metadata to "file:updatedMetadata"</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse
*
* <p>Clear the metadata of the file</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared
* @return A response containing the {@link FileMetadataInfo file meta info} and status code
* @throws StorageException If the file doesn't exist or the metadata contains invalid keys
*/
public Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata) {
return withContext(context -> setMetadataWithResponse(metadata, context));
}
Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(azureFileStorageClient.files()
.setMetadataWithRestResponseAsync(shareName, filePath, null, metadata, context))
.map(this::setMetadataResponse);
}
/**
* Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an
* in-place write on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload data "default" to the file in Storage File Service. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.upload
*
* <p>For more information, see the
* <a href="https:
*
* @param data The data which will upload to the storage file.
* @param length Specifies the number of bytes being transmitted in the request body.
* @return A response that only contains headers and response status code
*/
public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length) {
return uploadWithResponse(data, length).flatMap(FluxUtil::toMono);
}
/**
* Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an
* in-place write on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload "default" to the file. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param data The data which will upload to the storage file.
* @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is
* set to clear, the value of this header must be set to zero..
* @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code
* @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status
* code 413 (Request Entity Too Large)
*/
public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length) {
return withContext(context -> uploadWithResponse(data, length, context));
}
Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, Context context) {
FileRange range = new FileRange(0, length - 1);
return postProcessResponse(azureFileStorageClient.files()
.uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE,
length, data, null, null, context))
.map(this::uploadResponse);
}
/**
* Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place
* write on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload data "default" starting from 1024 bytes. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.upload
*
* <p>For more information, see the
* <a href="https:
*
* @param data The data which will upload to the storage file.
* @param length Specifies the number of bytes being transmitted in the request body.
* @param offset Optional starting point of the upload range. It will start from the beginning if it is
* {@code null}
* @return The {@link FileUploadInfo file upload info}
* @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status
* code 413 (Request Entity Too Large)
*/
public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length, long offset) {
return uploadWithResponse(data, length, offset).flatMap(FluxUtil::toMono);
}
/**
* Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place
* write on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param data The data which will upload to the storage file.
* @param offset Optional starting point of the upload range. It will start from the beginning if it is
* {@code null}
* @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is
* set to clear, the value of this header must be set to zero.
* @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code
* @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status
* code 413 (Request Entity Too Large)
*/
public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset) {
return withContext(context -> uploadWithResponse(data, length, offset, context));
}
Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset,
Context context) {
FileRange range = new FileRange(offset, offset + length - 1);
return postProcessResponse(azureFileStorageClient.files()
.uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE,
length, data, null, null, context))
.map(this::uploadResponse);
}
/**
* Uploads a range of bytes from one file to another file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload a number of bytes from a file at defined source and destination offsets </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @param length Specifies the number of bytes being transmitted in the request body.
* @param destinationOffset Starting point of the upload range on the destination.
* @param sourceOffset Starting point of the upload range on the source.
* @param sourceURI Specifies the URL of the source file.
* @return The {@link FileUploadRangeFromURLInfo file upload range from url info}
*/
public Mono<FileUploadRangeFromURLInfo> uploadRangeFromURL(long length, long destinationOffset, long sourceOffset,
URI sourceURI) {
return uploadRangeFromURLWithResponse(length, destinationOffset, sourceOffset, sourceURI)
.flatMap(FluxUtil::toMono);
}
/**
* Uploads a range of bytes from one file to another file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload a number of bytes from a file at defined source and destination offsets </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param length Specifies the number of bytes being transmitted in the request body.
* @param destinationOffset Starting point of the upload range on the destination.
* @param sourceOffset Starting point of the upload range on the source.
* @param sourceURI Specifies the URL of the source file.
* @return A response containing the {@link FileUploadRangeFromURLInfo file upload range from url info} with headers
* and response status code.
*/
public Mono<Response<FileUploadRangeFromURLInfo>> uploadRangeFromURLWithResponse(long length,
long destinationOffset, long sourceOffset, URI sourceURI) {
return withContext(context ->
uploadRangeFromURLWithResponse(length, destinationOffset, sourceOffset, sourceURI, context));
}
Mono<Response<FileUploadRangeFromURLInfo>> uploadRangeFromURLWithResponse(long length, long destinationOffset,
long sourceOffset, URI sourceURI, Context context) {
FileRange destinationRange = new FileRange(destinationOffset, destinationOffset + length - 1);
FileRange sourceRange = new FileRange(sourceOffset, sourceOffset + length - 1);
return postProcessResponse(azureFileStorageClient.files()
.uploadRangeFromURLWithRestResponseAsync(shareName, filePath, destinationRange.toString(),
sourceURI.toString(), 0, null, sourceRange.toString(), null, null, context))
.map(this::uploadRangeFromURLResponse);
}
/**
* Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write
* on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clears the first 1024 bytes. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange
*
* <p>For more information, see the
* <a href="https:
*
* @param length Specifies the number of bytes being cleared.
* @return The {@link FileUploadInfo file upload info}
*/
public Mono<FileUploadInfo> clearRange(long length) {
return clearRangeWithResponse(length, 0).flatMap(FluxUtil::toMono);
}
/**
* Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write
* on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the range starting from 1024 with length of 1024. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange
*
* <p>For more information, see the
* <a href="https:
*
* @param length Specifies the number of bytes being cleared in the request body.
* @param offset Optional starting point of the upload range. It will start from the beginning if it is
* {@code null}
* @return A response of {@link FileUploadInfo file upload info} that only contains headers and response status code
*/
public Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset) {
return withContext(context -> clearRangeWithResponse(length, offset, context));
}
Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) {
FileRange range = new FileRange(offset, offset + length - 1);
return postProcessResponse(azureFileStorageClient.files()
.uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L,
null, null, null, context))
.map(this::uploadResponse);
}
/**
* Uploads file to storage file service.
*
* <p><strong>Code Samples</strong></p>
*
* <p> Upload the file from the source file path. </p>
*
* (@codesnippet com.azure.storage.file.fileAsyncClient.uploadFromFile | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String filePath;
private final String snapshot;
/**
* Creates a FileAsyncClient that sends requests to the storage file at {@link AzureFileStorageImpl
* endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param filePath Path to the file
* @param snapshot The snapshot of the share
*/
FileAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String filePath, String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(filePath);
this.shareName = shareName;
this.filePath = filePath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage file client.
*
* @return the URL of the storage file client
* @throws RuntimeException If the file is using a malformed URL.
*/
/**
* Creates a file in the storage account and returns a response of {@link FileInfo} to interact with it.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create the file with size 1KB.</p>
*
* {@codesnippet com.azure.storage.file.fileClient.create}
*
* <p>For more information, see the
* <a href="https:
*
* @param maxSize The maximum size in bytes for the file, up to 1 TiB.
* @return A response containing the file info and the status of creating the file.
* @throws StorageException If the file has already existed, the parent directory does not exist or fileName is an
* invalid resource name.
*/
public Mono<FileInfo> create(long maxSize) {
return createWithResponse(maxSize, null, null, null, null).flatMap(FluxUtil::toMono);
}
/**
* Creates a file in the storage account and returns a response of FileInfo to interact with it.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create the file with length of 1024 bytes, some headers, file smb properties and metadata.</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.createWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param maxSize The maximum size in bytes for the file, up to 1 TiB.
* @param httpHeaders The user settable file http headers.
* @param smbProperties The user settable file smb properties.
* @param filePermission The file permission of the file.
* @param metadata Optional name-value pairs associated with the file as metadata.
* @return A response containing the {@link FileInfo file info} and the status of creating the file.
* @throws StorageException If the directory has already existed, the parent directory does not exist or directory
* is an invalid resource name.
*/
public Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders,
FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata) {
return withContext(context ->
createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, metadata, context));
}
Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders,
FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) {
smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties;
filePermissionAndKeyHelper(filePermission, smbProperties.getFilePermissionKey());
filePermission = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT);
String filePermissionKey = smbProperties.getFilePermissionKey();
String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE);
String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW);
String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW);
return postProcessResponse(azureFileStorageClient.files()
.createWithRestResponseAsync(shareName, filePath, maxSize, fileAttributes, fileCreationTime,
fileLastWriteTime, null, metadata, filePermission, filePermissionKey, httpHeaders, context))
.map(this::createFileInfoResponse);
}
/**
* Copies a blob or file to a destination file within the storage account.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Copy file from source url to the {@code resourcePath} </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.startCopy
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length.
* @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the
* naming rules.
* @return The {@link FileCopyInfo file copy info}.
* @see <a href="https:
*/
public Mono<FileCopyInfo> startCopy(String sourceUrl, Map<String, String> metadata) {
return startCopyWithResponse(sourceUrl, metadata).flatMap(FluxUtil::toMono);
}
/**
* Copies a blob or file to a destination file within the storage account.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Copy file from source url to the {@code resourcePath} </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.startCopyWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length.
* @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the
* naming rules.
* @return A response containing the {@link FileCopyInfo file copy info} and the status of copying the file.
* @see <a href="https:
*/
public Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata) {
return withContext(context -> startCopyWithResponse(sourceUrl, metadata, context));
}
Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata,
Context context) {
return postProcessResponse(azureFileStorageClient.files()
.startCopyWithRestResponseAsync(shareName, filePath, sourceUrl, null, metadata, context))
.map(this::startCopyResponse);
}
/**
* Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Abort copy file from copy id("someCopyId") </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopy
*
* <p>For more information, see the
* <a href="https:
*
* @param copyId Specifies the copy id which has copying pending status associate with it.
* @return An empty response.
*/
public Mono<Void> abortCopy(String copyId) {
return abortCopyWithResponse(copyId).flatMap(FluxUtil::toMono);
}
/**
* Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Abort copy file from copy id("someCopyId") </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopyWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param copyId Specifies the copy id which has copying pending status associate with it.
* @return A response containing the status of aborting copy the file.
*/
public Mono<Response<Void>> abortCopyWithResponse(String copyId) {
return withContext(context -> abortCopyWithResponse(copyId, context));
}
Mono<Response<Void>> abortCopyWithResponse(String copyId, Context context) {
return postProcessResponse(azureFileStorageClient.files()
.abortCopyWithRestResponseAsync(shareName, filePath, copyId, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Downloads a file from the system, including its metadata and properties into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Download the file to current folder. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFile
*
* <p>For more information, see the
* <a href="https:
*
* @param downloadFilePath The path where store the downloaded file
* @return An empty response.
*/
public Mono<FileProperties> downloadToFile(String downloadFilePath) {
return downloadToFileWithResponse(downloadFilePath, null).flatMap(FluxUtil::toMono);
}
/**
* Downloads a file from the system, including its metadata and properties into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Download the file from 1024 to 2048 bytes to current folder. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFileWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param downloadFilePath The path where store the downloaded file
* @param range Optional byte range which returns file data only from the specified range.
* @return An empty response.
*/
public Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range) {
return withContext(context -> downloadToFileWithResponse(downloadFilePath, range, context));
}
Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range,
Context context) {
return Mono.using(() -> channelSetup(downloadFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW),
channel -> getPropertiesWithResponse(context).flatMap(response ->
downloadResponseInChunk(response, channel, range, context)), this::channelCleanUp);
}
private Mono<Response<FileProperties>> downloadResponseInChunk(Response<FileProperties> response,
AsynchronousFileChannel channel,
FileRange range, Context context) {
return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new FileRange(0, response.getValue()
.getContentLength())))
.map(currentRange -> {
List<FileRange> chunks = new ArrayList<>();
for (long pos = currentRange.getStart(); pos < currentRange.getEnd(); pos += FILE_DEFAULT_BLOCK_SIZE) {
long count = FILE_DEFAULT_BLOCK_SIZE;
if (pos + count > currentRange.getEnd()) {
count = currentRange.getEnd() - pos;
}
chunks.add(new FileRange(pos, pos + count - 1));
}
return chunks;
}).flatMapMany(Flux::fromIterable).flatMap(chunk ->
downloadWithPropertiesWithResponse(chunk, false, context)
.map(dar -> dar.getValue().getBody())
.subscribeOn(Schedulers.elastic())
.flatMap(fbb -> FluxUtil
.writeFile(fbb, channel, chunk.getStart() - (range == null ? 0 : range.getStart()))
.subscribeOn(Schedulers.elastic())
.timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT))
.retry(3, throwable -> throwable instanceof IOException
|| throwable instanceof TimeoutException)))
.then(Mono.just(response));
}
private AsynchronousFileChannel channelSetup(String filePath, OpenOption... options) {
try {
return AsynchronousFileChannel.open(Paths.get(filePath), options);
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private void channelCleanUp(AsynchronousFileChannel channel) {
try {
channel.close();
} catch (IOException e) {
throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(e)));
}
}
/**
* Downloads a file from the system, including its metadata and properties
*
* <p><strong>Code Samples</strong></p>
*
* <p>Download the file with its metadata and properties. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return The {@link FileDownloadInfo file download Info}
*/
public Mono<FileDownloadInfo> downloadWithProperties() {
return downloadWithPropertiesWithResponse(null, null).flatMap(FluxUtil::toMono);
}
/**
* Downloads a file from the system, including its metadata and properties
*
* <p><strong>Code Samples</strong></p>
*
* <p>Download the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param range Optional byte range which returns file data only from the specified range.
* @param rangeGetContentMD5 Optional boolean which the service returns the MD5 hash for the range when it sets to
* true, as long as the range is less than or equal to 4 MB in size.
* @return A response containing the {@link FileDownloadInfo file download Info} with headers and response status
* code
*/
public Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range,
Boolean rangeGetContentMD5) {
return withContext(context -> downloadWithPropertiesWithResponse(range, rangeGetContentMD5, context));
}
Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5,
Context context) {
String rangeString = range == null ? null : range.toString();
return postProcessResponse(azureFileStorageClient.files()
.downloadWithRestResponseAsync(shareName, filePath, null, rangeString, rangeGetContentMD5, context))
.map(this::downloadWithPropertiesResponse);
}
/**
* Deletes the file associate with the client.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the file</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the directory doesn't exist or the file doesn't exist.
*/
public Mono<Void> delete() {
return deleteWithResponse(null).flatMap(FluxUtil::toMono);
}
/**
* Deletes the file associate with the client.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the file</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.deleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the directory doesn't exist or the file doesn't exist.
*/
public Mono<Response<Void>> deleteWithResponse() {
return withContext(this::deleteWithResponse);
}
Mono<Response<Void>> deleteWithResponse(Context context) {
return postProcessResponse(azureFileStorageClient.files()
.deleteWithRestResponseAsync(shareName, filePath, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves the properties of the storage account's file. The properties includes file metadata, last modified
* date, is server encrypted, and eTag.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve file properties</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return {@link FileProperties Storage file properties}
*/
public Mono<FileProperties> getProperties() {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Retrieves the properties of the storage account's file. The properties includes file metadata, last modified
* date, is server encrypted, and eTag.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve file properties</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.getPropertiesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing the {@link FileProperties storage file properties} and response status code
*/
public Mono<Response<FileProperties>> getPropertiesWithResponse() {
return withContext(this::getPropertiesWithResponse);
}
Mono<Response<FileProperties>> getPropertiesWithResponse(Context context) {
return postProcessResponse(azureFileStorageClient.files()
.getPropertiesWithRestResponseAsync(shareName, filePath, snapshot, null, context))
.map(this::getPropertiesResponse);
}
/**
* Sets the user-defined file properties to associate to the file.
*
* <p>If {@code null} is passed for the fileProperties.httpHeaders it will clear the httpHeaders associated to the
* file.
* If {@code null} is passed for the fileProperties.filesmbproperties it will preserve the filesmb properties
* associated with the file.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the httpHeaders of contentType of "text/plain"</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties
*
* <p>Clear the metadata of the file and preserve the SMB properties</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties
*
* <p>For more information, see the
* <a href="https:
*
* @param newFileSize New file size of the file
* @param httpHeaders The user settable file http headers.
* @param smbProperties The user settable file smb properties.
* @param filePermission The file permission of the file
* @return The {@link FileInfo file info}
* @throws IllegalArgumentException thrown if parameters fail the validation.
*/
public Mono<FileInfo> setProperties(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties,
String filePermission) {
return setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission)
.flatMap(FluxUtil::toMono);
}
/**
* Sets the user-defined file properties to associate to the file.
*
* <p>If {@code null} is passed for the httpHeaders it will clear the httpHeaders associated to the file.
* If {@code null} is passed for the filesmbproperties it will preserve the filesmbproperties associated with the
* file.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the httpHeaders of contentType of "text/plain"</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse
*
* <p>Clear the metadata of the file and preserve the SMB properties</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param newFileSize New file size of the file.
* @param httpHeaders The user settable file http headers.
* @param smbProperties The user settable file smb properties.
* @param filePermission The file permission of the file.
* @return Response containing the {@link FileInfo file info} and response status code.
* @throws IllegalArgumentException thrown if parameters fail the validation.
*/
public Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders,
FileSmbProperties smbProperties, String filePermission) {
return withContext(context ->
setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission, context));
}
Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders,
FileSmbProperties smbProperties, String filePermission, Context context) {
smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties;
filePermissionAndKeyHelper(filePermission, smbProperties.getFilePermissionKey());
filePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE);
String filePermissionKey = smbProperties.getFilePermissionKey();
String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE);
String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE);
String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE);
return postProcessResponse(azureFileStorageClient.files()
.setHTTPHeadersWithRestResponseAsync(shareName, filePath, fileAttributes, fileCreationTime,
fileLastWriteTime, null, newFileSize, filePermission, filePermissionKey, httpHeaders, context))
.map(this::setPropertiesResponse);
}
/**
* Sets the user-defined metadata to associate to the file.
*
* <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the metadata to "file:updatedMetadata"</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadata
*
* <p>Clear the metadata of the file</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared
* @return {@link FileMetadataInfo file meta info}
* @throws StorageException If the file doesn't exist or the metadata contains invalid keys
*/
public Mono<FileMetadataInfo> setMetadata(Map<String, String> metadata) {
return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono);
}
/**
* Sets the user-defined metadata to associate to the file.
*
* <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the metadata to "file:updatedMetadata"</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse
*
* <p>Clear the metadata of the file</p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared
* @return A response containing the {@link FileMetadataInfo file meta info} and status code
* @throws StorageException If the file doesn't exist or the metadata contains invalid keys
*/
public Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata) {
return withContext(context -> setMetadataWithResponse(metadata, context));
}
Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(azureFileStorageClient.files()
.setMetadataWithRestResponseAsync(shareName, filePath, null, metadata, context))
.map(this::setMetadataResponse);
}
/**
* Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an
* in-place write on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload data "default" to the file in Storage File Service. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.upload
*
* <p>For more information, see the
* <a href="https:
*
* @param data The data which will upload to the storage file.
* @param length Specifies the number of bytes being transmitted in the request body.
* @return A response that only contains headers and response status code
*/
public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length) {
return uploadWithResponse(data, length).flatMap(FluxUtil::toMono);
}
/**
* Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an
* in-place write on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload "default" to the file. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param data The data which will upload to the storage file.
* @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is
* set to clear, the value of this header must be set to zero..
* @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code
* @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status
* code 413 (Request Entity Too Large)
*/
public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length) {
return withContext(context -> uploadWithResponse(data, length, context));
}
Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, Context context) {
FileRange range = new FileRange(0, length - 1);
return postProcessResponse(azureFileStorageClient.files()
.uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE,
length, data, null, null, context))
.map(this::uploadResponse);
}
/**
* Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place
* write on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload data "default" starting from 1024 bytes. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.upload
*
* <p>For more information, see the
* <a href="https:
*
* @param data The data which will upload to the storage file.
* @param length Specifies the number of bytes being transmitted in the request body.
* @param offset Optional starting point of the upload range. It will start from the beginning if it is
* {@code null}
* @return The {@link FileUploadInfo file upload info}
* @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status
* code 413 (Request Entity Too Large)
*/
public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length, long offset) {
return uploadWithResponse(data, length, offset).flatMap(FluxUtil::toMono);
}
/**
* Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place
* write on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param data The data which will upload to the storage file.
* @param offset Optional starting point of the upload range. It will start from the beginning if it is
* {@code null}
* @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is
* set to clear, the value of this header must be set to zero.
* @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code
* @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status
* code 413 (Request Entity Too Large)
*/
public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset) {
return withContext(context -> uploadWithResponse(data, length, offset, context));
}
Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset,
Context context) {
FileRange range = new FileRange(offset, offset + length - 1);
return postProcessResponse(azureFileStorageClient.files()
.uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE,
length, data, null, null, context))
.map(this::uploadResponse);
}
/**
* Uploads a range of bytes from one file to another file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload a number of bytes from a file at defined source and destination offsets </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @param length Specifies the number of bytes being transmitted in the request body.
* @param destinationOffset Starting point of the upload range on the destination.
* @param sourceOffset Starting point of the upload range on the source.
* @param sourceURI Specifies the URL of the source file.
* @return The {@link FileUploadRangeFromURLInfo file upload range from url info}
*/
public Mono<FileUploadRangeFromURLInfo> uploadRangeFromURL(long length, long destinationOffset, long sourceOffset,
URI sourceURI) {
return uploadRangeFromURLWithResponse(length, destinationOffset, sourceOffset, sourceURI)
.flatMap(FluxUtil::toMono);
}
/**
* Uploads a range of bytes from one file to another file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Upload a number of bytes from a file at defined source and destination offsets </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param length Specifies the number of bytes being transmitted in the request body.
* @param destinationOffset Starting point of the upload range on the destination.
* @param sourceOffset Starting point of the upload range on the source.
* @param sourceURI Specifies the URL of the source file.
* @return A response containing the {@link FileUploadRangeFromURLInfo file upload range from url info} with headers
* and response status code.
*/
public Mono<Response<FileUploadRangeFromURLInfo>> uploadRangeFromURLWithResponse(long length,
long destinationOffset, long sourceOffset, URI sourceURI) {
return withContext(context ->
uploadRangeFromURLWithResponse(length, destinationOffset, sourceOffset, sourceURI, context));
}
Mono<Response<FileUploadRangeFromURLInfo>> uploadRangeFromURLWithResponse(long length, long destinationOffset,
long sourceOffset, URI sourceURI, Context context) {
FileRange destinationRange = new FileRange(destinationOffset, destinationOffset + length - 1);
FileRange sourceRange = new FileRange(sourceOffset, sourceOffset + length - 1);
return postProcessResponse(azureFileStorageClient.files()
.uploadRangeFromURLWithRestResponseAsync(shareName, filePath, destinationRange.toString(),
sourceURI.toString(), 0, null, sourceRange.toString(), null, null, context))
.map(this::uploadRangeFromURLResponse);
}
/**
* Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write
* on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clears the first 1024 bytes. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange
*
* <p>For more information, see the
* <a href="https:
*
* @param length Specifies the number of bytes being cleared.
* @return The {@link FileUploadInfo file upload info}
*/
public Mono<FileUploadInfo> clearRange(long length) {
return clearRangeWithResponse(length, 0).flatMap(FluxUtil::toMono);
}
/**
* Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write
* on the specified file.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the range starting from 1024 with length of 1024. </p>
*
* {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange
*
* <p>For more information, see the
* <a href="https:
*
* @param length Specifies the number of bytes being cleared in the request body.
* @param offset Optional starting point of the upload range. It will start from the beginning if it is
* {@code null}
* @return A response of {@link FileUploadInfo file upload info} that only contains headers and response status code
*/
public Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset) {
return withContext(context -> clearRangeWithResponse(length, offset, context));
}
Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) {
FileRange range = new FileRange(offset, offset + length - 1);
return postProcessResponse(azureFileStorageClient.files()
.uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L,
null, null, null, context))
.map(this::uploadResponse);
}
/**
* Uploads file to storage file service.
*
* <p><strong>Code Samples</strong></p>
*
* <p> Upload the file from the source file path. </p>
*
* (@codesnippet com.azure.storage.file.fileAsyncClient.uploadFromFile |
StringBuilder comment. | public URL getShareUrl() {
String shareURLString = String.format("%s/%s", azureFileStorageClient.getUrl(), shareName);
if (snapshot != null) {
shareURLString = String.format("%s?snapshot=%s", shareURLString, snapshot);
}
try {
return new URL(shareURLString);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), shareURLString), e));
}
} | shareURLString = String.format("%s?snapshot=%s", shareURLString, snapshot); | public URL getShareUrl() {
StringBuilder shareURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/").append(shareName);
if (snapshot != null) {
shareURLString.append("?snapshot=").append(snapshot);
}
try {
return new URL(shareURLString.toString());
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), shareURLString), e));
}
} | class ShareAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String snapshot;
/**
* Creates a ShareAsyncClient that sends requests to the storage share at {@link AzureFileStorageImpl
* endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the
* {@code azureFileStorageClient}.
*
* @param client Client that interacts with the service interfaces
* @param shareName Name of the share
*/
ShareAsyncClient(AzureFileStorageImpl client, String shareName, String snapshot) {
Objects.requireNonNull(shareName);
this.shareName = shareName;
this.snapshot = snapshot;
this.azureFileStorageClient = client;
}
/**
* Get the url of the storage share client.
*
* @return the url of the Storage Share.
* @throws RuntimeException If the share is using a malformed URL.
*/
/**
* Constructs a {@link DirectoryAsyncClient} that interacts with the root directory in the share.
*
* <p>If the directory doesn't exist in the share {@link DirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @return a {@link DirectoryAsyncClient} that interacts with the root directory in the share
*/
public DirectoryAsyncClient getRootDirectoryClient() {
return getDirectoryClient("");
}
/**
* Constructs a {@link DirectoryAsyncClient} that interacts with the specified directory.
*
* <p>If the directory doesn't exist in the share {@link DirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @param directoryName Name of the directory
* @return a {@link DirectoryAsyncClient} that interacts with the directory in the share
*/
public DirectoryAsyncClient getDirectoryClient(String directoryName) {
return new DirectoryAsyncClient(azureFileStorageClient, shareName, directoryName, snapshot);
}
/**
* Constructs a {@link FileAsyncClient} that interacts with the specified file.
*
* <p>If the file doesn't exist in the share {@link FileAsyncClient | class ShareAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String snapshot;
/**
* Creates a ShareAsyncClient that sends requests to the storage share at {@link AzureFileStorageImpl
* endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the
* {@code azureFileStorageClient}.
*
* @param client Client that interacts with the service interfaces
* @param shareName Name of the share
*/
ShareAsyncClient(AzureFileStorageImpl client, String shareName, String snapshot) {
Objects.requireNonNull(shareName);
this.shareName = shareName;
this.snapshot = snapshot;
this.azureFileStorageClient = client;
}
/**
* Get the url of the storage share client.
*
* @return the url of the Storage Share.
* @throws RuntimeException If the share is using a malformed URL.
*/
/**
* Constructs a {@link DirectoryAsyncClient} that interacts with the root directory in the share.
*
* <p>If the directory doesn't exist in the share {@link DirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @return a {@link DirectoryAsyncClient} that interacts with the root directory in the share
*/
public DirectoryAsyncClient getRootDirectoryClient() {
return getDirectoryClient("");
}
/**
* Constructs a {@link DirectoryAsyncClient} that interacts with the specified directory.
*
* <p>If the directory doesn't exist in the share {@link DirectoryAsyncClient
* azureFileStorageClient will need to be called before interaction with the directory can happen.</p>
*
* @param directoryName Name of the directory
* @return a {@link DirectoryAsyncClient} that interacts with the directory in the share
*/
public DirectoryAsyncClient getDirectoryClient(String directoryName) {
return new DirectoryAsyncClient(azureFileStorageClient, shareName, directoryName, snapshot);
}
/**
* Constructs a {@link FileAsyncClient} that interacts with the specified file.
*
* <p>If the file doesn't exist in the share {@link FileAsyncClient |
```java logger.error("Queue URL is malformed"); throw logger.logExceptionAsError(new RuntimeException("Queue URL is malformed")); ``` Does this log twice? | public URL getQueueUrl() {
try {
return new URL(String.format("%s/%s", client.getUrl(), queueName));
} catch (MalformedURLException ex) {
logger.error("Queue URL is malformed");
throw logger.logExceptionAsError(new RuntimeException("Queue URL is malformed"));
}
} | throw logger.logExceptionAsError(new RuntimeException("Queue URL is malformed")); | public URL getQueueUrl() {
try {
return new URL(String.format("%s/%s", client.getUrl(), queueName));
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new RuntimeException("Queue URL is malformed"));
}
} | class QueueAsyncClient {
private final ClientLogger logger = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@link
* Each service call goes through the {@link HttpPipeline pipeline}.
*
* @param client Client that interacts with the service interfaces
* @param queueName Name of the queue
*/
QueueAsyncClient(AzureQueueStorageImpl client, String queueName) {
Objects.requireNonNull(queueName);
this.queueName = queueName;
this.client = client;
}
/**
* @return the URL of the storage queue
* @throws RuntimeException If the queue is using a malformed URL.
*/
/**
* Creates a new queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.create}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If a queue with the same name already exists in the queue service.
*/
public Mono<Void> create() {
return createWithResponse(null).flatMap(FluxUtil::toMono);
}
/**
* Creates a new queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create a queue with metadata "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.createWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the queue
* @return A response that only contains headers and response status code
* @throws StorageException If a queue with the same name and different metadata already exists in the queue
* service.
*/
public Mono<Response<Void>> createWithResponse(Map<String, String> metadata) {
return withContext(context -> createWithResponse(metadata, context));
}
Mono<Response<Void>> createWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(client.queues()
.createWithRestResponseAsync(queueName, null, metadata, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Permanently deletes the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> delete() {
return deleteWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Permanently deletes the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.deleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> deleteWithResponse() {
return withContext(this::deleteWithResponse);
}
Mono<Response<Void>> deleteWithResponse(Context context) {
return postProcessResponse(client.queues().deleteWithRestResponseAsync(queueName, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves metadata and approximate message count of the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the properties of the queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link QueueProperties} value which contains the metadata and approximate
* messages count of the queue.
* @throws StorageException If the queue doesn't exist
*/
public Mono<QueueProperties> getProperties() {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Retrieves metadata and approximate message count of the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the properties of the queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getPropertiesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link QueueProperties} value which contains the metadata and approximate
* messages count of the queue.
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<QueueProperties>> getPropertiesWithResponse() {
return withContext(this::getPropertiesWithResponse);
}
Mono<Response<QueueProperties>> getPropertiesWithResponse(Context context) {
return postProcessResponse(client.queues().getPropertiesWithRestResponseAsync(queueName, context))
.map(this::getQueuePropertiesResponse);
}
/**
* Sets the metadata of the queue.
*
* Passing in a {@code null} value for metadata will clear the metadata associated with the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the queue's metadata to "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.setMetadata
*
* <p>Clear the queue's metadata</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono);
}
/**
* Sets the metadata of the queue.
*
* Passing in a {@code null} value for metadata will clear the metadata associated with the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the queue's metadata to "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.setMetadataWithResponse
*
* <p>Clear the queue's metadata</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata) {
return withContext(context -> setMetadataWithResponse(metadata, context));
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(client.queues()
.setMetadataWithRestResponseAsync(queueName, null, metadata, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves stored access policies specified on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>List the stored access policies</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getAccessPolicy}
*
* <p>For more information, see the
* <a href="https:
*
* @return The stored access policies specified on the queue.
* @throws StorageException If the queue doesn't exist
*/
public PagedFlux<SignedIdentifier> getAccessPolicy() {
Function<String, Mono<PagedResponse<SignedIdentifier>>> retriever =
marker -> postProcessResponse(this.client.queues()
.getAccessPolicyWithRestResponseAsync(queueName, Context.NONE))
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders()));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Sets stored access policies on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set a read only stored access policy</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.setAccessPolicy
*
* <p>For more information, see the
* <a href="https:
*
* @param permissions Access policies to set on the queue
* @return An empty response
* @throws StorageException If the queue doesn't exist, a stored access policy doesn't have all fields filled out,
* or the queue will have more than five policies.
*/
public Mono<Void> setAccessPolicy(List<SignedIdentifier> permissions) {
return setAccessPolicyWithResponse(permissions).flatMap(FluxUtil::toMono);
}
/**
* Sets stored access policies on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set a read only stored access policy</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.setAccessPolicyWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param permissions Access policies to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist, a stored access policy doesn't have all fields filled out,
* or the queue will have more than five policies.
*/
public Mono<Response<Void>> setAccessPolicyWithResponse(List<SignedIdentifier> permissions) {
return withContext(context -> setAccessPolicyWithResponse(permissions, context));
}
Mono<Response<Void>> setAccessPolicyWithResponse(List<SignedIdentifier> permissions, Context context) {
/*
We truncate to seconds because the service only supports nanoseconds or seconds, but doing an
OffsetDateTime.now will only give back milliseconds (more precise fields are zeroed and not serialized). This
allows for proper serialization with no real detriment to users as sub-second precision on active time for
signed identifiers is not really necessary.
*/
if (permissions != null) {
for (SignedIdentifier permission : permissions) {
if (permission.getAccessPolicy() != null && permission.getAccessPolicy().getStart() != null) {
permission.getAccessPolicy().setStart(
permission.getAccessPolicy().getStart().truncatedTo(ChronoUnit.SECONDS));
}
if (permission.getAccessPolicy() != null && permission.getAccessPolicy().getExpiry() != null) {
permission.getAccessPolicy().setExpiry(
permission.getAccessPolicy().getExpiry().truncatedTo(ChronoUnit.SECONDS));
}
}
}
return postProcessResponse(client.queues()
.setAccessPolicyWithRestResponseAsync(queueName, permissions, null, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Deletes all messages in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> clearMessages() {
return clearMessagesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Deletes all messages in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMessagesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> clearMessagesWithResponse() {
return withContext(this::clearMessagesWithResponse);
}
Mono<Response<Void>> clearMessagesWithResponse(Context context) {
return postProcessResponse(client.messages().clearWithRestResponseAsync(queueName, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Enqueues a message that has a time-to-live of 7 days and is instantly visible.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Enqueue a message of "Hello, Azure"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.enqueueMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Message text
* @return A {@link EnqueuedMessage} value that contains the {@link EnqueuedMessage
* {@link EnqueuedMessage
* about the enqueued message.
* @throws StorageException If the queue doesn't exist
*/
public Mono<EnqueuedMessage> enqueueMessage(String messageText) {
return enqueueMessageWithResponse(messageText, null, null).flatMap(FluxUtil::toMono);
}
/**
* Enqueues a message with a given time-to-live and a timeout period where the message is invisible in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a message of "Hello, Azure" that has a timeout of 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.enqueueMessageWithResponse
*
* <p>Add a message of "Goodbye, Azure" that has a time to live of 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.enqueueMessageWithResponse-liveTime
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Message text
* @param visibilityTimeout Optional. The timeout period for how long the message is invisible in the queue. If
* unset the value will default to 0 and the message will be instantly visible. The timeout must be between 0
* seconds and 7 days.
* @param timeToLive Optional. How long the message will stay alive in the queue. If unset the value will default to
* 7 days, if -1 is passed the message will not expire. The time to live must be -1 or any positive number.
* @return A {@link EnqueuedMessage} value that contains the {@link EnqueuedMessage
* {@link EnqueuedMessage
* about the enqueued message.
* @throws StorageException If the queue doesn't exist or the {@code visibilityTimeout} or {@code timeToLive} are
* outside of the allowed limits.
*/
public Mono<Response<EnqueuedMessage>> enqueueMessageWithResponse(String messageText, Duration visibilityTimeout,
Duration timeToLive) {
return withContext(context -> enqueueMessageWithResponse(messageText, visibilityTimeout, timeToLive, context));
}
Mono<Response<EnqueuedMessage>> enqueueMessageWithResponse(String messageText, Duration visibilityTimeout,
Duration timeToLive, Context context) {
Integer visibilityTimeoutInSeconds = (visibilityTimeout == null) ? null : (int) visibilityTimeout.getSeconds();
Integer timeToLiveInSeconds = (timeToLive == null) ? null : (int) timeToLive.getSeconds();
QueueMessage message = new QueueMessage().setMessageText(messageText);
return postProcessResponse(client.messages()
.enqueueWithRestResponseAsync(queueName, message, visibilityTimeoutInSeconds, timeToLiveInSeconds,
null, null, context))
.map(response -> new SimpleResponse<>(response, response.getValue().get(0)));
}
/**
* Retrieves the first message in the queue and hides it from other operations for 30 seconds.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue a message</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return The first {@link DequeuedMessage} in the queue, it contains {@link DequeuedMessage
* messageId} and {@link DequeuedMessage
* it contains other metadata about the message.
* @throws StorageException If the queue doesn't exist
*/
public PagedFlux<DequeuedMessage> dequeueMessages() {
return dequeueMessagesWithOptionalTimeout(1, null, null, Context.NONE);
}
/**
* Retrieves up to the maximum number of messages from the queue and hides them from other operations for 30
* seconds.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue up to 5 messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to get, if there are less messages exist in the queue
* than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed
* range is 1 to 32 messages.
* @return Up to {@code maxMessages} {@link DequeuedMessage DequeuedMessages} from the queue. Each DequeuedMessage
* contains {@link DequeuedMessage
* used to interact with the message and other metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} is outside of the allowed bounds
*/
public PagedFlux<DequeuedMessage> dequeueMessages(Integer maxMessages) {
return dequeueMessagesWithOptionalTimeout(maxMessages, null, null, Context.NONE);
}
/**
* Retrieves up to the maximum number of messages from the queue and hides them from other operations for the
* timeout period.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue up to 5 messages and give them a 60 second timeout period</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to get, if there are less messages exist in the queue
* than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed
* range is 1 to 32 messages.
* @param visibilityTimeout Optional. The timeout period for how long the message is invisible in the queue. If left
* empty the dequeued messages will be invisible for 30 seconds. The timeout must be between 1 second and 7 days.
* @return Up to {@code maxMessages} {@link DequeuedMessage DequeuedMessages} from the queue. Each DeqeuedMessage
* contains {@link DequeuedMessage
* used to interact with the message and other metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} or {@code visibilityTimeout} is
* outside of the allowed bounds
*/
public PagedFlux<DequeuedMessage> dequeueMessages(Integer maxMessages, Duration visibilityTimeout) {
return dequeueMessagesWithOptionalTimeout(maxMessages, visibilityTimeout, null, Context.NONE);
}
PagedFlux<DequeuedMessage> dequeueMessagesWithOptionalTimeout(Integer maxMessages, Duration visibilityTimeout,
Duration timeout, Context context) {
Integer visibilityTimeoutInSeconds = (visibilityTimeout == null) ? null : (int) visibilityTimeout.getSeconds();
Function<String, Mono<PagedResponse<DequeuedMessage>>> retriever =
marker -> postProcessResponse(Utility.applyOptionalTimeout(this.client.messages()
.dequeueWithRestResponseAsync(queueName, maxMessages, visibilityTimeoutInSeconds,
null, null, context), timeout)
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders())));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Peeks the first message in the queue.
*
* Peeked messages don't contain the necessary information needed to interact with the message nor will it hide
* messages from other operations on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Peek the first message</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.peekMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return A {@link PeekedMessage} that contains metadata about the message.
*/
public PagedFlux<PeekedMessage> peekMessages() {
return peekMessages(null);
}
/**
* Peek messages from the front of the queue up to the maximum number of messages.
*
* Peeked messages don't contain the necessary information needed to interact with the message nor will it hide
* messages from other operations on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Peek up to the first five messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.peekMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to peek, if there are less messages exist in the queue
* than requested all the messages will be peeked. If left empty only 1 message will be peeked, the allowed range is
* 1 to 32 messages.
* @return Up to {@code maxMessages} {@link PeekedMessage PeekedMessages} from the queue. Each PeekedMessage
* contains metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} is outside of the allowed bounds
*/
public PagedFlux<PeekedMessage> peekMessages(Integer maxMessages) {
return peekMessagesWithOptionalTimeout(maxMessages, null, Context.NONE);
}
PagedFlux<PeekedMessage> peekMessagesWithOptionalTimeout(Integer maxMessages, Duration timeout, Context context) {
Function<String, Mono<PagedResponse<PeekedMessage>>> retriever =
marker -> postProcessResponse(Utility.applyOptionalTimeout(this.client.messages()
.peekWithRestResponseAsync(queueName, maxMessages, null, null, context), timeout)
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders())));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Updates the specific message in the queue with a new message and resets the visibility timeout.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue the first message and update it to "Hello again, Azure" and hide it for 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.updateMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Updated value for the message
* @param messageId Id of the message to update
* @param popReceipt Unique identifier that must match for the message to be updated
* @param visibilityTimeout The timeout period for how long the message is invisible in the queue in seconds. The
* timeout period must be between 1 second and 7 days.
* @return A {@link UpdatedMessage} that contains the new {@link UpdatedMessage
* interact with the message, additionally contains the updated metadata about the message.
* @throws StorageException If the queue or messageId don't exist, the popReceipt doesn't match on the message, or
* the {@code visibilityTimeout} is outside the allowed bounds
*/
public Mono<UpdatedMessage> updateMessage(String messageText, String messageId, String popReceipt,
Duration visibilityTimeout) {
return updateMessageWithResponse(messageText, messageId, popReceipt, visibilityTimeout)
.flatMap(FluxUtil::toMono);
}
/**
* Updates the specific message in the queue with a new message and resets the visibility timeout.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue the first message and update it to "Hello again, Azure" and hide it for 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.updateMessageWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Updated value for the message
* @param messageId Id of the message to update
* @param popReceipt Unique identifier that must match for the message to be updated
* @param visibilityTimeout The timeout period for how long the message is invisible in the queue in seconds. The
* timeout period must be between 1 second and 7 days.
* @return A {@link UpdatedMessage} that contains the new {@link UpdatedMessage
* interact with the message, additionally contains the updated metadata about the message.
* @throws StorageException If the queue or messageId don't exist, the popReceipt doesn't match on the message, or
* the {@code visibilityTimeout} is outside the allowed bounds
*/
public Mono<Response<UpdatedMessage>> updateMessageWithResponse(String messageText, String messageId,
String popReceipt, Duration visibilityTimeout) {
return withContext(context ->
updateMessageWithResponse(messageText, messageId, popReceipt, visibilityTimeout, context));
}
Mono<Response<UpdatedMessage>> updateMessageWithResponse(String messageText, String messageId, String popReceipt,
Duration visibilityTimeout, Context context) {
QueueMessage message = new QueueMessage().setMessageText(messageText);
return postProcessResponse(client.messageIds()
.updateWithRestResponseAsync(queueName, messageId, message, popReceipt,
(int) visibilityTimeout.getSeconds(), context))
.map(this::getUpdatedMessageResponse);
}
/**
* Deletes the specified message in the queue
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the first message</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.deleteMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageId Id of the message to deleted
* @param popReceipt Unique identifier that must match for the message to be deleted
* @return An empty response
* @throws StorageException If the queue or messageId don't exist or the popReceipt doesn't match on the message
*/
public Mono<Void> deleteMessage(String messageId, String popReceipt) {
return deleteMessageWithResponse(messageId, popReceipt).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified message in the queue
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the first message</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.deleteMessageWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param messageId Id of the message to deleted
* @param popReceipt Unique identifier that must match for the message to be deleted
* @return A response that only contains headers and response status code
* @throws StorageException If the queue or messageId don't exist or the popReceipt doesn't match on the message
*/
public Mono<Response<Void>> deleteMessageWithResponse(String messageId, String popReceipt) {
return withContext(context -> deleteMessageWithResponse(messageId, popReceipt, context));
}
Mono<Response<Void>> deleteMessageWithResponse(String messageId, String popReceipt, Context context) {
return postProcessResponse(client.messageIds()
.deleteWithRestResponseAsync(queueName, messageId, popReceipt, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Generates a SAS token with the specified parameters
*
* @param permissions The {@code QueueSASPermission} permission for the SAS
* @param expiryTime The {@code OffsetDateTime} expiry time for the SAS
* @return A string that represents the SAS token
*/
public String generateSAS(QueueSASPermission permissions, OffsetDateTime expiryTime) {
return this.generateSAS(null, permissions, expiryTime, null /* startTime */, /* identifier */ null /*
version */, null /* sasProtocol */, null /* ipRange */);
}
/**
* Generates a SAS token with the specified parameters
*
* @param identifier The {@code String} name of the access policy on the queue this SAS references if any
* @return A string that represents the SAS token
*/
public String generateSAS(String identifier) {
return this.generateSAS(identifier, null /* permissions */, null /* expiryTime */, null /* startTime */,
null /* version */, null /* sasProtocol */, null /* ipRange */);
}
/**
* Generates a SAS token with the specified parameters
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.generateSAS
*
* <p>For more information, see the
* <a href="https:
*
* @param identifier The {@code String} name of the access policy on the queue this SAS references if any
* @param permissions The {@code QueueSASPermission} permission for the SAS
* @param expiryTime The {@code OffsetDateTime} expiry time for the SAS
* @param startTime An optional {@code OffsetDateTime} start time for the SAS
* @param version An optional {@code String} version for the SAS
* @param sasProtocol An optional {@code SASProtocol} protocol for the SAS
* @param ipRange An optional {@code IPRange} ip address range for the SAS
* @return A string that represents the SAS token
*/
public String generateSAS(String identifier, QueueSASPermission permissions, OffsetDateTime expiryTime,
OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) {
QueueServiceSASSignatureValues queueServiceSASSignatureValues = new QueueServiceSASSignatureValues(version,
sasProtocol, startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange,
identifier);
SharedKeyCredential sharedKeyCredential =
Utility.getSharedKeyCredential(this.client.getHttpPipeline());
Utility.assertNotNull("sharedKeyCredential", sharedKeyCredential);
QueueServiceSASSignatureValues values = queueServiceSASSignatureValues
.setCanonicalName(this.queueName, sharedKeyCredential.getAccountName());
QueueServiceSASQueryParameters queueServiceSasQueryParameters = values
.generateSASQueryParameters(sharedKeyCredential);
return queueServiceSasQueryParameters.encode();
}
/**
* Get the queue name of the client.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getQueueName}
*
* @return The name of the queue.
*/
public String getQueueName() {
return queueName;
}
/*
* Maps the HTTP headers returned from the service to the expected response type
* @param response Service response
* @return Mapped response
*/
private Response<QueueProperties> getQueuePropertiesResponse(QueuesGetPropertiesResponse response) {
QueueGetPropertiesHeaders propertiesHeaders = response.getDeserializedHeaders();
QueueProperties properties = new QueueProperties(propertiesHeaders.getMetadata(),
propertiesHeaders.getApproximateMessagesCount());
return new SimpleResponse<>(response, properties);
}
/*
* Maps the HTTP headers returned from the service to the expected response type
* @param response Service response
* @return Mapped response
*/
private Response<UpdatedMessage> getUpdatedMessageResponse(MessageIdsUpdateResponse response) {
MessageIdUpdateHeaders headers = response.getDeserializedHeaders();
UpdatedMessage updatedMessage = new UpdatedMessage(headers.getPopReceipt(), headers.getTimeNextVisible());
return new SimpleResponse<>(response, updatedMessage);
}
} | class QueueAsyncClient {
private final ClientLogger logger = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@link
* Each service call goes through the {@link HttpPipeline pipeline}.
*
* @param client Client that interacts with the service interfaces
* @param queueName Name of the queue
*/
QueueAsyncClient(AzureQueueStorageImpl client, String queueName) {
Objects.requireNonNull(queueName);
this.queueName = queueName;
this.client = client;
}
/**
* @return the URL of the storage queue
* @throws RuntimeException If the queue is using a malformed URL.
*/
/**
* Creates a new queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.create}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If a queue with the same name already exists in the queue service.
*/
public Mono<Void> create() {
return createWithResponse(null).flatMap(FluxUtil::toMono);
}
/**
* Creates a new queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create a queue with metadata "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.createWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the queue
* @return A response that only contains headers and response status code
* @throws StorageException If a queue with the same name and different metadata already exists in the queue
* service.
*/
public Mono<Response<Void>> createWithResponse(Map<String, String> metadata) {
return withContext(context -> createWithResponse(metadata, context));
}
Mono<Response<Void>> createWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(client.queues()
.createWithRestResponseAsync(queueName, null, metadata, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Permanently deletes the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> delete() {
return deleteWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Permanently deletes the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.deleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> deleteWithResponse() {
return withContext(this::deleteWithResponse);
}
Mono<Response<Void>> deleteWithResponse(Context context) {
return postProcessResponse(client.queues().deleteWithRestResponseAsync(queueName, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves metadata and approximate message count of the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the properties of the queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link QueueProperties} value which contains the metadata and approximate
* messages count of the queue.
* @throws StorageException If the queue doesn't exist
*/
public Mono<QueueProperties> getProperties() {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Retrieves metadata and approximate message count of the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the properties of the queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getPropertiesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link QueueProperties} value which contains the metadata and approximate
* messages count of the queue.
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<QueueProperties>> getPropertiesWithResponse() {
return withContext(this::getPropertiesWithResponse);
}
Mono<Response<QueueProperties>> getPropertiesWithResponse(Context context) {
return postProcessResponse(client.queues().getPropertiesWithRestResponseAsync(queueName, context))
.map(this::getQueuePropertiesResponse);
}
/**
* Sets the metadata of the queue.
*
* Passing in a {@code null} value for metadata will clear the metadata associated with the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the queue's metadata to "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.setMetadata
*
* <p>Clear the queue's metadata</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono);
}
/**
* Sets the metadata of the queue.
*
* Passing in a {@code null} value for metadata will clear the metadata associated with the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the queue's metadata to "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.setMetadataWithResponse
*
* <p>Clear the queue's metadata</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata) {
return withContext(context -> setMetadataWithResponse(metadata, context));
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(client.queues()
.setMetadataWithRestResponseAsync(queueName, null, metadata, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves stored access policies specified on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>List the stored access policies</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getAccessPolicy}
*
* <p>For more information, see the
* <a href="https:
*
* @return The stored access policies specified on the queue.
* @throws StorageException If the queue doesn't exist
*/
public PagedFlux<SignedIdentifier> getAccessPolicy() {
Function<String, Mono<PagedResponse<SignedIdentifier>>> retriever =
marker -> postProcessResponse(this.client.queues()
.getAccessPolicyWithRestResponseAsync(queueName, Context.NONE))
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders()));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Sets stored access policies on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set a read only stored access policy</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.setAccessPolicy
*
* <p>For more information, see the
* <a href="https:
*
* @param permissions Access policies to set on the queue
* @return An empty response
* @throws StorageException If the queue doesn't exist, a stored access policy doesn't have all fields filled out,
* or the queue will have more than five policies.
*/
public Mono<Void> setAccessPolicy(List<SignedIdentifier> permissions) {
return setAccessPolicyWithResponse(permissions).flatMap(FluxUtil::toMono);
}
/**
* Sets stored access policies on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set a read only stored access policy</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.setAccessPolicyWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param permissions Access policies to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist, a stored access policy doesn't have all fields filled out,
* or the queue will have more than five policies.
*/
public Mono<Response<Void>> setAccessPolicyWithResponse(List<SignedIdentifier> permissions) {
return withContext(context -> setAccessPolicyWithResponse(permissions, context));
}
Mono<Response<Void>> setAccessPolicyWithResponse(List<SignedIdentifier> permissions, Context context) {
/*
We truncate to seconds because the service only supports nanoseconds or seconds, but doing an
OffsetDateTime.now will only give back milliseconds (more precise fields are zeroed and not serialized). This
allows for proper serialization with no real detriment to users as sub-second precision on active time for
signed identifiers is not really necessary.
*/
if (permissions != null) {
for (SignedIdentifier permission : permissions) {
if (permission.getAccessPolicy() != null && permission.getAccessPolicy().getStart() != null) {
permission.getAccessPolicy().setStart(
permission.getAccessPolicy().getStart().truncatedTo(ChronoUnit.SECONDS));
}
if (permission.getAccessPolicy() != null && permission.getAccessPolicy().getExpiry() != null) {
permission.getAccessPolicy().setExpiry(
permission.getAccessPolicy().getExpiry().truncatedTo(ChronoUnit.SECONDS));
}
}
}
return postProcessResponse(client.queues()
.setAccessPolicyWithRestResponseAsync(queueName, permissions, null, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Deletes all messages in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> clearMessages() {
return clearMessagesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Deletes all messages in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMessagesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> clearMessagesWithResponse() {
return withContext(this::clearMessagesWithResponse);
}
Mono<Response<Void>> clearMessagesWithResponse(Context context) {
return postProcessResponse(client.messages().clearWithRestResponseAsync(queueName, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Enqueues a message that has a time-to-live of 7 days and is instantly visible.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Enqueue a message of "Hello, Azure"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.enqueueMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Message text
* @return A {@link EnqueuedMessage} value that contains the {@link EnqueuedMessage
* {@link EnqueuedMessage
* about the enqueued message.
* @throws StorageException If the queue doesn't exist
*/
public Mono<EnqueuedMessage> enqueueMessage(String messageText) {
return enqueueMessageWithResponse(messageText, null, null).flatMap(FluxUtil::toMono);
}
/**
* Enqueues a message with a given time-to-live and a timeout period where the message is invisible in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a message of "Hello, Azure" that has a timeout of 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.enqueueMessageWithResponse
*
* <p>Add a message of "Goodbye, Azure" that has a time to live of 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.enqueueMessageWithResponse-liveTime
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Message text
* @param visibilityTimeout Optional. The timeout period for how long the message is invisible in the queue. If
* unset the value will default to 0 and the message will be instantly visible. The timeout must be between 0
* seconds and 7 days.
* @param timeToLive Optional. How long the message will stay alive in the queue. If unset the value will default to
* 7 days, if -1 is passed the message will not expire. The time to live must be -1 or any positive number.
* @return A {@link EnqueuedMessage} value that contains the {@link EnqueuedMessage
* {@link EnqueuedMessage
* about the enqueued message.
* @throws StorageException If the queue doesn't exist or the {@code visibilityTimeout} or {@code timeToLive} are
* outside of the allowed limits.
*/
public Mono<Response<EnqueuedMessage>> enqueueMessageWithResponse(String messageText, Duration visibilityTimeout,
Duration timeToLive) {
return withContext(context -> enqueueMessageWithResponse(messageText, visibilityTimeout, timeToLive, context));
}
Mono<Response<EnqueuedMessage>> enqueueMessageWithResponse(String messageText, Duration visibilityTimeout,
Duration timeToLive, Context context) {
Integer visibilityTimeoutInSeconds = (visibilityTimeout == null) ? null : (int) visibilityTimeout.getSeconds();
Integer timeToLiveInSeconds = (timeToLive == null) ? null : (int) timeToLive.getSeconds();
QueueMessage message = new QueueMessage().setMessageText(messageText);
return postProcessResponse(client.messages()
.enqueueWithRestResponseAsync(queueName, message, visibilityTimeoutInSeconds, timeToLiveInSeconds,
null, null, context))
.map(response -> new SimpleResponse<>(response, response.getValue().get(0)));
}
/**
* Retrieves the first message in the queue and hides it from other operations for 30 seconds.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue a message</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return The first {@link DequeuedMessage} in the queue, it contains {@link DequeuedMessage
* messageId} and {@link DequeuedMessage
* it contains other metadata about the message.
* @throws StorageException If the queue doesn't exist
*/
public PagedFlux<DequeuedMessage> dequeueMessages() {
return dequeueMessagesWithOptionalTimeout(1, null, null, Context.NONE);
}
/**
* Retrieves up to the maximum number of messages from the queue and hides them from other operations for 30
* seconds.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue up to 5 messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to get, if there are less messages exist in the queue
* than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed
* range is 1 to 32 messages.
* @return Up to {@code maxMessages} {@link DequeuedMessage DequeuedMessages} from the queue. Each DequeuedMessage
* contains {@link DequeuedMessage
* used to interact with the message and other metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} is outside of the allowed bounds
*/
public PagedFlux<DequeuedMessage> dequeueMessages(Integer maxMessages) {
return dequeueMessagesWithOptionalTimeout(maxMessages, null, null, Context.NONE);
}
/**
* Retrieves up to the maximum number of messages from the queue and hides them from other operations for the
* timeout period.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue up to 5 messages and give them a 60 second timeout period</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to get, if there are less messages exist in the queue
* than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed
* range is 1 to 32 messages.
* @param visibilityTimeout Optional. The timeout period for how long the message is invisible in the queue. If left
* empty the dequeued messages will be invisible for 30 seconds. The timeout must be between 1 second and 7 days.
* @return Up to {@code maxMessages} {@link DequeuedMessage DequeuedMessages} from the queue. Each DeqeuedMessage
* contains {@link DequeuedMessage
* used to interact with the message and other metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} or {@code visibilityTimeout} is
* outside of the allowed bounds
*/
public PagedFlux<DequeuedMessage> dequeueMessages(Integer maxMessages, Duration visibilityTimeout) {
return dequeueMessagesWithOptionalTimeout(maxMessages, visibilityTimeout, null, Context.NONE);
}
PagedFlux<DequeuedMessage> dequeueMessagesWithOptionalTimeout(Integer maxMessages, Duration visibilityTimeout,
Duration timeout, Context context) {
Integer visibilityTimeoutInSeconds = (visibilityTimeout == null) ? null : (int) visibilityTimeout.getSeconds();
Function<String, Mono<PagedResponse<DequeuedMessage>>> retriever =
marker -> postProcessResponse(Utility.applyOptionalTimeout(this.client.messages()
.dequeueWithRestResponseAsync(queueName, maxMessages, visibilityTimeoutInSeconds,
null, null, context), timeout)
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders())));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Peeks the first message in the queue.
*
* Peeked messages don't contain the necessary information needed to interact with the message nor will it hide
* messages from other operations on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Peek the first message</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.peekMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return A {@link PeekedMessage} that contains metadata about the message.
*/
public PagedFlux<PeekedMessage> peekMessages() {
return peekMessages(null);
}
/**
* Peek messages from the front of the queue up to the maximum number of messages.
*
* Peeked messages don't contain the necessary information needed to interact with the message nor will it hide
* messages from other operations on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Peek up to the first five messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.peekMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to peek, if there are less messages exist in the queue
* than requested all the messages will be peeked. If left empty only 1 message will be peeked, the allowed range is
* 1 to 32 messages.
* @return Up to {@code maxMessages} {@link PeekedMessage PeekedMessages} from the queue. Each PeekedMessage
* contains metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} is outside of the allowed bounds
*/
public PagedFlux<PeekedMessage> peekMessages(Integer maxMessages) {
return peekMessagesWithOptionalTimeout(maxMessages, null, Context.NONE);
}
PagedFlux<PeekedMessage> peekMessagesWithOptionalTimeout(Integer maxMessages, Duration timeout, Context context) {
Function<String, Mono<PagedResponse<PeekedMessage>>> retriever =
marker -> postProcessResponse(Utility.applyOptionalTimeout(this.client.messages()
.peekWithRestResponseAsync(queueName, maxMessages, null, null, context), timeout)
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders())));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Updates the specific message in the queue with a new message and resets the visibility timeout.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue the first message and update it to "Hello again, Azure" and hide it for 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.updateMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Updated value for the message
* @param messageId Id of the message to update
* @param popReceipt Unique identifier that must match for the message to be updated
* @param visibilityTimeout The timeout period for how long the message is invisible in the queue in seconds. The
* timeout period must be between 1 second and 7 days.
* @return A {@link UpdatedMessage} that contains the new {@link UpdatedMessage
* interact with the message, additionally contains the updated metadata about the message.
* @throws StorageException If the queue or messageId don't exist, the popReceipt doesn't match on the message, or
* the {@code visibilityTimeout} is outside the allowed bounds
*/
public Mono<UpdatedMessage> updateMessage(String messageText, String messageId, String popReceipt,
Duration visibilityTimeout) {
return updateMessageWithResponse(messageText, messageId, popReceipt, visibilityTimeout)
.flatMap(FluxUtil::toMono);
}
/**
* Updates the specific message in the queue with a new message and resets the visibility timeout.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue the first message and update it to "Hello again, Azure" and hide it for 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.updateMessageWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Updated value for the message
* @param messageId Id of the message to update
* @param popReceipt Unique identifier that must match for the message to be updated
* @param visibilityTimeout The timeout period for how long the message is invisible in the queue in seconds. The
* timeout period must be between 1 second and 7 days.
* @return A {@link UpdatedMessage} that contains the new {@link UpdatedMessage
* interact with the message, additionally contains the updated metadata about the message.
* @throws StorageException If the queue or messageId don't exist, the popReceipt doesn't match on the message, or
* the {@code visibilityTimeout} is outside the allowed bounds
*/
public Mono<Response<UpdatedMessage>> updateMessageWithResponse(String messageText, String messageId,
String popReceipt, Duration visibilityTimeout) {
return withContext(context ->
updateMessageWithResponse(messageText, messageId, popReceipt, visibilityTimeout, context));
}
Mono<Response<UpdatedMessage>> updateMessageWithResponse(String messageText, String messageId, String popReceipt,
Duration visibilityTimeout, Context context) {
QueueMessage message = new QueueMessage().setMessageText(messageText);
return postProcessResponse(client.messageIds()
.updateWithRestResponseAsync(queueName, messageId, message, popReceipt,
(int) visibilityTimeout.getSeconds(), context))
.map(this::getUpdatedMessageResponse);
}
/**
* Deletes the specified message in the queue
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the first message</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.deleteMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageId Id of the message to deleted
* @param popReceipt Unique identifier that must match for the message to be deleted
* @return An empty response
* @throws StorageException If the queue or messageId don't exist or the popReceipt doesn't match on the message
*/
public Mono<Void> deleteMessage(String messageId, String popReceipt) {
return deleteMessageWithResponse(messageId, popReceipt).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified message in the queue
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the first message</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.deleteMessageWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param messageId Id of the message to deleted
* @param popReceipt Unique identifier that must match for the message to be deleted
* @return A response that only contains headers and response status code
* @throws StorageException If the queue or messageId don't exist or the popReceipt doesn't match on the message
*/
public Mono<Response<Void>> deleteMessageWithResponse(String messageId, String popReceipt) {
return withContext(context -> deleteMessageWithResponse(messageId, popReceipt, context));
}
Mono<Response<Void>> deleteMessageWithResponse(String messageId, String popReceipt, Context context) {
return postProcessResponse(client.messageIds()
.deleteWithRestResponseAsync(queueName, messageId, popReceipt, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Generates a SAS token with the specified parameters
*
* @param permissions The {@code QueueSASPermission} permission for the SAS
* @param expiryTime The {@code OffsetDateTime} expiry time for the SAS
* @return A string that represents the SAS token
*/
public String generateSAS(QueueSASPermission permissions, OffsetDateTime expiryTime) {
return this.generateSAS(null, permissions, expiryTime, null /* startTime */, /* identifier */ null /*
version */, null /* sasProtocol */, null /* ipRange */);
}
/**
* Generates a SAS token with the specified parameters
*
* @param identifier The {@code String} name of the access policy on the queue this SAS references if any
* @return A string that represents the SAS token
*/
public String generateSAS(String identifier) {
return this.generateSAS(identifier, null /* permissions */, null /* expiryTime */, null /* startTime */,
null /* version */, null /* sasProtocol */, null /* ipRange */);
}
/**
* Generates a SAS token with the specified parameters
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.generateSAS
*
* <p>For more information, see the
* <a href="https:
*
* @param identifier The {@code String} name of the access policy on the queue this SAS references if any
* @param permissions The {@code QueueSASPermission} permission for the SAS
* @param expiryTime The {@code OffsetDateTime} expiry time for the SAS
* @param startTime An optional {@code OffsetDateTime} start time for the SAS
* @param version An optional {@code String} version for the SAS
* @param sasProtocol An optional {@code SASProtocol} protocol for the SAS
* @param ipRange An optional {@code IPRange} ip address range for the SAS
* @return A string that represents the SAS token
*/
public String generateSAS(String identifier, QueueSASPermission permissions, OffsetDateTime expiryTime,
OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) {
QueueServiceSASSignatureValues queueServiceSASSignatureValues = new QueueServiceSASSignatureValues(version,
sasProtocol, startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange,
identifier);
SharedKeyCredential sharedKeyCredential =
Utility.getSharedKeyCredential(this.client.getHttpPipeline());
Utility.assertNotNull("sharedKeyCredential", sharedKeyCredential);
QueueServiceSASSignatureValues values = queueServiceSASSignatureValues
.setCanonicalName(this.queueName, sharedKeyCredential.getAccountName());
QueueServiceSASQueryParameters queueServiceSasQueryParameters = values
.generateSASQueryParameters(sharedKeyCredential);
return queueServiceSasQueryParameters.encode();
}
/**
* Get the queue name of the client.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getQueueName}
*
* @return The name of the queue.
*/
public String getQueueName() {
return queueName;
}
/*
* Maps the HTTP headers returned from the service to the expected response type
* @param response Service response
* @return Mapped response
*/
private Response<QueueProperties> getQueuePropertiesResponse(QueuesGetPropertiesResponse response) {
QueueGetPropertiesHeaders propertiesHeaders = response.getDeserializedHeaders();
QueueProperties properties = new QueueProperties(propertiesHeaders.getMetadata(),
propertiesHeaders.getApproximateMessagesCount());
return new SimpleResponse<>(response, properties);
}
/*
* Maps the HTTP headers returned from the service to the expected response type
* @param response Service response
* @return Mapped response
*/
private Response<UpdatedMessage> getUpdatedMessageResponse(MessageIdsUpdateResponse response) {
MessageIdUpdateHeaders headers = response.getDeserializedHeaders();
UpdatedMessage updatedMessage = new UpdatedMessage(headers.getPopReceipt(), headers.getTimeNextVisible());
return new SimpleResponse<>(response, updatedMessage);
}
} |
Good catch. | public URL getQueueUrl() {
try {
return new URL(String.format("%s/%s", client.getUrl(), queueName));
} catch (MalformedURLException ex) {
logger.error("Queue URL is malformed");
throw logger.logExceptionAsError(new RuntimeException("Queue URL is malformed"));
}
} | throw logger.logExceptionAsError(new RuntimeException("Queue URL is malformed")); | public URL getQueueUrl() {
try {
return new URL(String.format("%s/%s", client.getUrl(), queueName));
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new RuntimeException("Queue URL is malformed"));
}
} | class QueueAsyncClient {
private final ClientLogger logger = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@link
* Each service call goes through the {@link HttpPipeline pipeline}.
*
* @param client Client that interacts with the service interfaces
* @param queueName Name of the queue
*/
QueueAsyncClient(AzureQueueStorageImpl client, String queueName) {
Objects.requireNonNull(queueName);
this.queueName = queueName;
this.client = client;
}
/**
* @return the URL of the storage queue
* @throws RuntimeException If the queue is using a malformed URL.
*/
/**
* Creates a new queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.create}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If a queue with the same name already exists in the queue service.
*/
public Mono<Void> create() {
return createWithResponse(null).flatMap(FluxUtil::toMono);
}
/**
* Creates a new queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create a queue with metadata "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.createWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the queue
* @return A response that only contains headers and response status code
* @throws StorageException If a queue with the same name and different metadata already exists in the queue
* service.
*/
public Mono<Response<Void>> createWithResponse(Map<String, String> metadata) {
return withContext(context -> createWithResponse(metadata, context));
}
Mono<Response<Void>> createWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(client.queues()
.createWithRestResponseAsync(queueName, null, metadata, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Permanently deletes the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> delete() {
return deleteWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Permanently deletes the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.deleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> deleteWithResponse() {
return withContext(this::deleteWithResponse);
}
Mono<Response<Void>> deleteWithResponse(Context context) {
return postProcessResponse(client.queues().deleteWithRestResponseAsync(queueName, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves metadata and approximate message count of the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the properties of the queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link QueueProperties} value which contains the metadata and approximate
* messages count of the queue.
* @throws StorageException If the queue doesn't exist
*/
public Mono<QueueProperties> getProperties() {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Retrieves metadata and approximate message count of the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the properties of the queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getPropertiesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link QueueProperties} value which contains the metadata and approximate
* messages count of the queue.
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<QueueProperties>> getPropertiesWithResponse() {
return withContext(this::getPropertiesWithResponse);
}
Mono<Response<QueueProperties>> getPropertiesWithResponse(Context context) {
return postProcessResponse(client.queues().getPropertiesWithRestResponseAsync(queueName, context))
.map(this::getQueuePropertiesResponse);
}
/**
* Sets the metadata of the queue.
*
* Passing in a {@code null} value for metadata will clear the metadata associated with the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the queue's metadata to "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.setMetadata
*
* <p>Clear the queue's metadata</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono);
}
/**
* Sets the metadata of the queue.
*
* Passing in a {@code null} value for metadata will clear the metadata associated with the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the queue's metadata to "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.setMetadataWithResponse
*
* <p>Clear the queue's metadata</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata) {
return withContext(context -> setMetadataWithResponse(metadata, context));
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(client.queues()
.setMetadataWithRestResponseAsync(queueName, null, metadata, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves stored access policies specified on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>List the stored access policies</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getAccessPolicy}
*
* <p>For more information, see the
* <a href="https:
*
* @return The stored access policies specified on the queue.
* @throws StorageException If the queue doesn't exist
*/
public PagedFlux<SignedIdentifier> getAccessPolicy() {
Function<String, Mono<PagedResponse<SignedIdentifier>>> retriever =
marker -> postProcessResponse(this.client.queues()
.getAccessPolicyWithRestResponseAsync(queueName, Context.NONE))
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders()));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Sets stored access policies on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set a read only stored access policy</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.setAccessPolicy
*
* <p>For more information, see the
* <a href="https:
*
* @param permissions Access policies to set on the queue
* @return An empty response
* @throws StorageException If the queue doesn't exist, a stored access policy doesn't have all fields filled out,
* or the queue will have more than five policies.
*/
public Mono<Void> setAccessPolicy(List<SignedIdentifier> permissions) {
return setAccessPolicyWithResponse(permissions).flatMap(FluxUtil::toMono);
}
/**
* Sets stored access policies on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set a read only stored access policy</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.setAccessPolicyWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param permissions Access policies to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist, a stored access policy doesn't have all fields filled out,
* or the queue will have more than five policies.
*/
public Mono<Response<Void>> setAccessPolicyWithResponse(List<SignedIdentifier> permissions) {
return withContext(context -> setAccessPolicyWithResponse(permissions, context));
}
Mono<Response<Void>> setAccessPolicyWithResponse(List<SignedIdentifier> permissions, Context context) {
/*
We truncate to seconds because the service only supports nanoseconds or seconds, but doing an
OffsetDateTime.now will only give back milliseconds (more precise fields are zeroed and not serialized). This
allows for proper serialization with no real detriment to users as sub-second precision on active time for
signed identifiers is not really necessary.
*/
if (permissions != null) {
for (SignedIdentifier permission : permissions) {
if (permission.getAccessPolicy() != null && permission.getAccessPolicy().getStart() != null) {
permission.getAccessPolicy().setStart(
permission.getAccessPolicy().getStart().truncatedTo(ChronoUnit.SECONDS));
}
if (permission.getAccessPolicy() != null && permission.getAccessPolicy().getExpiry() != null) {
permission.getAccessPolicy().setExpiry(
permission.getAccessPolicy().getExpiry().truncatedTo(ChronoUnit.SECONDS));
}
}
}
return postProcessResponse(client.queues()
.setAccessPolicyWithRestResponseAsync(queueName, permissions, null, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Deletes all messages in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> clearMessages() {
return clearMessagesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Deletes all messages in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMessagesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> clearMessagesWithResponse() {
return withContext(this::clearMessagesWithResponse);
}
Mono<Response<Void>> clearMessagesWithResponse(Context context) {
return postProcessResponse(client.messages().clearWithRestResponseAsync(queueName, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Enqueues a message that has a time-to-live of 7 days and is instantly visible.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Enqueue a message of "Hello, Azure"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.enqueueMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Message text
* @return A {@link EnqueuedMessage} value that contains the {@link EnqueuedMessage
* {@link EnqueuedMessage
* about the enqueued message.
* @throws StorageException If the queue doesn't exist
*/
public Mono<EnqueuedMessage> enqueueMessage(String messageText) {
return enqueueMessageWithResponse(messageText, null, null).flatMap(FluxUtil::toMono);
}
/**
* Enqueues a message with a given time-to-live and a timeout period where the message is invisible in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a message of "Hello, Azure" that has a timeout of 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.enqueueMessageWithResponse
*
* <p>Add a message of "Goodbye, Azure" that has a time to live of 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.enqueueMessageWithResponse-liveTime
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Message text
* @param visibilityTimeout Optional. The timeout period for how long the message is invisible in the queue. If
* unset the value will default to 0 and the message will be instantly visible. The timeout must be between 0
* seconds and 7 days.
* @param timeToLive Optional. How long the message will stay alive in the queue. If unset the value will default to
* 7 days, if -1 is passed the message will not expire. The time to live must be -1 or any positive number.
* @return A {@link EnqueuedMessage} value that contains the {@link EnqueuedMessage
* {@link EnqueuedMessage
* about the enqueued message.
* @throws StorageException If the queue doesn't exist or the {@code visibilityTimeout} or {@code timeToLive} are
* outside of the allowed limits.
*/
public Mono<Response<EnqueuedMessage>> enqueueMessageWithResponse(String messageText, Duration visibilityTimeout,
Duration timeToLive) {
return withContext(context -> enqueueMessageWithResponse(messageText, visibilityTimeout, timeToLive, context));
}
Mono<Response<EnqueuedMessage>> enqueueMessageWithResponse(String messageText, Duration visibilityTimeout,
Duration timeToLive, Context context) {
Integer visibilityTimeoutInSeconds = (visibilityTimeout == null) ? null : (int) visibilityTimeout.getSeconds();
Integer timeToLiveInSeconds = (timeToLive == null) ? null : (int) timeToLive.getSeconds();
QueueMessage message = new QueueMessage().setMessageText(messageText);
return postProcessResponse(client.messages()
.enqueueWithRestResponseAsync(queueName, message, visibilityTimeoutInSeconds, timeToLiveInSeconds,
null, null, context))
.map(response -> new SimpleResponse<>(response, response.getValue().get(0)));
}
/**
* Retrieves the first message in the queue and hides it from other operations for 30 seconds.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue a message</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return The first {@link DequeuedMessage} in the queue, it contains {@link DequeuedMessage
* messageId} and {@link DequeuedMessage
* it contains other metadata about the message.
* @throws StorageException If the queue doesn't exist
*/
public PagedFlux<DequeuedMessage> dequeueMessages() {
return dequeueMessagesWithOptionalTimeout(1, null, null, Context.NONE);
}
/**
* Retrieves up to the maximum number of messages from the queue and hides them from other operations for 30
* seconds.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue up to 5 messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to get, if there are less messages exist in the queue
* than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed
* range is 1 to 32 messages.
* @return Up to {@code maxMessages} {@link DequeuedMessage DequeuedMessages} from the queue. Each DequeuedMessage
* contains {@link DequeuedMessage
* used to interact with the message and other metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} is outside of the allowed bounds
*/
public PagedFlux<DequeuedMessage> dequeueMessages(Integer maxMessages) {
return dequeueMessagesWithOptionalTimeout(maxMessages, null, null, Context.NONE);
}
/**
* Retrieves up to the maximum number of messages from the queue and hides them from other operations for the
* timeout period.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue up to 5 messages and give them a 60 second timeout period</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to get, if there are less messages exist in the queue
* than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed
* range is 1 to 32 messages.
* @param visibilityTimeout Optional. The timeout period for how long the message is invisible in the queue. If left
* empty the dequeued messages will be invisible for 30 seconds. The timeout must be between 1 second and 7 days.
* @return Up to {@code maxMessages} {@link DequeuedMessage DequeuedMessages} from the queue. Each DeqeuedMessage
* contains {@link DequeuedMessage
* used to interact with the message and other metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} or {@code visibilityTimeout} is
* outside of the allowed bounds
*/
public PagedFlux<DequeuedMessage> dequeueMessages(Integer maxMessages, Duration visibilityTimeout) {
return dequeueMessagesWithOptionalTimeout(maxMessages, visibilityTimeout, null, Context.NONE);
}
PagedFlux<DequeuedMessage> dequeueMessagesWithOptionalTimeout(Integer maxMessages, Duration visibilityTimeout,
Duration timeout, Context context) {
Integer visibilityTimeoutInSeconds = (visibilityTimeout == null) ? null : (int) visibilityTimeout.getSeconds();
Function<String, Mono<PagedResponse<DequeuedMessage>>> retriever =
marker -> postProcessResponse(Utility.applyOptionalTimeout(this.client.messages()
.dequeueWithRestResponseAsync(queueName, maxMessages, visibilityTimeoutInSeconds,
null, null, context), timeout)
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders())));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Peeks the first message in the queue.
*
* Peeked messages don't contain the necessary information needed to interact with the message nor will it hide
* messages from other operations on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Peek the first message</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.peekMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return A {@link PeekedMessage} that contains metadata about the message.
*/
public PagedFlux<PeekedMessage> peekMessages() {
return peekMessages(null);
}
/**
* Peek messages from the front of the queue up to the maximum number of messages.
*
* Peeked messages don't contain the necessary information needed to interact with the message nor will it hide
* messages from other operations on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Peek up to the first five messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.peekMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to peek, if there are less messages exist in the queue
* than requested all the messages will be peeked. If left empty only 1 message will be peeked, the allowed range is
* 1 to 32 messages.
* @return Up to {@code maxMessages} {@link PeekedMessage PeekedMessages} from the queue. Each PeekedMessage
* contains metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} is outside of the allowed bounds
*/
public PagedFlux<PeekedMessage> peekMessages(Integer maxMessages) {
return peekMessagesWithOptionalTimeout(maxMessages, null, Context.NONE);
}
PagedFlux<PeekedMessage> peekMessagesWithOptionalTimeout(Integer maxMessages, Duration timeout, Context context) {
Function<String, Mono<PagedResponse<PeekedMessage>>> retriever =
marker -> postProcessResponse(Utility.applyOptionalTimeout(this.client.messages()
.peekWithRestResponseAsync(queueName, maxMessages, null, null, context), timeout)
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders())));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Updates the specific message in the queue with a new message and resets the visibility timeout.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue the first message and update it to "Hello again, Azure" and hide it for 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.updateMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Updated value for the message
* @param messageId Id of the message to update
* @param popReceipt Unique identifier that must match for the message to be updated
* @param visibilityTimeout The timeout period for how long the message is invisible in the queue in seconds. The
* timeout period must be between 1 second and 7 days.
* @return A {@link UpdatedMessage} that contains the new {@link UpdatedMessage
* interact with the message, additionally contains the updated metadata about the message.
* @throws StorageException If the queue or messageId don't exist, the popReceipt doesn't match on the message, or
* the {@code visibilityTimeout} is outside the allowed bounds
*/
public Mono<UpdatedMessage> updateMessage(String messageText, String messageId, String popReceipt,
Duration visibilityTimeout) {
return updateMessageWithResponse(messageText, messageId, popReceipt, visibilityTimeout)
.flatMap(FluxUtil::toMono);
}
/**
* Updates the specific message in the queue with a new message and resets the visibility timeout.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue the first message and update it to "Hello again, Azure" and hide it for 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.updateMessageWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Updated value for the message
* @param messageId Id of the message to update
* @param popReceipt Unique identifier that must match for the message to be updated
* @param visibilityTimeout The timeout period for how long the message is invisible in the queue in seconds. The
* timeout period must be between 1 second and 7 days.
* @return A {@link UpdatedMessage} that contains the new {@link UpdatedMessage
* interact with the message, additionally contains the updated metadata about the message.
* @throws StorageException If the queue or messageId don't exist, the popReceipt doesn't match on the message, or
* the {@code visibilityTimeout} is outside the allowed bounds
*/
public Mono<Response<UpdatedMessage>> updateMessageWithResponse(String messageText, String messageId,
String popReceipt, Duration visibilityTimeout) {
return withContext(context ->
updateMessageWithResponse(messageText, messageId, popReceipt, visibilityTimeout, context));
}
Mono<Response<UpdatedMessage>> updateMessageWithResponse(String messageText, String messageId, String popReceipt,
Duration visibilityTimeout, Context context) {
QueueMessage message = new QueueMessage().setMessageText(messageText);
return postProcessResponse(client.messageIds()
.updateWithRestResponseAsync(queueName, messageId, message, popReceipt,
(int) visibilityTimeout.getSeconds(), context))
.map(this::getUpdatedMessageResponse);
}
/**
* Deletes the specified message in the queue
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the first message</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.deleteMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageId Id of the message to deleted
* @param popReceipt Unique identifier that must match for the message to be deleted
* @return An empty response
* @throws StorageException If the queue or messageId don't exist or the popReceipt doesn't match on the message
*/
public Mono<Void> deleteMessage(String messageId, String popReceipt) {
return deleteMessageWithResponse(messageId, popReceipt).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified message in the queue
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the first message</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.deleteMessageWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param messageId Id of the message to deleted
* @param popReceipt Unique identifier that must match for the message to be deleted
* @return A response that only contains headers and response status code
* @throws StorageException If the queue or messageId don't exist or the popReceipt doesn't match on the message
*/
public Mono<Response<Void>> deleteMessageWithResponse(String messageId, String popReceipt) {
return withContext(context -> deleteMessageWithResponse(messageId, popReceipt, context));
}
Mono<Response<Void>> deleteMessageWithResponse(String messageId, String popReceipt, Context context) {
return postProcessResponse(client.messageIds()
.deleteWithRestResponseAsync(queueName, messageId, popReceipt, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Generates a SAS token with the specified parameters
*
* @param permissions The {@code QueueSASPermission} permission for the SAS
* @param expiryTime The {@code OffsetDateTime} expiry time for the SAS
* @return A string that represents the SAS token
*/
public String generateSAS(QueueSASPermission permissions, OffsetDateTime expiryTime) {
return this.generateSAS(null, permissions, expiryTime, null /* startTime */, /* identifier */ null /*
version */, null /* sasProtocol */, null /* ipRange */);
}
/**
* Generates a SAS token with the specified parameters
*
* @param identifier The {@code String} name of the access policy on the queue this SAS references if any
* @return A string that represents the SAS token
*/
public String generateSAS(String identifier) {
return this.generateSAS(identifier, null /* permissions */, null /* expiryTime */, null /* startTime */,
null /* version */, null /* sasProtocol */, null /* ipRange */);
}
/**
* Generates a SAS token with the specified parameters
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.generateSAS
*
* <p>For more information, see the
* <a href="https:
*
* @param identifier The {@code String} name of the access policy on the queue this SAS references if any
* @param permissions The {@code QueueSASPermission} permission for the SAS
* @param expiryTime The {@code OffsetDateTime} expiry time for the SAS
* @param startTime An optional {@code OffsetDateTime} start time for the SAS
* @param version An optional {@code String} version for the SAS
* @param sasProtocol An optional {@code SASProtocol} protocol for the SAS
* @param ipRange An optional {@code IPRange} ip address range for the SAS
* @return A string that represents the SAS token
*/
public String generateSAS(String identifier, QueueSASPermission permissions, OffsetDateTime expiryTime,
OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) {
QueueServiceSASSignatureValues queueServiceSASSignatureValues = new QueueServiceSASSignatureValues(version,
sasProtocol, startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange,
identifier);
SharedKeyCredential sharedKeyCredential =
Utility.getSharedKeyCredential(this.client.getHttpPipeline());
Utility.assertNotNull("sharedKeyCredential", sharedKeyCredential);
QueueServiceSASSignatureValues values = queueServiceSASSignatureValues
.setCanonicalName(this.queueName, sharedKeyCredential.getAccountName());
QueueServiceSASQueryParameters queueServiceSasQueryParameters = values
.generateSASQueryParameters(sharedKeyCredential);
return queueServiceSasQueryParameters.encode();
}
/**
* Get the queue name of the client.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getQueueName}
*
* @return The name of the queue.
*/
public String getQueueName() {
return queueName;
}
/*
* Maps the HTTP headers returned from the service to the expected response type
* @param response Service response
* @return Mapped response
*/
private Response<QueueProperties> getQueuePropertiesResponse(QueuesGetPropertiesResponse response) {
QueueGetPropertiesHeaders propertiesHeaders = response.getDeserializedHeaders();
QueueProperties properties = new QueueProperties(propertiesHeaders.getMetadata(),
propertiesHeaders.getApproximateMessagesCount());
return new SimpleResponse<>(response, properties);
}
/*
* Maps the HTTP headers returned from the service to the expected response type
* @param response Service response
* @return Mapped response
*/
private Response<UpdatedMessage> getUpdatedMessageResponse(MessageIdsUpdateResponse response) {
MessageIdUpdateHeaders headers = response.getDeserializedHeaders();
UpdatedMessage updatedMessage = new UpdatedMessage(headers.getPopReceipt(), headers.getTimeNextVisible());
return new SimpleResponse<>(response, updatedMessage);
}
} | class QueueAsyncClient {
private final ClientLogger logger = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@link
* Each service call goes through the {@link HttpPipeline pipeline}.
*
* @param client Client that interacts with the service interfaces
* @param queueName Name of the queue
*/
QueueAsyncClient(AzureQueueStorageImpl client, String queueName) {
Objects.requireNonNull(queueName);
this.queueName = queueName;
this.client = client;
}
/**
* @return the URL of the storage queue
* @throws RuntimeException If the queue is using a malformed URL.
*/
/**
* Creates a new queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.create}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If a queue with the same name already exists in the queue service.
*/
public Mono<Void> create() {
return createWithResponse(null).flatMap(FluxUtil::toMono);
}
/**
* Creates a new queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Create a queue with metadata "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.createWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the queue
* @return A response that only contains headers and response status code
* @throws StorageException If a queue with the same name and different metadata already exists in the queue
* service.
*/
public Mono<Response<Void>> createWithResponse(Map<String, String> metadata) {
return withContext(context -> createWithResponse(metadata, context));
}
Mono<Response<Void>> createWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(client.queues()
.createWithRestResponseAsync(queueName, null, metadata, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Permanently deletes the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> delete() {
return deleteWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Permanently deletes the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete a queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.deleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> deleteWithResponse() {
return withContext(this::deleteWithResponse);
}
Mono<Response<Void>> deleteWithResponse(Context context) {
return postProcessResponse(client.queues().deleteWithRestResponseAsync(queueName, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves metadata and approximate message count of the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the properties of the queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link QueueProperties} value which contains the metadata and approximate
* messages count of the queue.
* @throws StorageException If the queue doesn't exist
*/
public Mono<QueueProperties> getProperties() {
return getPropertiesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Retrieves metadata and approximate message count of the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the properties of the queue</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getPropertiesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link QueueProperties} value which contains the metadata and approximate
* messages count of the queue.
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<QueueProperties>> getPropertiesWithResponse() {
return withContext(this::getPropertiesWithResponse);
}
Mono<Response<QueueProperties>> getPropertiesWithResponse(Context context) {
return postProcessResponse(client.queues().getPropertiesWithRestResponseAsync(queueName, context))
.map(this::getQueuePropertiesResponse);
}
/**
* Sets the metadata of the queue.
*
* Passing in a {@code null} value for metadata will clear the metadata associated with the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the queue's metadata to "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.setMetadata
*
* <p>Clear the queue's metadata</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono);
}
/**
* Sets the metadata of the queue.
*
* Passing in a {@code null} value for metadata will clear the metadata associated with the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the queue's metadata to "queue:metadataMap"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.setMetadataWithResponse
*
* <p>Clear the queue's metadata</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata) {
return withContext(context -> setMetadataWithResponse(metadata, context));
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, Context context) {
return postProcessResponse(client.queues()
.setMetadataWithRestResponseAsync(queueName, null, metadata, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Retrieves stored access policies specified on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>List the stored access policies</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getAccessPolicy}
*
* <p>For more information, see the
* <a href="https:
*
* @return The stored access policies specified on the queue.
* @throws StorageException If the queue doesn't exist
*/
public PagedFlux<SignedIdentifier> getAccessPolicy() {
Function<String, Mono<PagedResponse<SignedIdentifier>>> retriever =
marker -> postProcessResponse(this.client.queues()
.getAccessPolicyWithRestResponseAsync(queueName, Context.NONE))
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders()));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Sets stored access policies on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set a read only stored access policy</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.setAccessPolicy
*
* <p>For more information, see the
* <a href="https:
*
* @param permissions Access policies to set on the queue
* @return An empty response
* @throws StorageException If the queue doesn't exist, a stored access policy doesn't have all fields filled out,
* or the queue will have more than five policies.
*/
public Mono<Void> setAccessPolicy(List<SignedIdentifier> permissions) {
return setAccessPolicyWithResponse(permissions).flatMap(FluxUtil::toMono);
}
/**
* Sets stored access policies on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set a read only stored access policy</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.setAccessPolicyWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param permissions Access policies to set on the queue
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist, a stored access policy doesn't have all fields filled out,
* or the queue will have more than five policies.
*/
public Mono<Response<Void>> setAccessPolicyWithResponse(List<SignedIdentifier> permissions) {
return withContext(context -> setAccessPolicyWithResponse(permissions, context));
}
Mono<Response<Void>> setAccessPolicyWithResponse(List<SignedIdentifier> permissions, Context context) {
/*
We truncate to seconds because the service only supports nanoseconds or seconds, but doing an
OffsetDateTime.now will only give back milliseconds (more precise fields are zeroed and not serialized). This
allows for proper serialization with no real detriment to users as sub-second precision on active time for
signed identifiers is not really necessary.
*/
if (permissions != null) {
for (SignedIdentifier permission : permissions) {
if (permission.getAccessPolicy() != null && permission.getAccessPolicy().getStart() != null) {
permission.getAccessPolicy().setStart(
permission.getAccessPolicy().getStart().truncatedTo(ChronoUnit.SECONDS));
}
if (permission.getAccessPolicy() != null && permission.getAccessPolicy().getExpiry() != null) {
permission.getAccessPolicy().setExpiry(
permission.getAccessPolicy().getExpiry().truncatedTo(ChronoUnit.SECONDS));
}
}
}
return postProcessResponse(client.queues()
.setAccessPolicyWithRestResponseAsync(queueName, permissions, null, null, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Deletes all messages in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return An empty response
* @throws StorageException If the queue doesn't exist
*/
public Mono<Void> clearMessages() {
return clearMessagesWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Deletes all messages in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Clear the messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.clearMessagesWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response that only contains headers and response status code
* @throws StorageException If the queue doesn't exist
*/
public Mono<Response<Void>> clearMessagesWithResponse() {
return withContext(this::clearMessagesWithResponse);
}
Mono<Response<Void>> clearMessagesWithResponse(Context context) {
return postProcessResponse(client.messages().clearWithRestResponseAsync(queueName, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Enqueues a message that has a time-to-live of 7 days and is instantly visible.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Enqueue a message of "Hello, Azure"</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.enqueueMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Message text
* @return A {@link EnqueuedMessage} value that contains the {@link EnqueuedMessage
* {@link EnqueuedMessage
* about the enqueued message.
* @throws StorageException If the queue doesn't exist
*/
public Mono<EnqueuedMessage> enqueueMessage(String messageText) {
return enqueueMessageWithResponse(messageText, null, null).flatMap(FluxUtil::toMono);
}
/**
* Enqueues a message with a given time-to-live and a timeout period where the message is invisible in the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a message of "Hello, Azure" that has a timeout of 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.enqueueMessageWithResponse
*
* <p>Add a message of "Goodbye, Azure" that has a time to live of 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.enqueueMessageWithResponse-liveTime
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Message text
* @param visibilityTimeout Optional. The timeout period for how long the message is invisible in the queue. If
* unset the value will default to 0 and the message will be instantly visible. The timeout must be between 0
* seconds and 7 days.
* @param timeToLive Optional. How long the message will stay alive in the queue. If unset the value will default to
* 7 days, if -1 is passed the message will not expire. The time to live must be -1 or any positive number.
* @return A {@link EnqueuedMessage} value that contains the {@link EnqueuedMessage
* {@link EnqueuedMessage
* about the enqueued message.
* @throws StorageException If the queue doesn't exist or the {@code visibilityTimeout} or {@code timeToLive} are
* outside of the allowed limits.
*/
public Mono<Response<EnqueuedMessage>> enqueueMessageWithResponse(String messageText, Duration visibilityTimeout,
Duration timeToLive) {
return withContext(context -> enqueueMessageWithResponse(messageText, visibilityTimeout, timeToLive, context));
}
Mono<Response<EnqueuedMessage>> enqueueMessageWithResponse(String messageText, Duration visibilityTimeout,
Duration timeToLive, Context context) {
Integer visibilityTimeoutInSeconds = (visibilityTimeout == null) ? null : (int) visibilityTimeout.getSeconds();
Integer timeToLiveInSeconds = (timeToLive == null) ? null : (int) timeToLive.getSeconds();
QueueMessage message = new QueueMessage().setMessageText(messageText);
return postProcessResponse(client.messages()
.enqueueWithRestResponseAsync(queueName, message, visibilityTimeoutInSeconds, timeToLiveInSeconds,
null, null, context))
.map(response -> new SimpleResponse<>(response, response.getValue().get(0)));
}
/**
* Retrieves the first message in the queue and hides it from other operations for 30 seconds.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue a message</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return The first {@link DequeuedMessage} in the queue, it contains {@link DequeuedMessage
* messageId} and {@link DequeuedMessage
* it contains other metadata about the message.
* @throws StorageException If the queue doesn't exist
*/
public PagedFlux<DequeuedMessage> dequeueMessages() {
return dequeueMessagesWithOptionalTimeout(1, null, null, Context.NONE);
}
/**
* Retrieves up to the maximum number of messages from the queue and hides them from other operations for 30
* seconds.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue up to 5 messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to get, if there are less messages exist in the queue
* than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed
* range is 1 to 32 messages.
* @return Up to {@code maxMessages} {@link DequeuedMessage DequeuedMessages} from the queue. Each DequeuedMessage
* contains {@link DequeuedMessage
* used to interact with the message and other metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} is outside of the allowed bounds
*/
public PagedFlux<DequeuedMessage> dequeueMessages(Integer maxMessages) {
return dequeueMessagesWithOptionalTimeout(maxMessages, null, null, Context.NONE);
}
/**
* Retrieves up to the maximum number of messages from the queue and hides them from other operations for the
* timeout period.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue up to 5 messages and give them a 60 second timeout period</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.dequeueMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to get, if there are less messages exist in the queue
* than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed
* range is 1 to 32 messages.
* @param visibilityTimeout Optional. The timeout period for how long the message is invisible in the queue. If left
* empty the dequeued messages will be invisible for 30 seconds. The timeout must be between 1 second and 7 days.
* @return Up to {@code maxMessages} {@link DequeuedMessage DequeuedMessages} from the queue. Each DeqeuedMessage
* contains {@link DequeuedMessage
* used to interact with the message and other metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} or {@code visibilityTimeout} is
* outside of the allowed bounds
*/
public PagedFlux<DequeuedMessage> dequeueMessages(Integer maxMessages, Duration visibilityTimeout) {
return dequeueMessagesWithOptionalTimeout(maxMessages, visibilityTimeout, null, Context.NONE);
}
PagedFlux<DequeuedMessage> dequeueMessagesWithOptionalTimeout(Integer maxMessages, Duration visibilityTimeout,
Duration timeout, Context context) {
Integer visibilityTimeoutInSeconds = (visibilityTimeout == null) ? null : (int) visibilityTimeout.getSeconds();
Function<String, Mono<PagedResponse<DequeuedMessage>>> retriever =
marker -> postProcessResponse(Utility.applyOptionalTimeout(this.client.messages()
.dequeueWithRestResponseAsync(queueName, maxMessages, visibilityTimeoutInSeconds,
null, null, context), timeout)
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders())));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Peeks the first message in the queue.
*
* Peeked messages don't contain the necessary information needed to interact with the message nor will it hide
* messages from other operations on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Peek the first message</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.peekMessages}
*
* <p>For more information, see the
* <a href="https:
*
* @return A {@link PeekedMessage} that contains metadata about the message.
*/
public PagedFlux<PeekedMessage> peekMessages() {
return peekMessages(null);
}
/**
* Peek messages from the front of the queue up to the maximum number of messages.
*
* Peeked messages don't contain the necessary information needed to interact with the message nor will it hide
* messages from other operations on the queue.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Peek up to the first five messages</p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.peekMessages
*
* <p>For more information, see the
* <a href="https:
*
* @param maxMessages Optional. Maximum number of messages to peek, if there are less messages exist in the queue
* than requested all the messages will be peeked. If left empty only 1 message will be peeked, the allowed range is
* 1 to 32 messages.
* @return Up to {@code maxMessages} {@link PeekedMessage PeekedMessages} from the queue. Each PeekedMessage
* contains metadata about the message.
* @throws StorageException If the queue doesn't exist or {@code maxMessages} is outside of the allowed bounds
*/
public PagedFlux<PeekedMessage> peekMessages(Integer maxMessages) {
return peekMessagesWithOptionalTimeout(maxMessages, null, Context.NONE);
}
PagedFlux<PeekedMessage> peekMessagesWithOptionalTimeout(Integer maxMessages, Duration timeout, Context context) {
Function<String, Mono<PagedResponse<PeekedMessage>>> retriever =
marker -> postProcessResponse(Utility.applyOptionalTimeout(this.client.messages()
.peekWithRestResponseAsync(queueName, maxMessages, null, null, context), timeout)
.map(response -> new PagedResponseBase<>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue(),
null,
response.getDeserializedHeaders())));
return new PagedFlux<>(() -> retriever.apply(null), retriever);
}
/**
* Updates the specific message in the queue with a new message and resets the visibility timeout.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue the first message and update it to "Hello again, Azure" and hide it for 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.updateMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Updated value for the message
* @param messageId Id of the message to update
* @param popReceipt Unique identifier that must match for the message to be updated
* @param visibilityTimeout The timeout period for how long the message is invisible in the queue in seconds. The
* timeout period must be between 1 second and 7 days.
* @return A {@link UpdatedMessage} that contains the new {@link UpdatedMessage
* interact with the message, additionally contains the updated metadata about the message.
* @throws StorageException If the queue or messageId don't exist, the popReceipt doesn't match on the message, or
* the {@code visibilityTimeout} is outside the allowed bounds
*/
public Mono<UpdatedMessage> updateMessage(String messageText, String messageId, String popReceipt,
Duration visibilityTimeout) {
return updateMessageWithResponse(messageText, messageId, popReceipt, visibilityTimeout)
.flatMap(FluxUtil::toMono);
}
/**
* Updates the specific message in the queue with a new message and resets the visibility timeout.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Dequeue the first message and update it to "Hello again, Azure" and hide it for 5 seconds</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.updateMessageWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param messageText Updated value for the message
* @param messageId Id of the message to update
* @param popReceipt Unique identifier that must match for the message to be updated
* @param visibilityTimeout The timeout period for how long the message is invisible in the queue in seconds. The
* timeout period must be between 1 second and 7 days.
* @return A {@link UpdatedMessage} that contains the new {@link UpdatedMessage
* interact with the message, additionally contains the updated metadata about the message.
* @throws StorageException If the queue or messageId don't exist, the popReceipt doesn't match on the message, or
* the {@code visibilityTimeout} is outside the allowed bounds
*/
public Mono<Response<UpdatedMessage>> updateMessageWithResponse(String messageText, String messageId,
String popReceipt, Duration visibilityTimeout) {
return withContext(context ->
updateMessageWithResponse(messageText, messageId, popReceipt, visibilityTimeout, context));
}
Mono<Response<UpdatedMessage>> updateMessageWithResponse(String messageText, String messageId, String popReceipt,
Duration visibilityTimeout, Context context) {
QueueMessage message = new QueueMessage().setMessageText(messageText);
return postProcessResponse(client.messageIds()
.updateWithRestResponseAsync(queueName, messageId, message, popReceipt,
(int) visibilityTimeout.getSeconds(), context))
.map(this::getUpdatedMessageResponse);
}
/**
* Deletes the specified message in the queue
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the first message</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.deleteMessage
*
* <p>For more information, see the
* <a href="https:
*
* @param messageId Id of the message to deleted
* @param popReceipt Unique identifier that must match for the message to be deleted
* @return An empty response
* @throws StorageException If the queue or messageId don't exist or the popReceipt doesn't match on the message
*/
public Mono<Void> deleteMessage(String messageId, String popReceipt) {
return deleteMessageWithResponse(messageId, popReceipt).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified message in the queue
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the first message</p>
*
* {@codesnippet com.azure.storage.queue.QueueAsyncClient.deleteMessageWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param messageId Id of the message to deleted
* @param popReceipt Unique identifier that must match for the message to be deleted
* @return A response that only contains headers and response status code
* @throws StorageException If the queue or messageId don't exist or the popReceipt doesn't match on the message
*/
public Mono<Response<Void>> deleteMessageWithResponse(String messageId, String popReceipt) {
return withContext(context -> deleteMessageWithResponse(messageId, popReceipt, context));
}
Mono<Response<Void>> deleteMessageWithResponse(String messageId, String popReceipt, Context context) {
return postProcessResponse(client.messageIds()
.deleteWithRestResponseAsync(queueName, messageId, popReceipt, context))
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Generates a SAS token with the specified parameters
*
* @param permissions The {@code QueueSASPermission} permission for the SAS
* @param expiryTime The {@code OffsetDateTime} expiry time for the SAS
* @return A string that represents the SAS token
*/
public String generateSAS(QueueSASPermission permissions, OffsetDateTime expiryTime) {
return this.generateSAS(null, permissions, expiryTime, null /* startTime */, /* identifier */ null /*
version */, null /* sasProtocol */, null /* ipRange */);
}
/**
* Generates a SAS token with the specified parameters
*
* @param identifier The {@code String} name of the access policy on the queue this SAS references if any
* @return A string that represents the SAS token
*/
public String generateSAS(String identifier) {
return this.generateSAS(identifier, null /* permissions */, null /* expiryTime */, null /* startTime */,
null /* version */, null /* sasProtocol */, null /* ipRange */);
}
/**
* Generates a SAS token with the specified parameters
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.generateSAS
*
* <p>For more information, see the
* <a href="https:
*
* @param identifier The {@code String} name of the access policy on the queue this SAS references if any
* @param permissions The {@code QueueSASPermission} permission for the SAS
* @param expiryTime The {@code OffsetDateTime} expiry time for the SAS
* @param startTime An optional {@code OffsetDateTime} start time for the SAS
* @param version An optional {@code String} version for the SAS
* @param sasProtocol An optional {@code SASProtocol} protocol for the SAS
* @param ipRange An optional {@code IPRange} ip address range for the SAS
* @return A string that represents the SAS token
*/
public String generateSAS(String identifier, QueueSASPermission permissions, OffsetDateTime expiryTime,
OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) {
QueueServiceSASSignatureValues queueServiceSASSignatureValues = new QueueServiceSASSignatureValues(version,
sasProtocol, startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange,
identifier);
SharedKeyCredential sharedKeyCredential =
Utility.getSharedKeyCredential(this.client.getHttpPipeline());
Utility.assertNotNull("sharedKeyCredential", sharedKeyCredential);
QueueServiceSASSignatureValues values = queueServiceSASSignatureValues
.setCanonicalName(this.queueName, sharedKeyCredential.getAccountName());
QueueServiceSASQueryParameters queueServiceSasQueryParameters = values
.generateSASQueryParameters(sharedKeyCredential);
return queueServiceSasQueryParameters.encode();
}
/**
* Get the queue name of the client.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.queue.queueAsyncClient.getQueueName}
*
* @return The name of the queue.
*/
public String getQueueName() {
return queueName;
}
/*
* Maps the HTTP headers returned from the service to the expected response type
* @param response Service response
* @return Mapped response
*/
private Response<QueueProperties> getQueuePropertiesResponse(QueuesGetPropertiesResponse response) {
QueueGetPropertiesHeaders propertiesHeaders = response.getDeserializedHeaders();
QueueProperties properties = new QueueProperties(propertiesHeaders.getMetadata(),
propertiesHeaders.getApproximateMessagesCount());
return new SimpleResponse<>(response, properties);
}
/*
* Maps the HTTP headers returned from the service to the expected response type
* @param response Service response
* @return Mapped response
*/
private Response<UpdatedMessage> getUpdatedMessageResponse(MessageIdsUpdateResponse response) {
MessageIdUpdateHeaders headers = response.getDeserializedHeaders();
UpdatedMessage updatedMessage = new UpdatedMessage(headers.getPopReceipt(), headers.getTimeNextVisible());
return new SimpleResponse<>(response, updatedMessage);
}
} |
Any benefits of StringBuilder? | public URL getDirectoryUrl() {
String directoryURLString = String.format("%s/%s/%s", azureFileStorageClient.getUrl(),
shareName, directoryPath);
if (snapshot != null) {
directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot);
}
try {
return new URL(directoryURLString);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
}
} | directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot); | public URL getDirectoryUrl() {
StringBuilder directoryURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryURLString.append("?snapshot=").append(snapshot);
}
try {
return new URL(directoryURLString.toString());
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
}
} | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
* @throws RuntimeException If the directory is using a malformed URL.
*/
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
* @throws RuntimeException If the directory is using a malformed URL.
*/
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient |
Made the changes. | public URL getDirectoryUrl() {
String directoryURLString = String.format("%s/%s/%s", azureFileStorageClient.getUrl(),
shareName, directoryPath);
if (snapshot != null) {
directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot);
}
try {
return new URL(directoryURLString);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
}
} | directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot); | public URL getDirectoryUrl() {
StringBuilder directoryURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryURLString.append("?snapshot=").append(snapshot);
}
try {
return new URL(directoryURLString.toString());
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new RuntimeException(
String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
}
} | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
* @throws RuntimeException If the directory is using a malformed URL.
*/
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot) {
Objects.requireNonNull(shareName);
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
* @throws RuntimeException If the directory is using a malformed URL.
*/
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient |
`%n` | public void purgeDeletedCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
} | System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode())); | public void purgeDeletedCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
} | class CertificateAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RetryPolicy()).build();
CertificateAsyncClient keyClient = new CertificateClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async CertificateAsyncClient
* @return sync CertificateAsyncClient
*/
private CertificateAsyncClient getCertificateAsyncClient() {
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertiificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policy ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policy.issuerName(), policy.subjectName()));
certificateAsyncClient.getCertificatePolicyWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policyResponse ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policyResponse.getValue().issuerName(), policyResponse.getValue().subjectName()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
String certificateVersion = "6A385B124DEF4096AF1361A85B16C204";
certificateAsyncClient.getCertificateWithResponse("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s \n",
certificateWithVersion.getValue().name(), certificateWithVersion.getValue().secretId()));
certificateAsyncClient.getCertificate("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s \n",
certificateWithVersion.name(), certificateWithVersion.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
certificateAsyncClient.createCertificate("certificateName", certPolicy)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.createCertificateIssuer("issuerName", "providerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Issuer issuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuer(issuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.name(), issuerResponse.provider());
});
Issuer newIssuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuerWithResponse(newIssuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.name(), issuerResponse.provider());
}));
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuerWithResponse(issuerBase.getValue())
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
}));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s \n",
certificateResponse.enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuer(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s \n",
issuerResponse.enabled().toString()));
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuerWithResponse(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s \n",
issuerResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for
* {@link CertificateAsyncClient
*/
public void updateCertificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicy("certificateName", certificatePolicy)
.subscribe(updatedPolicy ->
System.out.printf("Certificate policy's updated transparency status %s \n",
updatedPolicy.certificateTransparency().toString()));
});
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicyWithResponse("certificateName",
certificatePolicy)
.subscribe(updatedPolicyResponse ->
System.out.printf("Certificate policy's updated transparency status %s \n",
updatedPolicyResponse.getValue().certificateTransparency().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificateWithResponse(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s \n",
certificateResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s \n", deletedIssuerResponse.getValue().name()));
certificateAsyncClient.deleteCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s \n", deletedIssuerResponse.name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getDeletedCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.getDeletedCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void purgeDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.doOnSuccess(response -> System.out.printf("Successfully Purged certificate \n"));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void recoverDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.recoverDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s \n", recoveredSecretResponse.name()));
certificateAsyncClient.recoverDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s \n", recoveredSecretResponse.getValue().name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void backupCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.backupCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s \n", certificateBackupResponse.length));
certificateAsyncClient.backupCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s \n",
certificateBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void restoreCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
byte[] certificateBackupByteArray = {};
certificateAsyncClient.restoreCertificate(certificateBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s \n",
certificateResponse.name(), certificateResponse.keyId()));
byte[] certificateBackup = {};
certificateAsyncClient.restoreCertificate(certificateBackup)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s \n",
certificateResponse.name(), certificateResponse.keyId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateIssuersCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateIssuers()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> System.out.printf("Received issuer with name %s and provider %s",
issuerResponse.name(), issuerResponse.provider())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listDeletedCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listDeletedCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedCertificateResponse.recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateVersionsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateVersions("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void contactsOperationsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
Contact oontactToAdd = new Contact("user", "useremail@exmaple.com");
certificateAsyncClient.setCertificateContacts(Arrays.asList(oontactToAdd)).subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Deleted Contact name %s and email %s", contact.name(), contact.emailAddress())
);
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* {@link CertificateAsyncClient
*/
public void certificateOperationCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.cancelCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Certificate operation status %s",
certificateOperation.status()));
certificateAsyncClient.cancelCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Certificate operation status %s",
certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Deleted Certificate operation's last"
+ " status %s", certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Deleted Certificate operation last status %s",
certificateOperation.status()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void getPendingCertificateSigningRequestCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getPendingCertificateSigningRequest("certificateName")
.subscribe(signingRequest -> System.out.printf("Received Signing request blob of length %s",
signingRequest.length));
certificateAsyncClient.getPendingCertificateSigningRequestWithResponse("certificateName")
.subscribe(signingRequestResponse -> System.out.printf("Received Signing request blob of length %s",
signingRequestResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void mergeCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
List<byte[]> x509Certs = new ArrayList<>();
certificateAsyncClient.mergeCertificate("certificateName", x509Certs)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509Certificates = new ArrayList<>();
certificateAsyncClient.mergeCertificateWithResponse("certificateName", x509Certificates)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
List<byte[]> x509CertificatesToMerge = new ArrayList<>();
MergeCertificateOptions config = new MergeCertificateOptions("certificateName", x509CertificatesToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificate(config)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509CertsToMerge = new ArrayList<>();
MergeCertificateOptions mergeConfig = new MergeCertificateOptions("certificateName", x509CertsToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificateWithResponse(mergeConfig)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
}
} | class CertificateAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RetryPolicy()).build();
CertificateAsyncClient keyClient = new CertificateClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async CertificateAsyncClient
* @return sync CertificateAsyncClient
*/
private CertificateAsyncClient getCertificateAsyncClient() {
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertiificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policy ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policy.issuerName(), policy.subjectName()));
certificateAsyncClient.getCertificatePolicyWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policyResponse ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policyResponse.getValue().issuerName(), policyResponse.getValue().subjectName()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
String certificateVersion = "6A385B124DEF4096AF1361A85B16C204";
certificateAsyncClient.getCertificateWithResponse("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s %n",
certificateWithVersion.getValue().name(), certificateWithVersion.getValue().secretId()));
certificateAsyncClient.getCertificate("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s %n",
certificateWithVersion.name(), certificateWithVersion.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
certificateAsyncClient.createCertificate("certificateName", certPolicy)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.createCertificateIssuer("issuerName", "providerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Issuer issuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuer(issuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.name(), issuerResponse.provider());
});
Issuer newIssuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuerWithResponse(newIssuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.name(), issuerResponse.provider());
}));
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuerWithResponse(issuerBase.getValue())
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
}));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s %n",
certificateResponse.enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuer(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s %n",
issuerResponse.enabled().toString()));
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuerWithResponse(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s %n",
issuerResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for
* {@link CertificateAsyncClient
*/
public void updateCertificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicy("certificateName", certificatePolicy)
.subscribe(updatedPolicy ->
System.out.printf("Certificate policy's updated transparency status %s %n",
updatedPolicy.certificateTransparency().toString()));
});
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicyWithResponse("certificateName",
certificatePolicy)
.subscribe(updatedPolicyResponse ->
System.out.printf("Certificate policy's updated transparency status %s %n",
updatedPolicyResponse.getValue().certificateTransparency().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificateWithResponse(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s %n",
certificateResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().name()));
certificateAsyncClient.deleteCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getDeletedCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.getDeletedCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void purgeDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.doOnSuccess(response -> System.out.println("Successfully Purged certificate"));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void recoverDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.recoverDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s %n", recoveredSecretResponse.name()));
certificateAsyncClient.recoverDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s %n", recoveredSecretResponse.getValue().name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void backupCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.backupCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s %n", certificateBackupResponse.length));
certificateAsyncClient.backupCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s %n",
certificateBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void restoreCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
byte[] certificateBackupByteArray = {};
certificateAsyncClient.restoreCertificate(certificateBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n",
certificateResponse.name(), certificateResponse.keyId()));
byte[] certificateBackup = {};
certificateAsyncClient.restoreCertificate(certificateBackup)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n",
certificateResponse.name(), certificateResponse.keyId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateIssuersCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateIssuers()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> System.out.printf("Received issuer with name %s and provider %s",
issuerResponse.name(), issuerResponse.provider())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listDeletedCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listDeletedCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedCertificateResponse.recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateVersionsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateVersions("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void contactsOperationsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
Contact oontactToAdd = new Contact("user", "useremail@exmaple.com");
certificateAsyncClient.setCertificateContacts(Arrays.asList(oontactToAdd)).subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Deleted Contact name %s and email %s", contact.name(), contact.emailAddress())
);
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* {@link CertificateAsyncClient
*/
public void certificateOperationCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.cancelCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Certificate operation status %s",
certificateOperation.status()));
certificateAsyncClient.cancelCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Certificate operation status %s",
certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Deleted Certificate operation's last"
+ " status %s", certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Deleted Certificate operation last status %s",
certificateOperation.status()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void getPendingCertificateSigningRequestCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getPendingCertificateSigningRequest("certificateName")
.subscribe(signingRequest -> System.out.printf("Received Signing request blob of length %s",
signingRequest.length));
certificateAsyncClient.getPendingCertificateSigningRequestWithResponse("certificateName")
.subscribe(signingRequestResponse -> System.out.printf("Received Signing request blob of length %s",
signingRequestResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void mergeCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
List<byte[]> x509Certs = new ArrayList<>();
certificateAsyncClient.mergeCertificate("certificateName", x509Certs)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509Certificates = new ArrayList<>();
certificateAsyncClient.mergeCertificateWithResponse("certificateName", x509Certificates)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
List<byte[]> x509CertificatesToMerge = new ArrayList<>();
MergeCertificateOptions config = new MergeCertificateOptions("certificateName", x509CertificatesToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificate(config)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509CertsToMerge = new ArrayList<>();
MergeCertificateOptions mergeConfig = new MergeCertificateOptions("certificateName", x509CertsToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificateWithResponse(mergeConfig)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
}
} |
You can uncomment this. Since it's verbose, it's most likely not logged and if verbose logging is enabled, then I guess logging this is okay. | public void onUnhandled(Event event) {
try {
super.onUnhandled(event);
} catch (NullPointerException e) {
logger.error("Exception occurred when handling event in super.", e);
}
} | public void onUnhandled(Event event) {
try {
super.onUnhandled(event);
} catch (NullPointerException e) {
logger.error("Exception occurred when handling event in super.", e);
}
} | class CustomIOHandler extends IOHandler {
private final ClientLogger logger = new ClientLogger(CustomIOHandler.class);
private final String connectionId;
public CustomIOHandler(final String connectionId) {
this.connectionId = connectionId;
}
@Override
public void onTransportClosed(Event event) {
final Transport transport = event.getTransport();
final Connection connection = event.getConnection();
logger.info("onTransportClosed name[{}], hostname[{}]",
connectionId, (connection != null ? connection.getHostname() : "n/a"));
if (transport != null && connection != null && connection.getTransport() != null) {
transport.unbind();
}
}
@Override
} | class CustomIOHandler extends IOHandler {
private final ClientLogger logger = new ClientLogger(CustomIOHandler.class);
private final String connectionId;
public CustomIOHandler(final String connectionId) {
this.connectionId = connectionId;
}
@Override
public void onTransportClosed(Event event) {
final Transport transport = event.getTransport();
final Connection connection = event.getConnection();
logger.info("onTransportClosed name[{}], hostname[{}]",
connectionId, (connection != null ? connection.getHostname() : "n/a"));
if (transport != null && connection != null && connection.getTransport() != null) {
transport.unbind();
}
}
@Override
} | |
Yeah. It's very, very verbose when it is enabled, because there are so many reactor events we don't bother to listen to. I guess that's why it's DEBUG. | public void onUnhandled(Event event) {
try {
super.onUnhandled(event);
} catch (NullPointerException e) {
logger.error("Exception occurred when handling event in super.", e);
}
} | public void onUnhandled(Event event) {
try {
super.onUnhandled(event);
} catch (NullPointerException e) {
logger.error("Exception occurred when handling event in super.", e);
}
} | class CustomIOHandler extends IOHandler {
private final ClientLogger logger = new ClientLogger(CustomIOHandler.class);
private final String connectionId;
public CustomIOHandler(final String connectionId) {
this.connectionId = connectionId;
}
@Override
public void onTransportClosed(Event event) {
final Transport transport = event.getTransport();
final Connection connection = event.getConnection();
logger.info("onTransportClosed name[{}], hostname[{}]",
connectionId, (connection != null ? connection.getHostname() : "n/a"));
if (transport != null && connection != null && connection.getTransport() != null) {
transport.unbind();
}
}
@Override
} | class CustomIOHandler extends IOHandler {
private final ClientLogger logger = new ClientLogger(CustomIOHandler.class);
private final String connectionId;
public CustomIOHandler(final String connectionId) {
this.connectionId = connectionId;
}
@Override
public void onTransportClosed(Event event) {
final Transport transport = event.getTransport();
final Connection connection = event.getConnection();
logger.info("onTransportClosed name[{}], hostname[{}]",
connectionId, (connection != null ? connection.getHostname() : "n/a"));
if (transport != null && connection != null && connection.getTransport() != null) {
transport.unbind();
}
}
@Override
} | |
Mind changing the `\n` to `%n` as expected in `printf` | public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException {
CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12")
.subjectAlternativeNames(SubjectAlternativeNames.fromEmails(Arrays.asList("wow@gmail.com")))
.keyOptions(new EcKeyOptions()
.reuseKey(true)
.curve(KeyCurveName.P_256));
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
String backupFilePath = "YOUR_BACKUP_FILE_PATH";
certificateAsyncClient.backupCertificate("certificateName")
.subscribe(certificateBackupResponse -> {
writeBackupToFile(certificateBackupResponse, backupFilePath);
System.out.printf("Certificate's Backup Byte array's length %s \n", certificateBackupResponse.length);
});
Thread.sleep(7000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
Thread.sleep(30000);
certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath());
certificateAsyncClient.restoreCertificate(backupFromFile)
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s \n",
certificateResponse.name(), certificateResponse.keyId()));
Thread.sleep(15000);
} | System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException {
CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12")
.subjectAlternativeNames(SubjectAlternativeNames.fromEmails(Arrays.asList("wow@gmail.com")))
.keyOptions(new EcKeyOptions()
.reuseKey(true)
.curve(KeyCurveName.P_256));
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
String backupFilePath = "YOUR_BACKUP_FILE_PATH";
certificateAsyncClient.backupCertificate("certificateName")
.subscribe(certificateBackupResponse -> {
writeBackupToFile(certificateBackupResponse, backupFilePath);
System.out.printf("Certificate's Backup Byte array's length %s %n", certificateBackupResponse.length);
});
Thread.sleep(7000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
Thread.sleep(30000);
certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath());
certificateAsyncClient.restoreCertificate(backupFromFile)
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n",
certificateResponse.name(), certificateResponse.keyId()));
Thread.sleep(15000);
} | class BackupAndRestoreOperationsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously backup and restore certificates in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
* @throws IOException when writing backup to file is unsuccessful.
*/
private static void writeBackupToFile(byte[] bytes, String filePath) {
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
OutputStream os = new FileOutputStream(file);
os.write(bytes);
System.out.println("Successfully wrote backup to file.");
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | class BackupAndRestoreOperationsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously backup and restore certificates in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
* @throws IOException when writing backup to file is unsuccessful.
*/
private static void writeBackupToFile(byte[] bytes, String filePath) {
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
OutputStream os = new FileOutputStream(file);
os.write(bytes);
System.out.println("Successfully wrote backup to file.");
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
Change this to `println` | public void purgeDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.doOnSuccess(response -> System.out.printf("Successfully Purged certificate \n"));
} | .doOnSuccess(response -> System.out.printf("Successfully Purged certificate \n")); | public void purgeDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.doOnSuccess(response -> System.out.println("Successfully Purged certificate"));
} | class CertificateAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RetryPolicy()).build();
CertificateAsyncClient keyClient = new CertificateClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async CertificateAsyncClient
* @return sync CertificateAsyncClient
*/
private CertificateAsyncClient getCertificateAsyncClient() {
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertiificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policy ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policy.issuerName(), policy.subjectName()));
certificateAsyncClient.getCertificatePolicyWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policyResponse ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policyResponse.getValue().issuerName(), policyResponse.getValue().subjectName()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
String certificateVersion = "6A385B124DEF4096AF1361A85B16C204";
certificateAsyncClient.getCertificateWithResponse("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s \n",
certificateWithVersion.getValue().name(), certificateWithVersion.getValue().secretId()));
certificateAsyncClient.getCertificate("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s \n",
certificateWithVersion.name(), certificateWithVersion.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
certificateAsyncClient.createCertificate("certificateName", certPolicy)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.createCertificateIssuer("issuerName", "providerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Issuer issuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuer(issuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.name(), issuerResponse.provider());
});
Issuer newIssuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuerWithResponse(newIssuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.name(), issuerResponse.provider());
}));
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuerWithResponse(issuerBase.getValue())
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
}));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s \n",
certificateResponse.enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuer(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s \n",
issuerResponse.enabled().toString()));
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuerWithResponse(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s \n",
issuerResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for
* {@link CertificateAsyncClient
*/
public void updateCertificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicy("certificateName", certificatePolicy)
.subscribe(updatedPolicy ->
System.out.printf("Certificate policy's updated transparency status %s \n",
updatedPolicy.certificateTransparency().toString()));
});
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicyWithResponse("certificateName",
certificatePolicy)
.subscribe(updatedPolicyResponse ->
System.out.printf("Certificate policy's updated transparency status %s \n",
updatedPolicyResponse.getValue().certificateTransparency().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificateWithResponse(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s \n",
certificateResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s \n", deletedIssuerResponse.getValue().name()));
certificateAsyncClient.deleteCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s \n", deletedIssuerResponse.name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getDeletedCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.getDeletedCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void purgeDeletedCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void recoverDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.recoverDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s \n", recoveredSecretResponse.name()));
certificateAsyncClient.recoverDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s \n", recoveredSecretResponse.getValue().name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void backupCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.backupCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s \n", certificateBackupResponse.length));
certificateAsyncClient.backupCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s \n",
certificateBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void restoreCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
byte[] certificateBackupByteArray = {};
certificateAsyncClient.restoreCertificate(certificateBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s \n",
certificateResponse.name(), certificateResponse.keyId()));
byte[] certificateBackup = {};
certificateAsyncClient.restoreCertificate(certificateBackup)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s \n",
certificateResponse.name(), certificateResponse.keyId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateIssuersCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateIssuers()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> System.out.printf("Received issuer with name %s and provider %s",
issuerResponse.name(), issuerResponse.provider())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listDeletedCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listDeletedCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedCertificateResponse.recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateVersionsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateVersions("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void contactsOperationsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
Contact oontactToAdd = new Contact("user", "useremail@exmaple.com");
certificateAsyncClient.setCertificateContacts(Arrays.asList(oontactToAdd)).subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Deleted Contact name %s and email %s", contact.name(), contact.emailAddress())
);
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* {@link CertificateAsyncClient
*/
public void certificateOperationCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.cancelCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Certificate operation status %s",
certificateOperation.status()));
certificateAsyncClient.cancelCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Certificate operation status %s",
certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Deleted Certificate operation's last"
+ " status %s", certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Deleted Certificate operation last status %s",
certificateOperation.status()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void getPendingCertificateSigningRequestCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getPendingCertificateSigningRequest("certificateName")
.subscribe(signingRequest -> System.out.printf("Received Signing request blob of length %s",
signingRequest.length));
certificateAsyncClient.getPendingCertificateSigningRequestWithResponse("certificateName")
.subscribe(signingRequestResponse -> System.out.printf("Received Signing request blob of length %s",
signingRequestResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void mergeCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
List<byte[]> x509Certs = new ArrayList<>();
certificateAsyncClient.mergeCertificate("certificateName", x509Certs)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509Certificates = new ArrayList<>();
certificateAsyncClient.mergeCertificateWithResponse("certificateName", x509Certificates)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
List<byte[]> x509CertificatesToMerge = new ArrayList<>();
MergeCertificateOptions config = new MergeCertificateOptions("certificateName", x509CertificatesToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificate(config)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509CertsToMerge = new ArrayList<>();
MergeCertificateOptions mergeConfig = new MergeCertificateOptions("certificateName", x509CertsToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificateWithResponse(mergeConfig)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
}
} | class CertificateAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RetryPolicy()).build();
CertificateAsyncClient keyClient = new CertificateClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async CertificateAsyncClient
* @return sync CertificateAsyncClient
*/
private CertificateAsyncClient getCertificateAsyncClient() {
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertiificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policy ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policy.issuerName(), policy.subjectName()));
certificateAsyncClient.getCertificatePolicyWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policyResponse ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policyResponse.getValue().issuerName(), policyResponse.getValue().subjectName()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
String certificateVersion = "6A385B124DEF4096AF1361A85B16C204";
certificateAsyncClient.getCertificateWithResponse("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s %n",
certificateWithVersion.getValue().name(), certificateWithVersion.getValue().secretId()));
certificateAsyncClient.getCertificate("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s %n",
certificateWithVersion.name(), certificateWithVersion.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
certificateAsyncClient.createCertificate("certificateName", certPolicy)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.createCertificateIssuer("issuerName", "providerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Issuer issuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuer(issuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.name(), issuerResponse.provider());
});
Issuer newIssuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuerWithResponse(newIssuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.name(), issuerResponse.provider());
}));
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuerWithResponse(issuerBase.getValue())
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
}));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s %n",
certificateResponse.enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuer(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s %n",
issuerResponse.enabled().toString()));
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuerWithResponse(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s %n",
issuerResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for
* {@link CertificateAsyncClient
*/
public void updateCertificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicy("certificateName", certificatePolicy)
.subscribe(updatedPolicy ->
System.out.printf("Certificate policy's updated transparency status %s %n",
updatedPolicy.certificateTransparency().toString()));
});
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicyWithResponse("certificateName",
certificatePolicy)
.subscribe(updatedPolicyResponse ->
System.out.printf("Certificate policy's updated transparency status %s %n",
updatedPolicyResponse.getValue().certificateTransparency().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificateWithResponse(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s %n",
certificateResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().name()));
certificateAsyncClient.deleteCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getDeletedCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.getDeletedCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void purgeDeletedCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void recoverDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.recoverDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s %n", recoveredSecretResponse.name()));
certificateAsyncClient.recoverDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s %n", recoveredSecretResponse.getValue().name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void backupCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.backupCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s %n", certificateBackupResponse.length));
certificateAsyncClient.backupCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s %n",
certificateBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void restoreCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
byte[] certificateBackupByteArray = {};
certificateAsyncClient.restoreCertificate(certificateBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n",
certificateResponse.name(), certificateResponse.keyId()));
byte[] certificateBackup = {};
certificateAsyncClient.restoreCertificate(certificateBackup)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n",
certificateResponse.name(), certificateResponse.keyId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateIssuersCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateIssuers()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> System.out.printf("Received issuer with name %s and provider %s",
issuerResponse.name(), issuerResponse.provider())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listDeletedCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listDeletedCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedCertificateResponse.recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateVersionsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateVersions("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void contactsOperationsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
Contact oontactToAdd = new Contact("user", "useremail@exmaple.com");
certificateAsyncClient.setCertificateContacts(Arrays.asList(oontactToAdd)).subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Deleted Contact name %s and email %s", contact.name(), contact.emailAddress())
);
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* {@link CertificateAsyncClient
*/
public void certificateOperationCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.cancelCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Certificate operation status %s",
certificateOperation.status()));
certificateAsyncClient.cancelCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Certificate operation status %s",
certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Deleted Certificate operation's last"
+ " status %s", certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Deleted Certificate operation last status %s",
certificateOperation.status()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void getPendingCertificateSigningRequestCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getPendingCertificateSigningRequest("certificateName")
.subscribe(signingRequest -> System.out.printf("Received Signing request blob of length %s",
signingRequest.length));
certificateAsyncClient.getPendingCertificateSigningRequestWithResponse("certificateName")
.subscribe(signingRequestResponse -> System.out.printf("Received Signing request blob of length %s",
signingRequestResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void mergeCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
List<byte[]> x509Certs = new ArrayList<>();
certificateAsyncClient.mergeCertificate("certificateName", x509Certs)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509Certificates = new ArrayList<>();
certificateAsyncClient.mergeCertificateWithResponse("certificateName", x509Certificates)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
List<byte[]> x509CertificatesToMerge = new ArrayList<>();
MergeCertificateOptions config = new MergeCertificateOptions("certificateName", x509CertificatesToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificate(config)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509CertsToMerge = new ArrayList<>();
MergeCertificateOptions mergeConfig = new MergeCertificateOptions("certificateName", x509CertsToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificateWithResponse(mergeConfig)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
}
} |
`%n` | public static void main(String[] args) throws InterruptedException {
CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12")
.subjectAlternativeNames(SubjectAlternativeNames.fromEmails(Arrays.asList("wow@gmail.com")))
.keyOptions(new EcKeyOptions()
.reuseKey(true)
.curve(KeyCurveName.P_256));
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s \n",
certificateResponse.enabled().toString()));
});
Thread.sleep(3000);
certificateAsyncClient.createCertificateIssuer("myIssuer", "Test")
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Thread.sleep(2000);
certificateAsyncClient.getCertificateIssuer("myIssuer")
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
Thread.sleep(2000);
certificateAsyncClient.createCertificate("myCertificate", new CertificatePolicy("myIssuer", "CN=IssuerSignedJavaPkcs12"), tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.getCertificateWithPolicy("myCertificate")
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
Thread.sleep(2000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificate("myCertificate")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateIssuerWithResponse("myIssuer")
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s \n", deletedIssuerResponse.getValue().name()));
Thread.sleep(50000);
certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
certificateAsyncClient.purgeDeletedCertificateWithResponse("myCertificate")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(4000);
} | System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws InterruptedException {
CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12")
.subjectAlternativeNames(SubjectAlternativeNames.fromEmails(Arrays.asList("wow@gmail.com")))
.keyOptions(new EcKeyOptions()
.reuseKey(true)
.curve(KeyCurveName.P_256));
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s %n",
certificateResponse.enabled().toString()));
});
Thread.sleep(3000);
certificateAsyncClient.createCertificateIssuer("myIssuer", "Test")
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Thread.sleep(2000);
certificateAsyncClient.getCertificateIssuer("myIssuer")
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
Thread.sleep(2000);
certificateAsyncClient.createCertificate("myCertificate", new CertificatePolicy("myIssuer", "CN=IssuerSignedJavaPkcs12"), tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.getCertificateWithPolicy("myCertificate")
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
Thread.sleep(2000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificate("myCertificate")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateIssuerWithResponse("myIssuer")
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().name()));
Thread.sleep(50000);
certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
certificateAsyncClient.purgeDeletedCertificateWithResponse("myCertificate")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(4000);
} | class HelloWorldAsync {
/**
* Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} | class HelloWorldAsync {
/**
* Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} |
`%n` | public static void main(String[] args) throws InterruptedException {
CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12")
.subjectAlternativeNames(SubjectAlternativeNames.fromEmails(Arrays.asList("wow@gmail.com")))
.keyOptions(new EcKeyOptions()
.reuseKey(true)
.curve(KeyCurveName.P_256));
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s \n",
certificateResponse.enabled().toString()));
});
Thread.sleep(3000);
certificateAsyncClient.createCertificateIssuer("myIssuer", "Test")
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Thread.sleep(2000);
certificateAsyncClient.getCertificateIssuer("myIssuer")
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
Thread.sleep(2000);
certificateAsyncClient.createCertificate("myCertificate", new CertificatePolicy("myIssuer", "CN=IssuerSignedJavaPkcs12"), tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.getCertificateWithPolicy("myCertificate")
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
Thread.sleep(2000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificate("myCertificate")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateIssuerWithResponse("myIssuer")
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s \n", deletedIssuerResponse.getValue().name()));
Thread.sleep(50000);
certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
certificateAsyncClient.purgeDeletedCertificateWithResponse("myCertificate")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(4000);
} | System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws InterruptedException {
CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12")
.subjectAlternativeNames(SubjectAlternativeNames.fromEmails(Arrays.asList("wow@gmail.com")))
.keyOptions(new EcKeyOptions()
.reuseKey(true)
.curve(KeyCurveName.P_256));
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s %n",
certificateResponse.enabled().toString()));
});
Thread.sleep(3000);
certificateAsyncClient.createCertificateIssuer("myIssuer", "Test")
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Thread.sleep(2000);
certificateAsyncClient.getCertificateIssuer("myIssuer")
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
Thread.sleep(2000);
certificateAsyncClient.createCertificate("myCertificate", new CertificatePolicy("myIssuer", "CN=IssuerSignedJavaPkcs12"), tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.getCertificateWithPolicy("myCertificate")
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
Thread.sleep(2000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificate("myCertificate")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateIssuerWithResponse("myIssuer")
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().name()));
Thread.sleep(50000);
certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
certificateAsyncClient.purgeDeletedCertificateWithResponse("myCertificate")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(4000);
} | class HelloWorldAsync {
/**
* Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} | class HelloWorldAsync {
/**
* Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} |
`%n` | public static void main(String[] args) throws InterruptedException {
CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12")
.subjectAlternativeNames(SubjectAlternativeNames.fromEmails(Arrays.asList("wow@gmail.com")))
.keyOptions(new EcKeyOptions()
.reuseKey(true)
.curve(KeyCurveName.P_256));
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
Thread.sleep(30000);
certificateAsyncClient.recoverDeletedCertificate("certificateName")
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s \n", recoveredSecretResponse.name()));
Thread.sleep(10000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
Thread.sleep(30000);
certificateAsyncClient.listDeletedCertificates()
.subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedCertificateResponse.recoveryId()));
Thread.sleep(15000);
certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws InterruptedException {
CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12")
.subjectAlternativeNames(SubjectAlternativeNames.fromEmails(Arrays.asList("wow@gmail.com")))
.keyOptions(new EcKeyOptions()
.reuseKey(true)
.curve(KeyCurveName.P_256));
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
Thread.sleep(22000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
Thread.sleep(30000);
certificateAsyncClient.recoverDeletedCertificate("certificateName")
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s %n", recoveredSecretResponse.name()));
Thread.sleep(10000);
certificateAsyncClient.deleteCertificate("certificateName")
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
Thread.sleep(30000);
certificateAsyncClient.listDeletedCertificates()
.subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedCertificateResponse.recoveryId()));
Thread.sleep(15000);
certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName")
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | class ManagingDeletedCertificatesAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted certificates in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} | class ManagingDeletedCertificatesAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted certificates in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} |
`%n` | public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1))
.setKeySize(2048))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s \n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
String backupFilePath = "YOUR_BACKUP_FILE_PATH";
keyAsyncClient.backupKey("CloudRsaKey").subscribe(backupResponse -> {
byte[] backupBytes = backupResponse;
writeBackupToFile(backupBytes, backupFilePath);
});
Thread.sleep(7000);
keyAsyncClient.deleteKey("CloudRsaKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath());
keyAsyncClient.restoreKey(backupFromFile).subscribe(keyResponse ->
System.out.printf("Restored Key with name %s \n", keyResponse.name()));
Thread.sleep(15000);
} | System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1))
.setKeySize(2048))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s %n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
String backupFilePath = "YOUR_BACKUP_FILE_PATH";
keyAsyncClient.backupKey("CloudRsaKey").subscribe(backupResponse -> {
byte[] backupBytes = backupResponse;
writeBackupToFile(backupBytes, backupFilePath);
});
Thread.sleep(7000);
keyAsyncClient.deleteKey("CloudRsaKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s %n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath());
keyAsyncClient.restoreKey(backupFromFile).subscribe(keyResponse ->
System.out.printf("Restored Key with name %s %n", keyResponse.name()));
Thread.sleep(15000);
} | class BackupAndRestoreOperationsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously backup and restore keys in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
* @throws IOException when writing backup to file is unsuccessful.
*/
private static void writeBackupToFile(byte[] bytes, String filePath) {
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
OutputStream os = new FileOutputStream(file);
os.write(bytes);
System.out.println("Successfully wrote backup to file.");
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | class BackupAndRestoreOperationsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously backup and restore keys in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
* @throws IOException when writing backup to file is unsuccessful.
*/
private static void writeBackupToFile(byte[] bytes, String filePath) {
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
OutputStream os = new FileOutputStream(file);
os.write(bytes);
System.out.println("Successfully wrote backup to file.");
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
Don't need `\n` | public void purgeDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKey("deletedKeyName")
.subscribe(purgeResponse ->
System.out.println("Successfully Purged deleted Key \n"));
} | System.out.println("Successfully Purged deleted Key \n")); | public void purgeDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKey("deletedKeyName")
.subscribe(purgeResponse ->
System.out.println("Successfully Purged deleted Key"));
} | class KeyAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithHttpClient() {
RecordedData networkData = new RecordedData();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClient() {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKey() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.createKey("keyName", KeyType.EC)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKey(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKey(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKey(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKeyWithResponses() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKeyWithResponse(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKeyWithResponse(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKeyWithResponse(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKeyWithResponse("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n",
keyResponse.getValue().name(), keyResponse.getValue().id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKeyWithResponse(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKey("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.getKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKey(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s \n", keyResponse.name(), keyResponse.id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.getValue().notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.getValue().notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void purgeDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %n \n", purgeResponse.getStatusCode()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.getValue().name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKey("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s \n", keyBackupResponse.length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s \n", keyBackupResponse.getValue().length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKey(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKeyWithResponse(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse -> System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listDeletedKeysSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listDeletedKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKey -> System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId()));
}
/**
* Generates code sample for using {@link KeyAsyncClient
*/
public void listKeyVersions() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeyVersions("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse ->
System.out.printf("Received key's version with name %s, type %s and version %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty(), keyResponse.version())));
}
/**
* Implementation not provided for this method
* @return {@code null}
*/
private TokenCredential getKeyVaultCredential() {
return null;
}
} | class KeyAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithHttpClient() {
RecordedData networkData = new RecordedData();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClient() {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKey() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.createKey("keyName", KeyType.EC)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKey(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKey(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKey(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKeyWithResponses() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKeyWithResponse(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKeyWithResponse(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKeyWithResponse(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKeyWithResponse("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n",
keyResponse.getValue().name(), keyResponse.getValue().id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKeyWithResponse(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKey("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.getKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKey(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s %n", keyResponse.name(), keyResponse.id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.getValue().notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.getValue().notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void purgeDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s %n", recoveredKeyResponse.getValue().name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKey("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s %n", recoveredKeyResponse.name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s %n", keyBackupResponse.length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s %n", keyBackupResponse.getValue().length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKey(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKeyWithResponse(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse -> System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listDeletedKeysSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listDeletedKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKey -> System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId()));
}
/**
* Generates code sample for using {@link KeyAsyncClient
*/
public void listKeyVersions() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeyVersions("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse ->
System.out.printf("Received key's version with name %s, type %s and version %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty(), keyResponse.version())));
}
/**
* Implementation not provided for this method
* @return {@code null}
*/
private TokenCredential getKeyVaultCredential() {
return null;
}
} |
`%n` | public static void main(String[] args) throws InterruptedException {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
Response<Key> createKeyResponse = keyAsyncClient.createRsaKeyWithResponse(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1))
.setKeySize(2048)).block();
System.out.printf("Create Key operation succeeded with status code %s \n", createKeyResponse.getStatusCode());
System.out.printf("Key is created with name %s and type %s \n", createKeyResponse.getValue().name(), createKeyResponse.getValue().getKeyMaterial().getKty());
Thread.sleep(2000);
keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse ->
System.out.printf("Key returned with name %s and type %s \n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse -> {
Key key = keyResponse;
key.setExpires(key.expires().plusYears(1));
keyAsyncClient.updateKey(key).subscribe(updatedKeyResponse ->
System.out.printf("Key's updated expiry time %s \n", updatedKeyResponse.expires().toString()));
});
Thread.sleep(2000);
keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1))
.setKeySize(4096))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s \n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.deleteKey("CloudRsaKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse ->
System.out.printf("Cloud Rsa key purge status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | System.out.printf("Cloud Rsa key purge status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws InterruptedException {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
Response<Key> createKeyResponse = keyAsyncClient.createRsaKeyWithResponse(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1))
.setKeySize(2048)).block();
System.out.printf("Create Key operation succeeded with status code %s \n", createKeyResponse.getStatusCode());
System.out.printf("Key is created with name %s and type %s \n", createKeyResponse.getValue().name(), createKeyResponse.getValue().getKeyMaterial().getKty());
Thread.sleep(2000);
keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse ->
System.out.printf("Key returned with name %s and type %s \n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse -> {
Key key = keyResponse;
key.setExpires(key.expires().plusYears(1));
keyAsyncClient.updateKey(key).subscribe(updatedKeyResponse ->
System.out.printf("Key's updated expiry time %s \n", updatedKeyResponse.expires().toString()));
});
Thread.sleep(2000);
keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1))
.setKeySize(4096))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s \n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.deleteKey("CloudRsaKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse ->
System.out.printf("Cloud Rsa key purge status response %n \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | class HelloWorldAsync {
/**
* Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} | class HelloWorldAsync {
/**
* Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} |
`%d%n`, remove the copy and paste error. | public void purgeDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %rsaPrivateExponent \n", purgeResponse.getStatusCode()));
} | System.out.printf("Purge Status response %rsaPrivateExponent \n", purgeResponse.getStatusCode())); | public void purgeDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
} | class KeyAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithHttpClient() {
RecordedData networkData = new RecordedData();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClient() {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKey() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.createKey("keyName", KeyType.EC)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKey(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKey(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKey(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKeyWithResponses() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKeyWithResponse(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKeyWithResponse(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKeyWithResponse(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKeyWithResponse("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n",
keyResponse.getValue().name(), keyResponse.getValue().id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKeyWithResponse(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKey("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.getKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKey(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s \n", keyResponse.name(), keyResponse.id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.getValue().notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.getValue().notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void purgeDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKey("deletedKeyName")
.subscribe(purgeResponse ->
System.out.printf("Successfully Purged deleted Key\n"));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.getValue().name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKey("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s \n", keyBackupResponse.length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s \n", keyBackupResponse.getValue().length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKey(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKeyWithResponse(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse -> System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listDeletedKeysSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listDeletedKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKey -> System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId()));
}
/**
* Generates code sample for using {@link KeyAsyncClient
*/
public void listKeyVersions() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeyVersions("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse ->
System.out.printf("Received key's version with name %s, type %s and version %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty(), keyResponse.version())));
}
/**
* Implementation not provided for this method
* @return {@code null}
*/
private TokenCredential getKeyVaultCredential() {
return null;
}
} | class KeyAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithHttpClient() {
RecordedData networkData = new RecordedData();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClient() {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKey() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.createKey("keyName", KeyType.EC)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKey(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKey(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKey(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKeyWithResponses() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKeyWithResponse(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKeyWithResponse(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKeyWithResponse(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKeyWithResponse("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n",
keyResponse.getValue().name(), keyResponse.getValue().id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKeyWithResponse(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKey("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.getKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKey(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s %n", keyResponse.name(), keyResponse.id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.getValue().notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.getValue().notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void purgeDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKey("deletedKeyName")
.subscribe(purgeResponse ->
System.out.println("Successfully Purged deleted Key"));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s %n", recoveredKeyResponse.getValue().name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKey("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s %n", recoveredKeyResponse.name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s %n", keyBackupResponse.length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s %n", keyBackupResponse.getValue().length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKey(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKeyWithResponse(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse -> System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listDeletedKeysSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listDeletedKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKey -> System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId()));
}
/**
* Generates code sample for using {@link KeyAsyncClient
*/
public void listKeyVersions() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeyVersions("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse ->
System.out.printf("Received key's version with name %s, type %s and version %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty(), keyResponse.version())));
}
/**
* Implementation not provided for this method
* @return {@code null}
*/
private TokenCredential getKeyVaultCredential() {
return null;
}
} |
`println` | public void purgeDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKey("deletedKeyName")
.subscribe(purgeResponse ->
System.out.printf("Successfully Purged deleted Key\n"));
} | System.out.printf("Successfully Purged deleted Key\n")); | public void purgeDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKey("deletedKeyName")
.subscribe(purgeResponse ->
System.out.println("Successfully Purged deleted Key"));
} | class KeyAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithHttpClient() {
RecordedData networkData = new RecordedData();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClient() {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKey() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.createKey("keyName", KeyType.EC)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKey(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKey(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKey(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKeyWithResponses() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKeyWithResponse(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKeyWithResponse(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKeyWithResponse(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKeyWithResponse("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n",
keyResponse.getValue().name(), keyResponse.getValue().id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKeyWithResponse(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKey("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.getKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKey(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s \n", keyResponse.name(), keyResponse.id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.getValue().notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.getValue().notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s \n",
updatedKeyResponse.notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void purgeDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %rsaPrivateExponent \n", purgeResponse.getStatusCode()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.getValue().name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKey("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s \n", keyBackupResponse.length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s \n", keyBackupResponse.getValue().length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKey(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s \n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKeyWithResponse(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s \n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse -> System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listDeletedKeysSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listDeletedKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKey -> System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId()));
}
/**
* Generates code sample for using {@link KeyAsyncClient
*/
public void listKeyVersions() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeyVersions("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse ->
System.out.printf("Received key's version with name %s, type %s and version %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty(), keyResponse.version())));
}
/**
* Implementation not provided for this method
* @return {@code null}
*/
private TokenCredential getKeyVaultCredential() {
return null;
}
} | class KeyAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithHttpClient() {
RecordedData networkData = new RecordedData();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClient() {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates code sample for creating a {@link KeyAsyncClient}
* @return An instance of {@link KeyAsyncClient}
*/
public KeyAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return keyAsyncClient;
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKey() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.createKey("keyName", KeyType.EC)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKey(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKey(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKey(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", keyResponse.getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void createKeyWithResponses() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createKeyWithResponse(keyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createRsaKeyWithResponse(rsaKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
keyAsyncClient.createEcKeyWithResponse(ecKeyCreateOptions)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKeyWithResponse("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n",
keyResponse.getValue().name(), keyResponse.getValue().id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKeyWithResponse(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
keyAsyncClient.getKey("keyName", keyVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.getKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
keyAsyncClient.listKeys().subscribe(keyBase ->
keyAsyncClient.getKey(keyBase)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Key with name %s and value %s %n", keyResponse.name(), keyResponse.id())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.getValue().notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKeyWithResponse(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.getValue().notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void updateKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse, KeyOperation.ENCRYPT, KeyOperation.DECRYPT)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.notBefore().toString()));
});
keyAsyncClient.getKey("keyName")
.subscribe(keyResponse -> {
keyResponse.setNotBefore(OffsetDateTime.now().plusDays(50));
keyAsyncClient.updateKey(keyResponse)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(updatedKeyResponse ->
System.out.printf("Key's updated not before time %s %n",
updatedKeyResponse.notBefore().toString()));
});
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void deleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.deleteKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void getDeleteKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.getDeletedKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s", deletedKeyResponse.getValue().getRecoveryId()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void purgeDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKeyWithResponse("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s %n", recoveredKeyResponse.getValue().name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void recoverDeletedKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.recoverDeletedKey("deletedKeyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s %n", recoveredKeyResponse.name()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKey("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s %n", keyBackupResponse.length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void backupKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.backupKeyWithResponse("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBackupResponse ->
System.out.printf("Key's Backup Byte array's length %s %n", keyBackupResponse.getValue().length));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKey(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s %n", keyResponse.name(), keyResponse.id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void restoreKeyWithResponseSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
byte[] keyBackupByteArray = {};
keyAsyncClient.restoreKeyWithResponse(keyBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyResponse ->
System.out.printf("Restored Key with name %s and id %s %n", keyResponse.getValue().name(),
keyResponse.getValue().id()));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listKeySnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse -> System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty())));
}
/**
* Generates a code sample for using {@link KeyAsyncClient
*/
public void listDeletedKeysSnippets() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listDeletedKeys()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedKey -> System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId()));
}
/**
* Generates code sample for using {@link KeyAsyncClient
*/
public void listKeyVersions() {
KeyAsyncClient keyAsyncClient = createAsyncClient();
keyAsyncClient.listKeyVersions("keyName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(keyBase -> keyAsyncClient.getKey(keyBase)
.subscribe(keyResponse ->
System.out.printf("Received key's version with name %s, type %s and version %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty(), keyResponse.version())));
}
/**
* Implementation not provided for this method
* @return {@code null}
*/
private TokenCredential getKeyVaultCredential() {
return null;
}
} |
Mind fixing the copy and paste error, `%d%n` | public void purgeDeletedKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
Response<Void> purgedResponse = keyClient.purgeDeletedKeyWithResponse("deletedKeyName", new Context(key2, value2));
System.out.printf("Purge Status Code: %rsaPrivateExponent", purgedResponse.getStatusCode());
} | System.out.printf("Purge Status Code: %rsaPrivateExponent", purgedResponse.getStatusCode()); | public void purgeDeletedKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
Response<Void> purgedResponse = keyClient.purgeDeletedKeyWithResponse("deletedKeyName", new Context(key2, value2));
System.out.printf("Purge Status Code: %d %n", purgedResponse.getStatusCode());
} | class KeyClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyClient}
* @return An instance of {@link KeyClient}
*/
public KeyClient createClient() {
KeyClient keyClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
return keyClient;
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void createKey() {
KeyClient keyClient = createClient();
Key key = keyClient.createKey("keyName", KeyType.EC);
System.out.printf("Key is created with name %s and id %s %n", key.name(), key.id());
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key optionsKey = keyClient.createKey(keyCreateOptions);
System.out.printf("Key is created with name %s and id %s \n", optionsKey.name(), optionsKey.id());
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key rsaKey = keyClient.createRsaKey(rsaKeyCreateOptions);
System.out.printf("Key is created with name %s and id %s \n", rsaKey.name(), rsaKey.id());
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key ecKey = keyClient.createEcKey(ecKeyCreateOptions);
System.out.printf("Key is created with name %s and id %s \n", ecKey.name(), ecKey.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void deleteKeySnippets() {
KeyClient keyClient = createClient();
Key key = keyClient.getKey("keyName");
DeletedKey deletedKey = keyClient.deleteKey("keyName");
System.out.printf("Deleted Key's Recovery Id %s", deletedKey.getRecoveryId());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void getDeletedKeySnippets() {
KeyClient keyClient = createClient();
DeletedKey deletedKey = keyClient.getDeletedKey("keyName");
System.out.printf("Deleted Key's Recovery Id %s", deletedKey.getRecoveryId());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void createKeyWithResponses() {
KeyClient keyClient = createClient();
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key optionsKey = keyClient.createKeyWithResponse(keyCreateOptions, new Context(key1, value1)).getValue();
System.out.printf("Key is created with name %s and id %s \n", optionsKey.name(), optionsKey.id());
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key rsaKey = keyClient.createRsaKeyWithResponse(rsaKeyCreateOptions, new Context(key1, value1)).getValue();
System.out.printf("Key is created with name %s and id %s \n", rsaKey.name(), rsaKey.id());
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key ecKey = keyClient.createEcKeyWithResponse(ecKeyCreateOptions, new Context(key1, value1)).getValue();
System.out.printf("Key is created with name %s and id %s \n", ecKey.name(), ecKey.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void getKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
Key keyWithVersion = keyClient.getKeyWithResponse("keyName", keyVersion,
new Context(key1, value1)).getValue();
System.out.printf("Key is returned with name %s and id %s \n", keyWithVersion.name(), keyWithVersion.id());
for (KeyBase key : keyClient.listKeys()) {
Key keyResponse = keyClient.getKeyWithResponse(key, new Context(key1, value1)).getValue();
System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty());
}
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void getKeySnippets() {
KeyClient keyClient = createClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
Key keyWithVersion = keyClient.getKey("keyName", keyVersion);
System.out.printf("Key is returned with name %s and id %s \n", keyWithVersion.name(), keyWithVersion.id());
Key keyWithVersionValue = keyClient.getKey("keyName");
System.out.printf("Key is returned with name %s and id %s \n", keyWithVersionValue.name(), keyWithVersionValue.id());
for (KeyBase key : keyClient.listKeys()) {
Key keyResponse = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty());
}
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void updateKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
Key key = keyClient.getKey("keyName");
key.setExpires(OffsetDateTime.now().plusDays(60));
KeyBase updatedKeyBase = keyClient.updateKeyWithResponse(key,
new Context(key1, value1), KeyOperation.ENCRYPT, KeyOperation.DECRYPT).getValue();
Key updatedKey = keyClient.getKey(updatedKeyBase.name());
System.out.printf("Key is updated with name %s and id %s \n", updatedKey.name(), updatedKey.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void updateKeySnippets() {
KeyClient keyClient = createClient();
Key key = keyClient.getKey("keyName");
key.setExpires(OffsetDateTime.now().plusDays(60));
KeyBase updatedKeyBase = keyClient.updateKey(key, KeyOperation.ENCRYPT, KeyOperation.DECRYPT);
Key updatedKey = keyClient.getKey(updatedKeyBase.name());
System.out.printf("Key is updated with name %s and id %s \n", updatedKey.name(), updatedKey.id());
Key updateKey = keyClient.getKey("keyName");
key.setExpires(OffsetDateTime.now().plusDays(60));
KeyBase updatedKeyBaseValue = keyClient.updateKey(updateKey);
Key updatedKeyValue = keyClient.getKey(updatedKeyBaseValue.name());
System.out.printf("Key is updated with name %s and id %s \n", updatedKeyValue.name(), updatedKeyValue.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void deleteKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
Key key = keyClient.getKey("keyName");
DeletedKey deletedKey = keyClient.deleteKeyWithResponse("keyName", new Context(key1, value1)).getValue();
System.out.printf("Deleted Key's Recovery Id %s", deletedKey.getRecoveryId());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void getDeleteKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
DeletedKey deletedKey = keyClient.getDeletedKeyWithResponse("keyName", new Context(key1, value1)).getValue();
System.out.printf("Deleted Key with recovery Id %s \n", deletedKey.getRecoveryId());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void purgeDeletedKeySnippets() {
KeyClient keyClient = createClient();
keyClient.purgeDeletedKey("deletedKeyName");
}
/**
* Generates a code sample for using {@link KeyClient
*/
/**
* Generates a code sample for using {@link KeyClient
*/
public void recoverDeletedKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
Key recoveredKey = keyClient.recoverDeletedKeyWithResponse("deletedKeyName",
new Context(key2, value2)).getValue();
System.out.printf("Recovered key with name %s", recoveredKey.name());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void recoverDeletedKeySnippets() {
KeyClient keyClient = createClient();
Key recoveredKey = keyClient.recoverDeletedKey("deletedKeyName");
System.out.printf("Recovered key with name %s", recoveredKey.name());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void backupKeySnippets() {
KeyClient keyClient = createClient();
byte[] keyBackup = keyClient.backupKey("keyName");
System.out.printf("Key's Backup Byte array's length %s", keyBackup.length);
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void backupKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
byte[] keyBackup = keyClient.backupKeyWithResponse("keyName", new Context(key2, value2)).getValue();
System.out.printf("Key's Backup Byte array's length %s", keyBackup.length);
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void restoreKeySnippets() {
KeyClient keyClient = createClient();
byte[] keyBackupByteArray = {};
Key keyResponse = keyClient.restoreKey(keyBackupByteArray);
System.out.printf("Restored Key with name %s and id %s \n", keyResponse.name(), keyResponse.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void restoreKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
byte[] keyBackupByteArray = {};
Response<Key> keyResponse = keyClient.restoreKeyWithResponse(keyBackupByteArray, new Context(key1, value1));
System.out.printf("Restored Key with name %s and id %s \n",
keyResponse.getValue().name(), keyResponse.getValue().id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty());
}
for (KeyBase key : keyClient.listKeys(new Context(key2, value2))) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty());
}
keyClient.listKeys().iterableByPage().forEach(resp -> {
System.out.printf("Got response headers . Url: %s, Status code: %d %n",
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(value -> {
Key keyWithMaterial = keyClient.getKey(value);
System.out.printf("Received key with name %s and type %s %n", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty());
});
});
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void listDeletedKeysSnippets() {
KeyClient keyClient = createClient();
for (DeletedKey deletedKey : keyClient.listDeletedKeys()) {
System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId());
}
for (DeletedKey deletedKey : keyClient.listDeletedKeys(new Context(key2, value2))) {
System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId());
}
keyClient.listDeletedKeys().iterableByPage().forEach(resp -> {
System.out.printf("Got response headers . Url: %s, Status code: %d %n",
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(value -> {
System.out.printf("Deleted key's recovery Id %s %n", value.getRecoveryId());
});
});
}
/**
* Generates code sample for using {@link KeyClient
*/
public void listKeyVersions() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeyVersions("keyName")) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty(), keyWithMaterial.version());
}
for (KeyBase key : keyClient.listKeyVersions("keyName", new Context(key2, value2))) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty(), keyWithMaterial.version());
}
keyClient.listKeyVersions("keyName").iterableByPage().forEach(resp -> {
System.out.printf("Got response headers . Url: %s, Status code: %d %n",
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(value -> {
System.out.printf("Key name: %s, Key version: %s %n", value.name(), value.version());
});
});
}
/**
* Implementation not provided for this method
* @return {@code null}
*/
private TokenCredential getKeyVaultCredential() {
return null;
}
} | class KeyClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyClient}
* @return An instance of {@link KeyClient}
*/
public KeyClient createClient() {
KeyClient keyClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
return keyClient;
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void createKey() {
KeyClient keyClient = createClient();
Key key = keyClient.createKey("keyName", KeyType.EC);
System.out.printf("Key is created with name %s and id %s %n", key.name(), key.id());
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key optionsKey = keyClient.createKey(keyCreateOptions);
System.out.printf("Key is created with name %s and id %s %n", optionsKey.name(), optionsKey.id());
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key rsaKey = keyClient.createRsaKey(rsaKeyCreateOptions);
System.out.printf("Key is created with name %s and id %s %n", rsaKey.name(), rsaKey.id());
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key ecKey = keyClient.createEcKey(ecKeyCreateOptions);
System.out.printf("Key is created with name %s and id %s %n", ecKey.name(), ecKey.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void deleteKeySnippets() {
KeyClient keyClient = createClient();
Key key = keyClient.getKey("keyName");
DeletedKey deletedKey = keyClient.deleteKey("keyName");
System.out.printf("Deleted Key's Recovery Id %s", deletedKey.getRecoveryId());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void getDeletedKeySnippets() {
KeyClient keyClient = createClient();
DeletedKey deletedKey = keyClient.getDeletedKey("keyName");
System.out.printf("Deleted Key's Recovery Id %s", deletedKey.getRecoveryId());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void createKeyWithResponses() {
KeyClient keyClient = createClient();
KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key optionsKey = keyClient.createKeyWithResponse(keyCreateOptions, new Context(key1, value1)).getValue();
System.out.printf("Key is created with name %s and id %s %n", optionsKey.name(), optionsKey.id());
RsaKeyCreateOptions rsaKeyCreateOptions = new RsaKeyCreateOptions("keyName")
.setKeySize(2048)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key rsaKey = keyClient.createRsaKeyWithResponse(rsaKeyCreateOptions, new Context(key1, value1)).getValue();
System.out.printf("Key is created with name %s and id %s %n", rsaKey.name(), rsaKey.id());
EcKeyCreateOptions ecKeyCreateOptions = new EcKeyCreateOptions("keyName")
.setCurve(KeyCurveName.P_384)
.setNotBefore(OffsetDateTime.now().plusDays(1))
.setExpires(OffsetDateTime.now().plusYears(1));
Key ecKey = keyClient.createEcKeyWithResponse(ecKeyCreateOptions, new Context(key1, value1)).getValue();
System.out.printf("Key is created with name %s and id %s %n", ecKey.name(), ecKey.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void getKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
Key keyWithVersion = keyClient.getKeyWithResponse("keyName", keyVersion,
new Context(key1, value1)).getValue();
System.out.printf("Key is returned with name %s and id %s %n", keyWithVersion.name(), keyWithVersion.id());
for (KeyBase key : keyClient.listKeys()) {
Key keyResponse = keyClient.getKeyWithResponse(key, new Context(key1, value1)).getValue();
System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty());
}
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void getKeySnippets() {
KeyClient keyClient = createClient();
String keyVersion = "6A385B124DEF4096AF1361A85B16C204";
Key keyWithVersion = keyClient.getKey("keyName", keyVersion);
System.out.printf("Key is returned with name %s and id %s %n", keyWithVersion.name(), keyWithVersion.id());
Key keyWithVersionValue = keyClient.getKey("keyName");
System.out.printf("Key is returned with name %s and id %s %n", keyWithVersionValue.name(), keyWithVersionValue.id());
for (KeyBase key : keyClient.listKeys()) {
Key keyResponse = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyResponse.name(),
keyResponse.getKeyMaterial().getKty());
}
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void updateKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
Key key = keyClient.getKey("keyName");
key.setExpires(OffsetDateTime.now().plusDays(60));
KeyBase updatedKeyBase = keyClient.updateKeyWithResponse(key,
new Context(key1, value1), KeyOperation.ENCRYPT, KeyOperation.DECRYPT).getValue();
Key updatedKey = keyClient.getKey(updatedKeyBase.name());
System.out.printf("Key is updated with name %s and id %s %n", updatedKey.name(), updatedKey.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void updateKeySnippets() {
KeyClient keyClient = createClient();
Key key = keyClient.getKey("keyName");
key.setExpires(OffsetDateTime.now().plusDays(60));
KeyBase updatedKeyBase = keyClient.updateKey(key, KeyOperation.ENCRYPT, KeyOperation.DECRYPT);
Key updatedKey = keyClient.getKey(updatedKeyBase.name());
System.out.printf("Key is updated with name %s and id %s %n", updatedKey.name(), updatedKey.id());
Key updateKey = keyClient.getKey("keyName");
key.setExpires(OffsetDateTime.now().plusDays(60));
KeyBase updatedKeyBaseValue = keyClient.updateKey(updateKey);
Key updatedKeyValue = keyClient.getKey(updatedKeyBaseValue.name());
System.out.printf("Key is updated with name %s and id %s %n", updatedKeyValue.name(), updatedKeyValue.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void deleteKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
Key key = keyClient.getKey("keyName");
DeletedKey deletedKey = keyClient.deleteKeyWithResponse("keyName", new Context(key1, value1)).getValue();
System.out.printf("Deleted Key's Recovery Id %s", deletedKey.getRecoveryId());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void getDeleteKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
DeletedKey deletedKey = keyClient.getDeletedKeyWithResponse("keyName", new Context(key1, value1)).getValue();
System.out.printf("Deleted Key with recovery Id %s %n", deletedKey.getRecoveryId());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void purgeDeletedKeySnippets() {
KeyClient keyClient = createClient();
keyClient.purgeDeletedKey("deletedKeyName");
}
/**
* Generates a code sample for using {@link KeyClient
*/
/**
* Generates a code sample for using {@link KeyClient
*/
public void recoverDeletedKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
Key recoveredKey = keyClient.recoverDeletedKeyWithResponse("deletedKeyName",
new Context(key2, value2)).getValue();
System.out.printf("Recovered key with name %s", recoveredKey.name());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void recoverDeletedKeySnippets() {
KeyClient keyClient = createClient();
Key recoveredKey = keyClient.recoverDeletedKey("deletedKeyName");
System.out.printf("Recovered key with name %s", recoveredKey.name());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void backupKeySnippets() {
KeyClient keyClient = createClient();
byte[] keyBackup = keyClient.backupKey("keyName");
System.out.printf("Key's Backup Byte array's length %s", keyBackup.length);
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void backupKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
byte[] keyBackup = keyClient.backupKeyWithResponse("keyName", new Context(key2, value2)).getValue();
System.out.printf("Key's Backup Byte array's length %s", keyBackup.length);
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void restoreKeySnippets() {
KeyClient keyClient = createClient();
byte[] keyBackupByteArray = {};
Key keyResponse = keyClient.restoreKey(keyBackupByteArray);
System.out.printf("Restored Key with name %s and id %s %n", keyResponse.name(), keyResponse.id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void restoreKeyWithResponseSnippets() {
KeyClient keyClient = createClient();
byte[] keyBackupByteArray = {};
Response<Key> keyResponse = keyClient.restoreKeyWithResponse(keyBackupByteArray, new Context(key1, value1));
System.out.printf("Restored Key with name %s and id %s %n",
keyResponse.getValue().name(), keyResponse.getValue().id());
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty());
}
for (KeyBase key : keyClient.listKeys(new Context(key2, value2))) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty());
}
keyClient.listKeys().iterableByPage().forEach(resp -> {
System.out.printf("Got response headers . Url: %s, Status code: %d %n",
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(value -> {
Key keyWithMaterial = keyClient.getKey(value);
System.out.printf("Received key with name %s and type %s %n", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty());
});
});
}
/**
* Generates a code sample for using {@link KeyClient
*/
public void listDeletedKeysSnippets() {
KeyClient keyClient = createClient();
for (DeletedKey deletedKey : keyClient.listDeletedKeys()) {
System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId());
}
for (DeletedKey deletedKey : keyClient.listDeletedKeys(new Context(key2, value2))) {
System.out.printf("Deleted key's recovery Id %s", deletedKey.getRecoveryId());
}
keyClient.listDeletedKeys().iterableByPage().forEach(resp -> {
System.out.printf("Got response headers . Url: %s, Status code: %d %n",
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(value -> {
System.out.printf("Deleted key's recovery Id %s %n", value.getRecoveryId());
});
});
}
/**
* Generates code sample for using {@link KeyClient
*/
public void listKeyVersions() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeyVersions("keyName")) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty(), keyWithMaterial.version());
}
for (KeyBase key : keyClient.listKeyVersions("keyName", new Context(key2, value2))) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(),
keyWithMaterial.getKeyMaterial().getKty(), keyWithMaterial.version());
}
keyClient.listKeyVersions("keyName").iterableByPage().forEach(resp -> {
System.out.printf("Got response headers . Url: %s, Status code: %d %n",
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(value -> {
System.out.printf("Key name: %s, Key version: %s %n", value.name(), value.version());
});
});
}
/**
* Implementation not provided for this method
* @return {@code null}
*/
private TokenCredential getKeyVaultCredential() {
return null;
}
} |
`%n` | public static void main(String[] args) throws InterruptedException {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
keyAsyncClient.createEcKey(new EcKeyCreateOptions("CloudEcKey")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s \n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s \n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.deleteKey("CloudEcKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.recoverDeletedKey("CloudEcKey").subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.name()));
Thread.sleep(10000);
keyAsyncClient.deleteKey("CloudEcKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.getRecoveryId()));
keyAsyncClient.deleteKey("CloudRsaKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.listDeletedKeys().subscribe(deletedKey ->
System.out.printf("Deleted key's recovery Id %s \n", deletedKey.getRecoveryId()));
Thread.sleep(15000);
keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse ->
System.out.printf("Storage account key purge status response %d \n", purgeResponse.getStatusCode()));
keyAsyncClient.purgeDeletedKeyWithResponse("CloudEcKey").subscribe(purgeResponse ->
System.out.printf("Bank account key purge status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | System.out.printf("Storage account key purge status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws InterruptedException {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
keyAsyncClient.createEcKey(new EcKeyCreateOptions("CloudEcKey")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s %n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s %n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.deleteKey("CloudEcKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s %n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.recoverDeletedKey("CloudEcKey").subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s %n", recoveredKeyResponse.name()));
Thread.sleep(10000);
keyAsyncClient.deleteKey("CloudEcKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s %n", deletedKeyResponse.getRecoveryId()));
keyAsyncClient.deleteKey("CloudRsaKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s %n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.listDeletedKeys().subscribe(deletedKey ->
System.out.printf("Deleted key's recovery Id %s %n", deletedKey.getRecoveryId()));
Thread.sleep(15000);
keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse ->
System.out.printf("Storage account key purge status response %d %n", purgeResponse.getStatusCode()));
keyAsyncClient.purgeDeletedKeyWithResponse("CloudEcKey").subscribe(purgeResponse ->
System.out.printf("Bank account key purge status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | class ManagingDeletedKeysAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted keys in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} | class ManagingDeletedKeysAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted keys in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} |
`%n` | public static void main(String[] args) throws InterruptedException {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
keyAsyncClient.createEcKey(new EcKeyCreateOptions("CloudEcKey")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s \n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s \n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.deleteKey("CloudEcKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.recoverDeletedKey("CloudEcKey").subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.name()));
Thread.sleep(10000);
keyAsyncClient.deleteKey("CloudEcKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.getRecoveryId()));
keyAsyncClient.deleteKey("CloudRsaKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.listDeletedKeys().subscribe(deletedKey ->
System.out.printf("Deleted key's recovery Id %s \n", deletedKey.getRecoveryId()));
Thread.sleep(15000);
keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse ->
System.out.printf("Storage account key purge status response %d \n", purgeResponse.getStatusCode()));
keyAsyncClient.purgeDeletedKeyWithResponse("CloudEcKey").subscribe(purgeResponse ->
System.out.printf("Bank account key purge status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | System.out.printf("Bank account key purge status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws InterruptedException {
KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
keyAsyncClient.createEcKey(new EcKeyCreateOptions("CloudEcKey")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s %n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(keyResponse ->
System.out.printf("Key is created with name %s and type %s %n", keyResponse.name(), keyResponse.getKeyMaterial().getKty()));
Thread.sleep(2000);
keyAsyncClient.deleteKey("CloudEcKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s %n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.recoverDeletedKey("CloudEcKey").subscribe(recoveredKeyResponse ->
System.out.printf("Recovered Key with name %s %n", recoveredKeyResponse.name()));
Thread.sleep(10000);
keyAsyncClient.deleteKey("CloudEcKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s %n", deletedKeyResponse.getRecoveryId()));
keyAsyncClient.deleteKey("CloudRsaKey").subscribe(deletedKeyResponse ->
System.out.printf("Deleted Key's Recovery Id %s %n", deletedKeyResponse.getRecoveryId()));
Thread.sleep(30000);
keyAsyncClient.listDeletedKeys().subscribe(deletedKey ->
System.out.printf("Deleted key's recovery Id %s %n", deletedKey.getRecoveryId()));
Thread.sleep(15000);
keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse ->
System.out.printf("Storage account key purge status response %d %n", purgeResponse.getStatusCode()));
keyAsyncClient.purgeDeletedKeyWithResponse("CloudEcKey").subscribe(purgeResponse ->
System.out.printf("Bank account key purge status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | class ManagingDeletedKeysAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted keys in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} | class ManagingDeletedKeysAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted keys in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} |
Don't need `\n` | public void purgeDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecret("deletedSecretName")
.doOnSuccess(purgeResponse ->
System.out.println("Successfully Purged deleted Secret \n"));
} | System.out.println("Successfully Purged deleted Secret \n")); | public void purgeDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecret("deletedSecretName")
.doOnSuccess(purgeResponse ->
System.out.println("Successfully Purged deleted Secret"));
} | class SecretAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient keyClient = new SecretClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async SecretAsyncClient
* @return sync SecretAsyncClient
*/
private SecretAsyncClient getAsyncSecretClient() {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getName(),
secretResponse.getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecret("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s \n",
secretWithVersion.getName(), secretWithVersion.getValue()));
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s \n",
secretWithVersion.getName(), secretWithVersion.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecretWithResponse(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getValue().getName(),
secretResponse.getValue().getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecretWithResponse("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s \n",
secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecret(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n",
secretResponse.getName(), secretResponse.getValue()));
secretAsyncClient.setSecret("secretName", "secretValue")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecretWithResponse(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecret(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s \n",
secretResponse.getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecretWithResponse(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s \n",
secretResponse.getValue().getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void purgeDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %n \n", purgeResponse.getStatusCode()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecret("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.getValue().getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s \n", secretBackupResponse.length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s \n", secretBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecret(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s \n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecretWithResponse(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s \n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listDeletedSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listDeletedSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s \n",
deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretVersionsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecretVersions("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
} | class SecretAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient keyClient = new SecretClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async SecretAsyncClient
* @return sync SecretAsyncClient
*/
private SecretAsyncClient getAsyncSecretClient() {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getName(),
secretResponse.getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecret("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s %n",
secretWithVersion.getName(), secretWithVersion.getValue()));
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s %n",
secretWithVersion.getName(), secretWithVersion.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecretWithResponse(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getValue().getName(),
secretResponse.getValue().getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecretWithResponse("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s %n",
secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecret(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n",
secretResponse.getName(), secretResponse.getValue()));
secretAsyncClient.setSecret("secretName", "secretValue")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecretWithResponse(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecret(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s %n",
secretResponse.getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecretWithResponse(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s %n",
secretResponse.getValue().getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void purgeDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecret("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s %n", recoveredSecretResponse.getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s %n", recoveredSecretResponse.getValue().getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s %n", secretBackupResponse.length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s %n", secretBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecret(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecretWithResponse(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listDeletedSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listDeletedSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s %n",
deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretVersionsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecretVersions("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
} |
`%n` | public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
secretAsyncClient.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
String backupFilePath = "YOUR_BACKUP_FILE_PATH";
secretAsyncClient.backupSecret("StorageAccountPassword").subscribe(backupResponse -> {
byte[] backupBytes = backupResponse;
writeBackupToFile(backupBytes, backupFilePath);
});
Thread.sleep(7000);
secretAsyncClient.deleteSecret("StorageAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword").subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath());
secretAsyncClient.restoreSecret(backupFromFile).subscribe(secretResponse ->
System.out.printf("Restored Secret with name %s \n", secretResponse.getName()));
Thread.sleep(15000);
} | System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
secretAsyncClient.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf")
.setExpires(OffsetDateTime.now().plusYears(1)))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
String backupFilePath = "YOUR_BACKUP_FILE_PATH";
secretAsyncClient.backupSecret("StorageAccountPassword").subscribe(backupResponse -> {
byte[] backupBytes = backupResponse;
writeBackupToFile(backupBytes, backupFilePath);
});
Thread.sleep(7000);
secretAsyncClient.deleteSecret("StorageAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword").subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath());
secretAsyncClient.restoreSecret(backupFromFile).subscribe(secretResponse ->
System.out.printf("Restored Secret with name %s %n", secretResponse.getName()));
Thread.sleep(15000);
} | class BackupAndRestoreOperationsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously backup and restore secrets in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
* @throws IOException when writing backup to file is unsuccessful.
*/
private static void writeBackupToFile(byte[] bytes, String filePath) {
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
OutputStream os = new FileOutputStream(file);
os.write(bytes);
System.out.println("Successfully wrote backup to file.");
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | class BackupAndRestoreOperationsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously backup and restore secrets in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
* @throws IOException when writing backup to file is unsuccessful.
*/
private static void writeBackupToFile(byte[] bytes, String filePath) {
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
OutputStream os = new FileOutputStream(file);
os.write(bytes);
System.out.println("Successfully wrote backup to file.");
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
`%n` | public static void main(String[] args) throws InterruptedException {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
secretAsyncClient.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse ->
System.out.printf("Secret returned with name %s , value %s \n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse -> {
Secret secret = secretResponse;
secret.setExpires(secret.getExpires().plusYears(1));
secretAsyncClient.updateSecret(secret).subscribe(updatedSecretResponse ->
System.out.printf("Secret's updated expiry time %s \n", updatedSecretResponse.getExpires().toString()));
});
Thread.sleep(2000);
secretAsyncClient.setSecret("BankAccountPassword", "bhjd4DDgsa").subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword").subscribe(purgeResponse ->
System.out.printf("Bank account secret purge status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | System.out.printf("Bank account secret purge status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws InterruptedException {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
secretAsyncClient.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse ->
System.out.printf("Secret returned with name %s , value %s %n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse -> {
Secret secret = secretResponse;
secret.setExpires(secret.getExpires().plusYears(1));
secretAsyncClient.updateSecret(secret).subscribe(updatedSecretResponse ->
System.out.printf("Secret's updated expiry time %s %n", updatedSecretResponse.getExpires().toString()));
});
Thread.sleep(2000);
secretAsyncClient.setSecret("BankAccountPassword", "bhjd4DDgsa").subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword").subscribe(purgeResponse ->
System.out.printf("Bank account secret purge status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | class HelloWorldAsync {
/**
* Authenticates with the key vault and shows how to asynchronously set, get, update and delete a secret in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} | class HelloWorldAsync {
/**
* Authenticates with the key vault and shows how to asynchronously set, get, update and delete a secret in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} |
`%n` | public static void main(String[] args) throws InterruptedException {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
secretAsyncClient.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.recoverDeletedSecret("BankAccountPassword").subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.getName()));
Thread.sleep(10000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
secretAsyncClient.deleteSecret("StorageAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.listDeletedSecrets().subscribe(deletedSecret ->
System.out.printf("Deleted secret's recovery Id %s \n", deletedSecret.getRecoveryId()));
Thread.sleep(15000);
secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword").subscribe(purgeResponse ->
System.out.printf("Storage account secret purge status response %d \n", purgeResponse.getStatusCode()));
secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword").subscribe(purgeResponse ->
System.out.printf("Bank account secret purge status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | System.out.printf("Storage account secret purge status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws InterruptedException {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
secretAsyncClient.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.recoverDeletedSecret("BankAccountPassword").subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s %n", recoveredSecretResponse.getName()));
Thread.sleep(10000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
secretAsyncClient.deleteSecret("StorageAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.listDeletedSecrets().subscribe(deletedSecret ->
System.out.printf("Deleted secret's recovery Id %s %n", deletedSecret.getRecoveryId()));
Thread.sleep(15000);
secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword").subscribe(purgeResponse ->
System.out.printf("Storage account secret purge status response %d %n", purgeResponse.getStatusCode()));
secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword").subscribe(purgeResponse ->
System.out.printf("Bank account secret purge status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | class ManagingDeletedSecretsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted secrets in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} | class ManagingDeletedSecretsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted secrets in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} |
`%n` | public static void main(String[] args) throws InterruptedException {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
secretAsyncClient.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.recoverDeletedSecret("BankAccountPassword").subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.getName()));
Thread.sleep(10000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
secretAsyncClient.deleteSecret("StorageAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.listDeletedSecrets().subscribe(deletedSecret ->
System.out.printf("Deleted secret's recovery Id %s \n", deletedSecret.getRecoveryId()));
Thread.sleep(15000);
secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword").subscribe(purgeResponse ->
System.out.printf("Storage account secret purge status response %d \n", purgeResponse.getStatusCode()));
secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword").subscribe(purgeResponse ->
System.out.printf("Bank account secret purge status response %d \n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | System.out.printf("Bank account secret purge status response %d \n", purgeResponse.getStatusCode())); | public static void main(String[] args) throws InterruptedException {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
secretAsyncClient.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf")
.setExpires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue()));
Thread.sleep(2000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.recoverDeletedSecret("BankAccountPassword").subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s %n", recoveredSecretResponse.getName()));
Thread.sleep(10000);
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
secretAsyncClient.deleteSecret("StorageAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
Thread.sleep(30000);
secretAsyncClient.listDeletedSecrets().subscribe(deletedSecret ->
System.out.printf("Deleted secret's recovery Id %s %n", deletedSecret.getRecoveryId()));
Thread.sleep(15000);
secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword").subscribe(purgeResponse ->
System.out.printf("Storage account secret purge status response %d %n", purgeResponse.getStatusCode()));
secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword").subscribe(purgeResponse ->
System.out.printf("Bank account secret purge status response %d %n", purgeResponse.getStatusCode()));
Thread.sleep(15000);
} | class ManagingDeletedSecretsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted secrets in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} | class ManagingDeletedSecretsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted secrets in a soft-delete enabled key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
} |
`println` | public void purgeDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecret("deletedSecretName")
.doOnSuccess(purgeResponse ->
System.out.printf("Successfully Purged deleted Secret \n"));
} | System.out.printf("Successfully Purged deleted Secret \n")); | public void purgeDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecret("deletedSecretName")
.doOnSuccess(purgeResponse ->
System.out.println("Successfully Purged deleted Secret"));
} | class SecretAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient keyClient = new SecretClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async SecretAsyncClient
* @return sync SecretAsyncClient
*/
private SecretAsyncClient getAsyncSecretClient() {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getName(),
secretResponse.getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecret("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s \n",
secretWithVersion.getName(), secretWithVersion.getValue()));
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s \n",
secretWithVersion.getName(), secretWithVersion.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecretWithResponse(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getValue().getName(),
secretResponse.getValue().getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecretWithResponse("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s \n",
secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecret(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n",
secretResponse.getName(), secretResponse.getValue()));
secretAsyncClient.setSecret("secretName", "secretValue")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecretWithResponse(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecret(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s \n",
secretResponse.getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecretWithResponse(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s \n",
secretResponse.getValue().getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void purgeDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecret("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.getValue().getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s \n", secretBackupResponse.length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s \n", secretBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecret(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s \n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecretWithResponse(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s \n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listDeletedSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listDeletedSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s \n",
deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretVersionsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecretVersions("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
} | class SecretAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient keyClient = new SecretClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async SecretAsyncClient
* @return sync SecretAsyncClient
*/
private SecretAsyncClient getAsyncSecretClient() {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getName(),
secretResponse.getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecret("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s %n",
secretWithVersion.getName(), secretWithVersion.getValue()));
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s %n",
secretWithVersion.getName(), secretWithVersion.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecretWithResponse(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getValue().getName(),
secretResponse.getValue().getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecretWithResponse("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s %n",
secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecret(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n",
secretResponse.getName(), secretResponse.getValue()));
secretAsyncClient.setSecret("secretName", "secretValue")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecretWithResponse(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecret(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s %n",
secretResponse.getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecretWithResponse(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s %n",
secretResponse.getValue().getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void purgeDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecret("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s %n", recoveredSecretResponse.getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s %n", recoveredSecretResponse.getValue().getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s %n", secretBackupResponse.length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s %n", secretBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecret(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecretWithResponse(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listDeletedSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listDeletedSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s %n",
deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretVersionsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecretVersions("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
} |
`%n` | public void purgeDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode()));
} | System.out.printf("Purge Status response %d \n", purgeResponse.getStatusCode())); | public void purgeDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
} | class SecretAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient keyClient = new SecretClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async SecretAsyncClient
* @return sync SecretAsyncClient
*/
private SecretAsyncClient getAsyncSecretClient() {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getName(),
secretResponse.getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecret("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s \n",
secretWithVersion.getName(), secretWithVersion.getValue()));
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s \n",
secretWithVersion.getName(), secretWithVersion.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecretWithResponse(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getValue().getName(),
secretResponse.getValue().getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecretWithResponse("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s \n",
secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecret(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n",
secretResponse.getName(), secretResponse.getValue()));
secretAsyncClient.setSecret("secretName", "secretValue")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecretWithResponse(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecret(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s \n",
secretResponse.getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecretWithResponse(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s \n",
secretResponse.getValue().getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void purgeDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecret("deletedSecretName")
.doOnSuccess(purgeResponse ->
System.out.printf("Successfully Purged deleted Secret \n"));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecret("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.getValue().getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s \n", secretBackupResponse.length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s \n", secretBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecret(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s \n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecretWithResponse(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s \n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listDeletedSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listDeletedSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s \n",
deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretVersionsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecretVersions("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
} | class SecretAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient keyClient = new SecretClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async SecretAsyncClient
* @return sync SecretAsyncClient
*/
private SecretAsyncClient getAsyncSecretClient() {
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link SecretAsyncClient}
* @return An instance of {@link SecretAsyncClient}
*/
public SecretAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getName(),
secretResponse.getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecret("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s %n",
secretWithVersion.getName(), secretWithVersion.getValue()));
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s %n",
secretWithVersion.getName(), secretWithVersion.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecretWithResponse(secretBase)
.subscribe(secretResponse ->
System.out.printf("Secret is returned with name %s and value %s %n", secretResponse.getValue().getName(),
secretResponse.getValue().getValue())));
String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
secretAsyncClient.getSecretWithResponse("secretName", secretVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretWithVersion ->
System.out.printf("Secret is returned with name %s and value %s %n",
secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecret(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n",
secretResponse.getName(), secretResponse.getValue()));
secretAsyncClient.setSecret("secretName", "secretValue")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void setSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
Secret newSecret = new Secret("secretName", "secretValue").
setExpires(OffsetDateTime.now().plusDays(60));
secretAsyncClient.setSecretWithResponse(newSecret)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s %n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecret(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s %n",
secretResponse.getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void updateSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponseValue -> {
Secret secret = secretResponseValue;
secret.setNotBefore(OffsetDateTime.now().plusDays(50));
secretAsyncClient.updateSecretWithResponse(secret)
.subscribe(secretResponse ->
System.out.printf("Secret's updated not before time %s %n",
secretResponse.getValue().getNotBefore().toString()));
});
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void deleteSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.deleteSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void getDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.getDeletedSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getValue().getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void purgeDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.purgeDeletedSecret("deletedSecretName")
.doOnSuccess(purgeResponse ->
System.out.println("Successfully Purged deleted Secret"));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecret("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s %n", recoveredSecretResponse.getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void recoverDeletedSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.recoverDeletedSecretWithResponse("deletedSecretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Secret with name %s %n", recoveredSecretResponse.getValue().getName()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecret("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s %n", secretBackupResponse.length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void backupSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.backupSecretWithResponse("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBackupResponse ->
System.out.printf("Secret's Backup Byte array's length %s %n", secretBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecret(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
secretResponse.getName(), secretResponse.getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void restoreSecretWithResponseCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
byte[] secretBackupByteArray = {};
secretAsyncClient.restoreSecretWithResponse(secretBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listDeletedSecretsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listDeletedSecrets()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s %n",
deletedSecretResponse.getRecoveryId()));
}
/**
* Method to insert code snippets for {@link SecretAsyncClient
*/
public void listSecretVersionsCodeSnippets() {
SecretAsyncClient secretAsyncClient = getAsyncSecretClient();
secretAsyncClient.listSecretVersions("secretName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(secretBase -> secretAsyncClient.getSecret(secretBase)
.subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
secretResponse.getName(), secretResponse.getValue())));
}
} |
Don't need `\n` | public void purgeDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.doOnSuccess(response -> System.out.println("Successfully Purged certificate \n"));
} | .doOnSuccess(response -> System.out.println("Successfully Purged certificate \n")); | public void purgeDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.doOnSuccess(response -> System.out.println("Successfully Purged certificate"));
} | class CertificateAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RetryPolicy()).build();
CertificateAsyncClient keyClient = new CertificateClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async CertificateAsyncClient
* @return sync CertificateAsyncClient
*/
private CertificateAsyncClient getCertificateAsyncClient() {
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertiificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policy ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policy.issuerName(), policy.subjectName()));
certificateAsyncClient.getCertificatePolicyWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policyResponse ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policyResponse.getValue().issuerName(), policyResponse.getValue().subjectName()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
String certificateVersion = "6A385B124DEF4096AF1361A85B16C204";
certificateAsyncClient.getCertificateWithResponse("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s \n",
certificateWithVersion.getValue().name(), certificateWithVersion.getValue().secretId()));
certificateAsyncClient.getCertificate("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s \n",
certificateWithVersion.name(), certificateWithVersion.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
certificateAsyncClient.createCertificate("certificateName", certPolicy)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.createCertificateIssuer("issuerName", "providerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Issuer issuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuer(issuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.name(), issuerResponse.provider());
});
Issuer newIssuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuerWithResponse(newIssuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.name(), issuerResponse.provider());
}));
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuerWithResponse(issuerBase.getValue())
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
}));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s \n",
certificateResponse.enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuer(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s \n",
issuerResponse.enabled().toString()));
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuerWithResponse(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s \n",
issuerResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for
* {@link CertificateAsyncClient
*/
public void updateCertificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicy("certificateName", certificatePolicy)
.subscribe(updatedPolicy ->
System.out.printf("Certificate policy's updated transparency status %s \n",
updatedPolicy.certificateTransparency().toString()));
});
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicyWithResponse("certificateName",
certificatePolicy)
.subscribe(updatedPolicyResponse ->
System.out.printf("Certificate policy's updated transparency status %s \n",
updatedPolicyResponse.getValue().certificateTransparency().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificateWithResponse(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s \n",
certificateResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s \n", deletedIssuerResponse.getValue().name()));
certificateAsyncClient.deleteCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s \n", deletedIssuerResponse.name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getDeletedCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.getDeletedCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void purgeDeletedCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %n \n", purgeResponse.getStatusCode()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void recoverDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.recoverDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s \n", recoveredSecretResponse.name()));
certificateAsyncClient.recoverDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s \n", recoveredSecretResponse.getValue().name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void backupCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.backupCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s \n", certificateBackupResponse.length));
certificateAsyncClient.backupCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s \n",
certificateBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void restoreCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
byte[] certificateBackupByteArray = {};
certificateAsyncClient.restoreCertificate(certificateBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s \n",
certificateResponse.name(), certificateResponse.keyId()));
byte[] certificateBackup = {};
certificateAsyncClient.restoreCertificate(certificateBackup)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s \n",
certificateResponse.name(), certificateResponse.keyId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateIssuersCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateIssuers()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> System.out.printf("Received issuer with name %s and provider %s",
issuerResponse.name(), issuerResponse.provider())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listDeletedCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listDeletedCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s \n",
deletedCertificateResponse.recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateVersionsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateVersions("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void contactsOperationsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
Contact oontactToAdd = new Contact("user", "useremail@exmaple.com");
certificateAsyncClient.setCertificateContacts(Arrays.asList(oontactToAdd)).subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Deleted Contact name %s and email %s", contact.name(), contact.emailAddress())
);
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* {@link CertificateAsyncClient
*/
public void certificateOperationCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.cancelCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Certificate operation status %s",
certificateOperation.status()));
certificateAsyncClient.cancelCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Certificate operation status %s",
certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Deleted Certificate operation's last"
+ " status %s", certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Deleted Certificate operation last status %s",
certificateOperation.status()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void getPendingCertificateSigningRequestCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getPendingCertificateSigningRequest("certificateName")
.subscribe(signingRequest -> System.out.printf("Received Signing request blob of length %s",
signingRequest.length));
certificateAsyncClient.getPendingCertificateSigningRequestWithResponse("certificateName")
.subscribe(signingRequestResponse -> System.out.printf("Received Signing request blob of length %s",
signingRequestResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void mergeCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
List<byte[]> x509Certs = new ArrayList<>();
certificateAsyncClient.mergeCertificate("certificateName", x509Certs)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509Certificates = new ArrayList<>();
certificateAsyncClient.mergeCertificateWithResponse("certificateName", x509Certificates)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
List<byte[]> x509CertificatesToMerge = new ArrayList<>();
MergeCertificateOptions config = new MergeCertificateOptions("certificateName", x509CertificatesToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificate(config)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509CertsToMerge = new ArrayList<>();
MergeCertificateOptions mergeConfig = new MergeCertificateOptions("certificateName", x509CertsToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificateWithResponse(mergeConfig)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
}
} | class CertificateAsyncClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithHttpclient() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RetryPolicy()).build();
CertificateAsyncClient keyClient = new CertificateClientBuilder()
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.addPolicy(new RecordNetworkCallPolicy(networkData))
.httpClient(HttpClient.createDefault())
.buildAsyncClient();
return keyClient;
}
/**
* Implementation for async CertificateAsyncClient
* @return sync CertificateAsyncClient
*/
private CertificateAsyncClient getCertificateAsyncClient() {
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https:
.httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Generates code sample for creating a {@link CertificateAsyncClient}
* @return An instance of {@link CertificateAsyncClient}
*/
public CertificateAsyncClient createAsyncClientWithPipeline() {
RecordedData networkData = new RecordedData();
HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(networkData)).build();
CertificateAsyncClient secretAsyncClient = new CertificateClientBuilder()
.pipeline(pipeline)
.endpoint("https:
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
return secretAsyncClient;
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertiificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policy ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policy.issuerName(), policy.subjectName()));
certificateAsyncClient.getCertificatePolicyWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(policyResponse ->
System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n",
policyResponse.getValue().issuerName(), policyResponse.getValue().subjectName()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId()));
String certificateVersion = "6A385B124DEF4096AF1361A85B16C204";
certificateAsyncClient.getCertificateWithResponse("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s %n",
certificateWithVersion.getValue().name(), certificateWithVersion.getValue().secretId()));
certificateAsyncClient.getCertificate("certificateName", certificateVersion)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateWithVersion ->
System.out.printf("Certificate is returned with name %s and secretId %s %n",
certificateWithVersion.name(), certificateWithVersion.secretId()));
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse ->
System.out.printf("Certificate is returned with name %s and secretId %s %n", certificateResponse.name(),
certificateResponse.secretId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
Map<String, String> tags = new HashMap<>();
tags.put("foo", "bar");
certificateAsyncClient.createCertificate("certificateName", policy, tags)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12");
certificateAsyncClient.createCertificate("certificateName", certPolicy)
.getObserver().subscribe(pollResponse -> {
System.out.println("---------------------------------------------------------------------------------");
System.out.println(pollResponse.getStatus());
System.out.println(pollResponse.getValue().status());
System.out.println(pollResponse.getValue().statusDetails());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void createCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.createCertificateIssuer("issuerName", "providerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer created with %s and %s", issuer.name(), issuer.provider());
});
Issuer issuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuer(issuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.name(), issuerResponse.provider());
});
Issuer newIssuer = new Issuer("issuerName", "providerName")
.accountId("keyvaultuser")
.password("temp2");
certificateAsyncClient.createCertificateIssuerWithResponse(newIssuer)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer created with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuer -> {
System.out.printf("Issuer returned with %s and %s", issuer.name(), issuer.provider());
});
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.name(), issuerResponse.provider());
}));
certificateAsyncClient.getCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuerWithResponse(issuerBase.getValue())
.subscribe(issuerResponse -> {
System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().name(),
issuerResponse.getValue().provider());
}));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificate(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s %n",
certificateResponse.enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuer(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s %n",
issuerResponse.enabled().toString()));
});
certificateAsyncClient.getCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerResponseValue -> {
Issuer issuer = issuerResponseValue;
issuer.enabled(false);
certificateAsyncClient.updateCertificateIssuerWithResponse(issuer)
.subscribe(issuerResponse ->
System.out.printf("Issuer's enabled status %s %n",
issuerResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for
* {@link CertificateAsyncClient
*/
public void updateCertificatePolicyCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicy("certificateName", certificatePolicy)
.subscribe(updatedPolicy ->
System.out.printf("Certificate policy's updated transparency status %s %n",
updatedPolicy.certificateTransparency().toString()));
});
certificateAsyncClient.getCertificatePolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificatePolicyResponseValue -> {
CertificatePolicy certificatePolicy = certificatePolicyResponseValue;
certificatePolicy.certificateTransparency(true);
certificateAsyncClient.updateCertificatePolicyWithResponse("certificateName",
certificatePolicy)
.subscribe(updatedPolicyResponse ->
System.out.printf("Certificate policy's updated transparency status %s %n",
updatedPolicyResponse.getValue().certificateTransparency().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void updateCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getCertificateWithPolicy("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponseValue -> {
Certificate certificate = certificateResponseValue;
certificate.enabled(false);
certificateAsyncClient.updateCertificateWithResponse(certificate)
.subscribe(certificateResponse ->
System.out.printf("Certificate's enabled status %s %n",
certificateResponse.getValue().enabled().toString()));
});
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.deleteCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void deleteCertificateIssuerCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.deleteCertificateIssuerWithResponse("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().name()));
certificateAsyncClient.deleteCertificateIssuer("issuerName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedIssuerResponse ->
System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void getDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getDeletedCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.recoveryId()));
certificateAsyncClient.getDeletedCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedSecretResponse ->
System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedSecretResponse.getValue().recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void purgeDeletedCertificateWithResponseCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(purgeResponse ->
System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void recoverDeletedCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.recoverDeletedCertificate("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s %n", recoveredSecretResponse.name()));
certificateAsyncClient.recoverDeletedCertificateWithResponse("deletedCertificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(recoveredSecretResponse ->
System.out.printf("Recovered Certificate with name %s %n", recoveredSecretResponse.getValue().name()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void backupCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.backupCertificate("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s %n", certificateBackupResponse.length));
certificateAsyncClient.backupCertificateWithResponse("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBackupResponse ->
System.out.printf("Certificate's Backup Byte array's length %s %n",
certificateBackupResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void restoreCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
byte[] certificateBackupByteArray = {};
certificateAsyncClient.restoreCertificate(certificateBackupByteArray)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n",
certificateResponse.name(), certificateResponse.keyId()));
byte[] certificateBackup = {};
certificateAsyncClient.restoreCertificate(certificateBackup)
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n",
certificateResponse.name(), certificateResponse.keyId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateIssuersCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateIssuers()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(issuerBase -> certificateAsyncClient.getCertificateIssuer(issuerBase)
.subscribe(issuerResponse -> System.out.printf("Received issuer with name %s and provider %s",
issuerResponse.name(), issuerResponse.provider())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listDeletedCertificatesCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listDeletedCertificates()
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s %n",
deletedCertificateResponse.recoveryId()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void listCertificateVersionsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.listCertificateVersions("certificateName")
.subscriberContext(Context.of(key1, value1, key2, value2))
.subscribe(certificateBase -> certificateAsyncClient.getCertificate(certificateBase)
.subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s",
certificateResponse.name(), certificateResponse.keyId())));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
*/
public void contactsOperationsCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
Contact oontactToAdd = new Contact("user", "useremail@exmaple.com");
certificateAsyncClient.setCertificateContacts(Arrays.asList(oontactToAdd)).subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Contact name %s and email %s", contact.name(), contact.emailAddress())
);
certificateAsyncClient.listCertificateContacts().subscribe(contact ->
System.out.printf("Deleted Contact name %s and email %s", contact.name(), contact.emailAddress())
);
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* {@link CertificateAsyncClient
*/
public void certificateOperationCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.cancelCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Certificate operation status %s",
certificateOperation.status()));
certificateAsyncClient.cancelCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Certificate operation status %s",
certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperationWithResponse("certificateName")
.subscribe(certificateOperationResponse -> System.out.printf("Deleted Certificate operation's last"
+ " status %s", certificateOperationResponse.getValue().status()));
certificateAsyncClient.deleteCertificateOperation("certificateName")
.subscribe(certificateOperation -> System.out.printf("Deleted Certificate operation last status %s",
certificateOperation.status()));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void getPendingCertificateSigningRequestCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
certificateAsyncClient.getPendingCertificateSigningRequest("certificateName")
.subscribe(signingRequest -> System.out.printf("Received Signing request blob of length %s",
signingRequest.length));
certificateAsyncClient.getPendingCertificateSigningRequestWithResponse("certificateName")
.subscribe(signingRequestResponse -> System.out.printf("Received Signing request blob of length %s",
signingRequestResponse.getValue().length));
}
/**
* Method to insert code snippets for {@link CertificateAsyncClient
* and {@link CertificateAsyncClient
*/
public void mergeCertificateCodeSnippets() {
CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient();
List<byte[]> x509Certs = new ArrayList<>();
certificateAsyncClient.mergeCertificate("certificateName", x509Certs)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509Certificates = new ArrayList<>();
certificateAsyncClient.mergeCertificateWithResponse("certificateName", x509Certificates)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
List<byte[]> x509CertificatesToMerge = new ArrayList<>();
MergeCertificateOptions config = new MergeCertificateOptions("certificateName", x509CertificatesToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificate(config)
.subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s",
certificate.name(), certificate.keyId()));
List<byte[]> x509CertsToMerge = new ArrayList<>();
MergeCertificateOptions mergeConfig = new MergeCertificateOptions("certificateName", x509CertsToMerge)
.enabled(false);
certificateAsyncClient.mergeCertificateWithResponse(mergeConfig)
.subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s",
certificateResponse.getValue().name(), certificateResponse.getValue().keyId()));
}
} |
You can create a static instance of this `ObjectMapper` to avoid creating lots of these objects for every `decryptBlob` call. | private EncryptionData getAndValidateEncryptionData(String encryptedDataString) {
if (encryptedDataString == null) {
throw logger.logExceptionAsError(new IllegalStateException(CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB));
}
ObjectMapper objectMapper = new ObjectMapper();
try {
EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class);
if (encryptionData == null) {
throw logger.logExceptionAsError(new IllegalStateException(
CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB));
}
Objects.requireNonNull(encryptionData.contentEncryptionIV());
Objects.requireNonNull(encryptionData.wrappedContentKey().getEncryptedKey());
if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1.equals(encryptionData.encryptionAgent().getProtocol())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT,
"Invalid Encryption Agent. This version of the client library does not understand the "
+ "Encryption Agent set on the blob message: %s",
encryptionData.encryptionAgent())));
}
return encryptionData;
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
} | ObjectMapper objectMapper = new ObjectMapper(); | private EncryptionData getAndValidateEncryptionData(String encryptedDataString) {
if (encryptedDataString == null) {
return null;
}
ObjectMapper objectMapper = new ObjectMapper();
try {
EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class);
if (encryptionData == null) {
return encryptionData;
}
Objects.requireNonNull(encryptionData.getContentEncryptionIV(), "contentEncryptionIV in encryptionData "
+ "cannot be null");
Objects.requireNonNull(encryptionData.getWrappedContentKey().getEncryptedKey(), "encryptedKey in "
+ "encryptionData.wrappedContentKey cannot be null");
if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1
.equals(encryptionData.getEncryptionAgent().getProtocol())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT,
"Invalid Encryption Agent. This version of the client library does not understand the "
+ "Encryption Agent set on the blob message: %s",
encryptionData.getEncryptionAgent())));
}
return encryptionData;
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} |
Add an error message to indicate what was null everywhere you are using `Objects.requireNonNull` ```suggestion Objects.requireNonNull(encryptionData.contentEncryptionIV(), "contentEncryptionIV in encryptionData cannot be null"); ``` | private EncryptionData getAndValidateEncryptionData(String encryptedDataString) {
if (encryptedDataString == null) {
throw logger.logExceptionAsError(new IllegalStateException(CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB));
}
ObjectMapper objectMapper = new ObjectMapper();
try {
EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class);
if (encryptionData == null) {
throw logger.logExceptionAsError(new IllegalStateException(
CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB));
}
Objects.requireNonNull(encryptionData.contentEncryptionIV());
Objects.requireNonNull(encryptionData.wrappedContentKey().getEncryptedKey());
if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1.equals(encryptionData.encryptionAgent().getProtocol())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT,
"Invalid Encryption Agent. This version of the client library does not understand the "
+ "Encryption Agent set on the blob message: %s",
encryptionData.encryptionAgent())));
}
return encryptionData;
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
} | Objects.requireNonNull(encryptionData.contentEncryptionIV()); | private EncryptionData getAndValidateEncryptionData(String encryptedDataString) {
if (encryptedDataString == null) {
return null;
}
ObjectMapper objectMapper = new ObjectMapper();
try {
EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class);
if (encryptionData == null) {
return encryptionData;
}
Objects.requireNonNull(encryptionData.getContentEncryptionIV(), "contentEncryptionIV in encryptionData "
+ "cannot be null");
Objects.requireNonNull(encryptionData.getWrappedContentKey().getEncryptedKey(), "encryptedKey in "
+ "encryptionData.wrappedContentKey cannot be null");
if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1
.equals(encryptionData.getEncryptionAgent().getProtocol())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT,
"Invalid Encryption Agent. This version of the client library does not understand the "
+ "Encryption Agent set on the blob message: %s",
encryptionData.getEncryptionAgent())));
}
return encryptionData;
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} |
This should throw NPE instead - https://azure.github.io/azure-sdk/java_implementation.html#java-errors-system-errors | private EncryptionData getAndValidateEncryptionData(String encryptedDataString) {
if (encryptedDataString == null) {
throw logger.logExceptionAsError(new IllegalStateException(CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB));
}
ObjectMapper objectMapper = new ObjectMapper();
try {
EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class);
if (encryptionData == null) {
throw logger.logExceptionAsError(new IllegalStateException(
CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB));
}
Objects.requireNonNull(encryptionData.contentEncryptionIV());
Objects.requireNonNull(encryptionData.wrappedContentKey().getEncryptedKey());
if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1.equals(encryptionData.encryptionAgent().getProtocol())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT,
"Invalid Encryption Agent. This version of the client library does not understand the "
+ "Encryption Agent set on the blob message: %s",
encryptionData.encryptionAgent())));
}
return encryptionData;
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
} | if (encryptedDataString == null) { | private EncryptionData getAndValidateEncryptionData(String encryptedDataString) {
if (encryptedDataString == null) {
return null;
}
ObjectMapper objectMapper = new ObjectMapper();
try {
EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class);
if (encryptionData == null) {
return encryptionData;
}
Objects.requireNonNull(encryptionData.getContentEncryptionIV(), "contentEncryptionIV in encryptionData "
+ "cannot be null");
Objects.requireNonNull(encryptionData.getWrappedContentKey().getEncryptedKey(), "encryptedKey in "
+ "encryptionData.wrappedContentKey cannot be null");
if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1
.equals(encryptionData.getEncryptionAgent().getProtocol())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT,
"Invalid Encryption Agent. This version of the client library does not understand the "
+ "Encryption Agent set on the blob message: %s",
encryptionData.getEncryptionAgent())));
}
return encryptionData;
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} |
Don't need this check as the `blobName()` builder method already checks for null. | private AzureBlobStorageImpl constructImpl() {
Objects.requireNonNull(blobName, "'blobName' cannot be null.");
/*
Implicit and explicit root container access are functionally equivalent, but explicit references are easier
to read and debug.
*/
if (ImplUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
checkValidEncryptionParameters();
HttpPipeline pipeline = super.getPipeline();
if (pipeline == null) {
pipeline = buildPipeline();
}
return new AzureBlobStorageBuilder()
.url(String.format("%s/%s/%s", endpoint, containerName, blobName))
.pipeline(pipeline)
.build();
} | Objects.requireNonNull(blobName, "'blobName' cannot be null."); | private AzureBlobStorageImpl constructImpl() {
Objects.requireNonNull(blobName, "'blobName' cannot be null.");
/*
Implicit and explicit root container access are functionally equivalent, but explicit references are easier
to read and debug.
*/
if (ImplUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
checkValidEncryptionParameters();
HttpPipeline pipeline = super.getPipeline();
if (pipeline == null) {
pipeline = buildPipeline();
}
return new AzureBlobStorageBuilder()
.url(String.format("%s/%s/%s", endpoint, containerName, blobName))
.pipeline(pipeline)
.build();
} | class EncryptedBlobClientBuilder extends BaseBlobClientBuilder<EncryptedBlobClientBuilder> {
private final ClientLogger logger = new ClientLogger(EncryptedBlobClientBuilder.class);
private String containerName;
private String blobName;
private String snapshot;
private AsyncKeyEncryptionKey keyWrapper;
private AsyncKeyEncryptionKeyResolver keyResolver;
private KeyWrapAlgorithm keyWrapAlgorithm;
/**
* Creates a new instance of the EncryptedBlobClientBuilder
*/
public EncryptedBlobClientBuilder() {
}
/**
* Creates an {@code EncryptedBlockBlobAsyncClient} from a {@code BlockBlobAsyncClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlockBlobAsyncClient
*
* @param client The client to convert.
* @return The encrypted client.
*/
public EncryptedBlockBlobAsyncClient buildEncryptedBlockBlobAsyncClient(BlockBlobAsyncClient client) {
checkValidEncryptionParameters();
AzureBlobStorageImpl impl = new AzureBlobStorageBuilder()
.url(client.getBlobUrl())
.pipeline(addDecryptionPolicy(client.getHttpPipeline(),
client.getHttpPipeline().getHttpClient()))
.build();
return new EncryptedBlockBlobAsyncClient(impl, client.getSnapshotId(), client.getAccountName(), this.keyWrapper,
this.keyWrapAlgorithm);
}
/**
* Creates an {@code EncryptedBlockBlobClient} from a {@code BlockBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlockBlobClient
*
* @param client The client to convert.
* @return The encrypted client.
*/
public EncryptedBlockBlobClient buildEncryptedBlockBlobClient(BlockBlobClient client) {
checkValidEncryptionParameters();
AzureBlobStorageImpl impl = new AzureBlobStorageBuilder()
.url(client.getBlobUrl())
.pipeline(addDecryptionPolicy(client.getHttpPipeline(),
client.getHttpPipeline().getHttpClient()))
.build();
return new EncryptedBlockBlobClient(new EncryptedBlockBlobAsyncClient(impl, client.getSnapshotId(),
client.getAccountName(), this.keyWrapper, this.keyWrapAlgorithm));
}
/**
* Creates a {@link EncryptedBlockBlobClient} based on options set in the Builder.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlockBlobAsyncClient}
*
* @return a {@link EncryptedBlockBlobClient} created from the configurations in this builder.
* @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
*/
public EncryptedBlockBlobClient buildEncryptedBlockBlobClient() {
return new EncryptedBlockBlobClient(buildEncryptedBlockBlobAsyncClient());
}
/**
* Creates a {@link EncryptedBlockBlobAsyncClient} based on options set in the Builder.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlockBlobClient}
*
* @return a {@link EncryptedBlockBlobAsyncClient} created from the configurations in this builder.
* @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
*/
public EncryptedBlockBlobAsyncClient buildEncryptedBlockBlobAsyncClient() {
return new EncryptedBlockBlobAsyncClient(constructImpl(), snapshot, accountName, keyWrapper, keyWrapAlgorithm);
}
/**
* Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name)
* @param endpoint URL of the service
* @return the updated BlobClientBuilder object
* @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL.
*/
@Override
public EncryptedBlobClientBuilder endpoint(String endpoint) {
try {
URL url = new URL(endpoint);
BlobUrlParts parts = BlobUrlParts.parse(url);
this.accountName = parts.getAccountName();
this.endpoint = parts.getScheme() + ":
this.containerName = parts.getBlobContainerName();
this.blobName = parts.getBlobName();
this.snapshot = parts.getSnapshot();
String sasToken = parts.getSasQueryParameters().encode();
if (ImplUtils.isNullOrEmpty(sasToken)) {
super.sasToken(sasToken);
}
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(
new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."));
}
return this;
}
@Override
protected void addOptionalEncryptionPolicy(List<HttpPipelinePolicy> policies) {
BlobDecryptionPolicy decryptionPolicy = new BlobDecryptionPolicy(keyWrapper, keyResolver);
policies.add(decryptionPolicy);
}
/**
* Sets the name of the container this client is connecting to.
* @param containerName the name of the container
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder containerName(String containerName) {
this.containerName = containerName;
return this;
}
/**
* Sets the name of the blob this client is connecting to.
*
* @param blobName the name of the blob
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code blobName} is {@code null}
*/
public EncryptedBlobClientBuilder blobName(String blobName) {
this.blobName = Objects.requireNonNull(blobName);
return this;
}
/**
* Sets the snapshot of the blob this client is connecting to.
*
* @param snapshot the snapshot identifier for the blob
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder snapshot(String snapshot) {
this.snapshot = snapshot;
return this;
}
/**
* Sets the customer provided key for a Storage Builder. This will not work for an Encrypted Client
* since they are not compatible functions.
*
* @param key The customer provided key
* @return the updated EncryptedBlobClientBuilder object
* @throws UnsupportedOperationException Since customer provided key and client side encryption
* are different functions
*/
@Override
public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey key) {
throw logger.logExceptionAsError(new UnsupportedOperationException("Customer Provided Key "
+ "and Encryption are not compatible"));
}
/**
* Sets the encryption key parameters for the client
*
* @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key
* @param keyWrapAlgorithm The {@link KeyWrapAlgorithm} used to wrap the key.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, KeyWrapAlgorithm keyWrapAlgorithm) {
this.keyWrapper = key;
this.keyWrapAlgorithm = keyWrapAlgorithm;
return this;
}
/**
* Sets the encryption parameters for this client
*
* @param keyResolver The key resolver used to select the correct key for decrypting existing blobs.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) {
this.keyResolver = keyResolver;
return this;
}
private void checkValidEncryptionParameters() {
if (this.keyWrapper == null && this.keyResolver == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null"));
}
if (this.keyWrapper != null && this.keyWrapAlgorithm == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Wrap Algorithm must be specified with "
+ "the Key."));
}
}
/**
* Gets the {@link UserAgentPolicy user agent policy} that is used to set the User-Agent header for each request.
*
* @return the {@code UserAgentPolicy} that will be used in the {@link HttpPipeline}.
*/
protected final UserAgentPolicy getUserAgentPolicy() {
return new UserAgentPolicy(BlobCryptographyConfiguration.NAME, BlobCryptographyConfiguration.VERSION,
super.getConfiguration());
}
@Override
protected Class<EncryptedBlobClientBuilder> getClazz() {
return EncryptedBlobClientBuilder.class;
}
private HttpPipeline addDecryptionPolicy(HttpPipeline originalPipeline, HttpClient client) {
HttpPipelinePolicy[] policies = new HttpPipelinePolicy[originalPipeline.getPolicyCount() + 1];
policies[0] = new BlobDecryptionPolicy(keyWrapper, keyResolver);
for (int i = 0; i < originalPipeline.getPolicyCount(); i++) {
policies[i + 1] = originalPipeline.getPolicy(i);
}
return new HttpPipelineBuilder()
.httpClient(client)
.policies(policies)
.build();
}
} | class EncryptedBlobClientBuilder extends BaseBlobClientBuilder<EncryptedBlobClientBuilder> {
private final ClientLogger logger = new ClientLogger(EncryptedBlobClientBuilder.class);
private String containerName;
private String blobName;
private String snapshot;
private AsyncKeyEncryptionKey keyWrapper;
private AsyncKeyEncryptionKeyResolver keyResolver;
private String keyWrapAlgorithm;
/**
* Creates a new instance of the EncryptedBlobClientBuilder
*/
public EncryptedBlobClientBuilder() {
}
/**
* Creates a {@link EncryptedBlobClient} based on options set in the Builder.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient}
*
* @return a {@link EncryptedBlobClient} created from the configurations in this builder.
* @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
*/
public EncryptedBlobClient buildEncryptedBlobClient() {
return new EncryptedBlobClient(buildEncryptedBlobAsyncClient());
}
/**
* Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient}
*
* @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder.
* @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
*/
public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() {
return new EncryptedBlobAsyncClient(constructImpl(), snapshot, accountName, keyWrapper, keyWrapAlgorithm);
}
/**
* Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name)
* @param endpoint URL of the service
* @return the updated BlobClientBuilder object
* @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL.
*/
@Override
public EncryptedBlobClientBuilder endpoint(String endpoint) {
try {
URL url = new URL(endpoint);
BlobUrlParts parts = BlobUrlParts.parse(url);
this.accountName = parts.getAccountName();
this.endpoint = parts.getScheme() + ":
this.containerName = parts.getBlobContainerName();
this.blobName = parts.getBlobName();
this.snapshot = parts.getSnapshot();
String sasToken = parts.getSasQueryParameters().encode();
if (ImplUtils.isNullOrEmpty(sasToken)) {
super.sasToken(sasToken);
}
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(
new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."));
}
return this;
}
@Override
protected void addOptionalEncryptionPolicy(List<HttpPipelinePolicy> policies) {
BlobDecryptionPolicy decryptionPolicy = new BlobDecryptionPolicy(keyWrapper, keyResolver);
policies.add(decryptionPolicy);
}
/**
* Sets the name of the container this client is connecting to.
* @param containerName the name of the container
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder containerName(String containerName) {
this.containerName = containerName;
return this;
}
/**
* Sets the name of the blob this client is connecting to.
*
* @param blobName the name of the blob
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code blobName} is {@code null}
*/
public EncryptedBlobClientBuilder blobName(String blobName) {
this.blobName = blobName;
return this;
}
/**
* Sets the snapshot of the blob this client is connecting to.
*
* @param snapshot the snapshot identifier for the blob
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder snapshot(String snapshot) {
this.snapshot = snapshot;
return this;
}
/**
* Sets the customer provided key for a Storage Builder. This will not work for an Encrypted Client
* since they are not compatible functions.
*
* @param key The customer provided key
* @return the updated EncryptedBlobClientBuilder object
* @throws UnsupportedOperationException Since customer provided key and client side encryption
* are different functions
*/
@Override
public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey key) {
throw logger.logExceptionAsError(new UnsupportedOperationException("Customer Provided Key "
+ "and Encryption are not compatible"));
}
/**
* Sets the encryption key parameters for the client
*
* @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key
* @param keyWrapAlgorithm The {@link String} used to wrap the key.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) {
this.keyWrapper = key;
this.keyWrapAlgorithm = keyWrapAlgorithm;
return this;
}
/**
* Sets the encryption parameters for this client
*
* @param keyResolver The key resolver used to select the correct key for decrypting existing blobs.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) {
this.keyResolver = keyResolver;
return this;
}
private void checkValidEncryptionParameters() {
if (this.keyWrapper == null && this.keyResolver == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null"));
}
if (this.keyWrapper != null && this.keyWrapAlgorithm == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Wrap Algorithm must be specified with "
+ "the Key."));
}
}
/**
* Gets the {@link UserAgentPolicy user agent policy} that is used to set the User-Agent header for each request.
*
* @return the {@code UserAgentPolicy} that will be used in the {@link HttpPipeline}.
*/
protected UserAgentPolicy getUserAgentPolicy() {
return new UserAgentPolicy(BlobCryptographyConfiguration.NAME, BlobCryptographyConfiguration.VERSION,
super.getConfiguration());
}
@Override
protected Class<EncryptedBlobClientBuilder> getClazz() {
return EncryptedBlobClientBuilder.class;
}
} |
Was this a bug in the previously released preview? | public BlobContainerClientBuilder endpoint(String endpoint) {
try {
URL url = new URL(endpoint);
BlobUrlParts parts = BlobUrlParts.parse(url);
this.endpoint = parts.getScheme() + ":
this.containerName = parts.getBlobContainerName();
String sasToken = parts.getSasQueryParameters().encode();
if (!ImplUtils.isNullOrEmpty(sasToken)) {
this.sasToken(sasToken);
}
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(
new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."));
}
return this;
} | if (!ImplUtils.isNullOrEmpty(sasToken)) { | public BlobContainerClientBuilder endpoint(String endpoint) {
try {
URL url = new URL(endpoint);
BlobUrlParts parts = BlobUrlParts.parse(url);
this.endpoint = parts.getScheme() + ":
this.containerName = parts.getBlobContainerName();
String sasToken = parts.getSasQueryParameters().encode();
if (!ImplUtils.isNullOrEmpty(sasToken)) {
this.sasToken(sasToken);
}
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(
new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."));
}
return this;
} | class BlobContainerClientBuilder {
private final ClientLogger logger = new ClientLogger(BlobContainerClientBuilder.class);
private String endpoint;
private String accountName;
private String containerName;
private CpkInfo customerProvidedKey;
private SharedKeyCredential sharedKeyCredential;
private TokenCredential tokenCredential;
private SasTokenCredential sasTokenCredential;
private HttpClient httpClient;
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private HttpLogOptions logOptions = new HttpLogOptions();
private RequestRetryOptions retryOptions = new RequestRetryOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
/**
* Creates a builder instance that is able to configure and construct {@link BlobContainerClient ContainerClients}
* and {@link BlobContainerAsyncClient ContainerAsyncClients}.
*/
public BlobContainerClientBuilder() {
}
/**
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.buildClient}
*
* @return a {@link BlobContainerClient} created from the configurations in this builder.
*/
public BlobContainerClient buildClient() {
return new BlobContainerClient(buildAsyncClient());
}
/**
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.buildAsyncClient}
*
* @return a {@link BlobContainerAsyncClient} created from the configurations in this builder.
*/
public BlobContainerAsyncClient buildAsyncClient() {
/*
Implicit and explicit root container access are functionally equivalent, but explicit references are easier
to read and debug.
*/
if (Objects.isNull(containerName) || containerName.isEmpty()) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(() -> {
if (sharedKeyCredential != null) {
return new SharedKeyCredentialPolicy(sharedKeyCredential);
} else if (tokenCredential != null) {
return new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint));
} else if (sasTokenCredential != null) {
return new SasTokenCredentialPolicy(sasTokenCredential);
} else {
return null;
}
}, retryOptions, logOptions, httpClient, additionalPolicies, configuration);
return new BlobContainerAsyncClient(new AzureBlobStorageBuilder()
.url(String.format("%s/%s", endpoint, containerName))
.pipeline(pipeline)
.build(), customerProvidedKey, accountName);
}
/**
* Sets the service endpoint, additionally parses it for information (SAS token, container name)
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.endpoint
*
* @param endpoint URL of the service
* @return the updated BlobContainerClientBuilder object
* @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL.
*/
/**
* Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server.
*
* @param customerProvidedKey Customer provided key containing the encryption key information.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) {
if (customerProvidedKey == null) {
this.customerProvidedKey = null;
} else {
this.customerProvidedKey = new CpkInfo()
.setEncryptionKey(customerProvidedKey.getKey())
.setEncryptionKeySha256(customerProvidedKey.getKeySHA256())
.setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm());
}
return this;
}
/**
* Sets the {@link SharedKeyCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public BlobContainerClientBuilder credential(SharedKeyCredential credential) {
this.sharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public BlobContainerClientBuilder credential(TokenCredential credential) {
this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.sharedKeyCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code sasToken} is {@code null}.
*/
public BlobContainerClientBuilder sasToken(String sasToken) {
this.sasTokenCredential = new SasTokenCredential(Objects.requireNonNull(sasToken,
"'sasToken' cannot be null."));
this.sharedKeyCredential = null;
this.tokenCredential = null;
return this;
}
/**
* Clears the credential used to authorize the request.
*
* <p>This is for containers that are publicly accessible.</p>
*
* @return the updated BlobContainerClientBuilder
*/
public BlobContainerClientBuilder setAnonymousAccess() {
this.sharedKeyCredential = null;
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Constructs a {@link SharedKeyCredential} used to authorize requests sent to the service. Additionally, if the
* connection string contains `DefaultEndpointsProtocol` and `EndpointSuffix` it will set the {@link
*
*
* @param connectionString Connection string of the storage account.
* @return the updated BlobContainerClientBuilder
* @throws IllegalArgumentException If {@code connectionString} doesn't contain `AccountName` or `AccountKey`.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public BlobContainerClientBuilder connectionString(String connectionString) {
BuilderHelper.configureConnectionString(connectionString, (accountName) -> this.accountName = accountName,
this::credential, this::endpoint, logger);
return this;
}
/**
* Sets the name of the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.Builder.containerName
*
* @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root},
* will be used.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder containerName(String containerName) {
this.containerName = containerName;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent.
*
* @param pipelinePolicy a pipeline policy
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public BlobContainerClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public BlobContainerClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryOptions The options used to configure retry behavior.
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public BlobContainerClientBuilder retryOptions(RequestRetryOptions retryOptions) {
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
} | class BlobContainerClientBuilder {
private final ClientLogger logger = new ClientLogger(BlobContainerClientBuilder.class);
private String endpoint;
private String accountName;
private String containerName;
private CpkInfo customerProvidedKey;
private SharedKeyCredential sharedKeyCredential;
private TokenCredential tokenCredential;
private SasTokenCredential sasTokenCredential;
private HttpClient httpClient;
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private HttpLogOptions logOptions = new HttpLogOptions();
private RequestRetryOptions retryOptions = new RequestRetryOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
/**
* Creates a builder instance that is able to configure and construct {@link BlobContainerClient ContainerClients}
* and {@link BlobContainerAsyncClient ContainerAsyncClients}.
*/
public BlobContainerClientBuilder() {
}
/**
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.buildClient}
*
* @return a {@link BlobContainerClient} created from the configurations in this builder.
*/
public BlobContainerClient buildClient() {
return new BlobContainerClient(buildAsyncClient());
}
/**
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.buildAsyncClient}
*
* @return a {@link BlobContainerAsyncClient} created from the configurations in this builder.
*/
public BlobContainerAsyncClient buildAsyncClient() {
/*
Implicit and explicit root container access are functionally equivalent, but explicit references are easier
to read and debug.
*/
if (Objects.isNull(containerName) || containerName.isEmpty()) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(() -> {
if (sharedKeyCredential != null) {
return new SharedKeyCredentialPolicy(sharedKeyCredential);
} else if (tokenCredential != null) {
return new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint));
} else if (sasTokenCredential != null) {
return new SasTokenCredentialPolicy(sasTokenCredential);
} else {
return null;
}
}, retryOptions, logOptions, httpClient, additionalPolicies, configuration);
return new BlobContainerAsyncClient(new AzureBlobStorageBuilder()
.url(String.format("%s/%s", endpoint, containerName))
.pipeline(pipeline)
.build(), customerProvidedKey, accountName);
}
/**
* Sets the service endpoint, additionally parses it for information (SAS token, container name)
*
* @param endpoint URL of the service
* @return the updated BlobContainerClientBuilder object
* @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL.
*/
/**
* Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server.
*
* @param customerProvidedKey Customer provided key containing the encryption key information.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) {
if (customerProvidedKey == null) {
this.customerProvidedKey = null;
} else {
this.customerProvidedKey = new CpkInfo()
.setEncryptionKey(customerProvidedKey.getKey())
.setEncryptionKeySha256(customerProvidedKey.getKeySHA256())
.setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm());
}
return this;
}
/**
* Sets the {@link SharedKeyCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public BlobContainerClientBuilder credential(SharedKeyCredential credential) {
this.sharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public BlobContainerClientBuilder credential(TokenCredential credential) {
this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.sharedKeyCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code sasToken} is {@code null}.
*/
public BlobContainerClientBuilder sasToken(String sasToken) {
this.sasTokenCredential = new SasTokenCredential(Objects.requireNonNull(sasToken,
"'sasToken' cannot be null."));
this.sharedKeyCredential = null;
this.tokenCredential = null;
return this;
}
/**
* Clears the credential used to authorize the request.
*
* <p>This is for containers that are publicly accessible.</p>
*
* @return the updated BlobContainerClientBuilder
*/
public BlobContainerClientBuilder setAnonymousAccess() {
this.sharedKeyCredential = null;
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Constructs a {@link SharedKeyCredential} used to authorize requests sent to the service. Additionally, if the
* connection string contains `DefaultEndpointsProtocol` and `EndpointSuffix` it will set the {@link
*
*
* @param connectionString Connection string of the storage account.
* @return the updated BlobContainerClientBuilder
* @throws IllegalArgumentException If {@code connectionString} doesn't contain `AccountName` or `AccountKey`.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public BlobContainerClientBuilder connectionString(String connectionString) {
BuilderHelper.configureConnectionString(connectionString, (accountName) -> this.accountName = accountName,
this::credential, this::endpoint, logger);
return this;
}
/**
* Sets the name of the container.
*
* @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root},
* will be used.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder containerName(String containerName) {
this.containerName = containerName;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent.
*
* @param pipelinePolicy a pipeline policy
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public BlobContainerClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public BlobContainerClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryOptions The options used to configure retry behavior.
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public BlobContainerClientBuilder retryOptions(RequestRetryOptions retryOptions) {
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
} |
Yes, this appears to have been release with the incorrect boolean check. | public BlobContainerClientBuilder endpoint(String endpoint) {
try {
URL url = new URL(endpoint);
BlobUrlParts parts = BlobUrlParts.parse(url);
this.endpoint = parts.getScheme() + ":
this.containerName = parts.getBlobContainerName();
String sasToken = parts.getSasQueryParameters().encode();
if (!ImplUtils.isNullOrEmpty(sasToken)) {
this.sasToken(sasToken);
}
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(
new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."));
}
return this;
} | if (!ImplUtils.isNullOrEmpty(sasToken)) { | public BlobContainerClientBuilder endpoint(String endpoint) {
try {
URL url = new URL(endpoint);
BlobUrlParts parts = BlobUrlParts.parse(url);
this.endpoint = parts.getScheme() + ":
this.containerName = parts.getBlobContainerName();
String sasToken = parts.getSasQueryParameters().encode();
if (!ImplUtils.isNullOrEmpty(sasToken)) {
this.sasToken(sasToken);
}
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(
new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."));
}
return this;
} | class BlobContainerClientBuilder {
private final ClientLogger logger = new ClientLogger(BlobContainerClientBuilder.class);
private String endpoint;
private String accountName;
private String containerName;
private CpkInfo customerProvidedKey;
private SharedKeyCredential sharedKeyCredential;
private TokenCredential tokenCredential;
private SasTokenCredential sasTokenCredential;
private HttpClient httpClient;
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private HttpLogOptions logOptions = new HttpLogOptions();
private RequestRetryOptions retryOptions = new RequestRetryOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
/**
* Creates a builder instance that is able to configure and construct {@link BlobContainerClient ContainerClients}
* and {@link BlobContainerAsyncClient ContainerAsyncClients}.
*/
public BlobContainerClientBuilder() {
}
/**
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.buildClient}
*
* @return a {@link BlobContainerClient} created from the configurations in this builder.
*/
public BlobContainerClient buildClient() {
return new BlobContainerClient(buildAsyncClient());
}
/**
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.buildAsyncClient}
*
* @return a {@link BlobContainerAsyncClient} created from the configurations in this builder.
*/
public BlobContainerAsyncClient buildAsyncClient() {
/*
Implicit and explicit root container access are functionally equivalent, but explicit references are easier
to read and debug.
*/
if (Objects.isNull(containerName) || containerName.isEmpty()) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(() -> {
if (sharedKeyCredential != null) {
return new SharedKeyCredentialPolicy(sharedKeyCredential);
} else if (tokenCredential != null) {
return new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint));
} else if (sasTokenCredential != null) {
return new SasTokenCredentialPolicy(sasTokenCredential);
} else {
return null;
}
}, retryOptions, logOptions, httpClient, additionalPolicies, configuration);
return new BlobContainerAsyncClient(new AzureBlobStorageBuilder()
.url(String.format("%s/%s", endpoint, containerName))
.pipeline(pipeline)
.build(), customerProvidedKey, accountName);
}
/**
* Sets the service endpoint, additionally parses it for information (SAS token, container name)
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.endpoint
*
* @param endpoint URL of the service
* @return the updated BlobContainerClientBuilder object
* @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL.
*/
/**
* Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server.
*
* @param customerProvidedKey Customer provided key containing the encryption key information.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) {
if (customerProvidedKey == null) {
this.customerProvidedKey = null;
} else {
this.customerProvidedKey = new CpkInfo()
.setEncryptionKey(customerProvidedKey.getKey())
.setEncryptionKeySha256(customerProvidedKey.getKeySHA256())
.setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm());
}
return this;
}
/**
* Sets the {@link SharedKeyCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public BlobContainerClientBuilder credential(SharedKeyCredential credential) {
this.sharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public BlobContainerClientBuilder credential(TokenCredential credential) {
this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.sharedKeyCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code sasToken} is {@code null}.
*/
public BlobContainerClientBuilder sasToken(String sasToken) {
this.sasTokenCredential = new SasTokenCredential(Objects.requireNonNull(sasToken,
"'sasToken' cannot be null."));
this.sharedKeyCredential = null;
this.tokenCredential = null;
return this;
}
/**
* Clears the credential used to authorize the request.
*
* <p>This is for containers that are publicly accessible.</p>
*
* @return the updated BlobContainerClientBuilder
*/
public BlobContainerClientBuilder setAnonymousAccess() {
this.sharedKeyCredential = null;
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Constructs a {@link SharedKeyCredential} used to authorize requests sent to the service. Additionally, if the
* connection string contains `DefaultEndpointsProtocol` and `EndpointSuffix` it will set the {@link
*
*
* @param connectionString Connection string of the storage account.
* @return the updated BlobContainerClientBuilder
* @throws IllegalArgumentException If {@code connectionString} doesn't contain `AccountName` or `AccountKey`.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public BlobContainerClientBuilder connectionString(String connectionString) {
BuilderHelper.configureConnectionString(connectionString, (accountName) -> this.accountName = accountName,
this::credential, this::endpoint, logger);
return this;
}
/**
* Sets the name of the container.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.Builder.containerName
*
* @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root},
* will be used.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder containerName(String containerName) {
this.containerName = containerName;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent.
*
* @param pipelinePolicy a pipeline policy
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public BlobContainerClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public BlobContainerClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryOptions The options used to configure retry behavior.
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public BlobContainerClientBuilder retryOptions(RequestRetryOptions retryOptions) {
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
} | class BlobContainerClientBuilder {
private final ClientLogger logger = new ClientLogger(BlobContainerClientBuilder.class);
private String endpoint;
private String accountName;
private String containerName;
private CpkInfo customerProvidedKey;
private SharedKeyCredential sharedKeyCredential;
private TokenCredential tokenCredential;
private SasTokenCredential sasTokenCredential;
private HttpClient httpClient;
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private HttpLogOptions logOptions = new HttpLogOptions();
private RequestRetryOptions retryOptions = new RequestRetryOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
/**
* Creates a builder instance that is able to configure and construct {@link BlobContainerClient ContainerClients}
* and {@link BlobContainerAsyncClient ContainerAsyncClients}.
*/
public BlobContainerClientBuilder() {
}
/**
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.buildClient}
*
* @return a {@link BlobContainerClient} created from the configurations in this builder.
*/
public BlobContainerClient buildClient() {
return new BlobContainerClient(buildAsyncClient());
}
/**
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.BlobContainerClientBuilder.buildAsyncClient}
*
* @return a {@link BlobContainerAsyncClient} created from the configurations in this builder.
*/
public BlobContainerAsyncClient buildAsyncClient() {
/*
Implicit and explicit root container access are functionally equivalent, but explicit references are easier
to read and debug.
*/
if (Objects.isNull(containerName) || containerName.isEmpty()) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(() -> {
if (sharedKeyCredential != null) {
return new SharedKeyCredentialPolicy(sharedKeyCredential);
} else if (tokenCredential != null) {
return new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint));
} else if (sasTokenCredential != null) {
return new SasTokenCredentialPolicy(sasTokenCredential);
} else {
return null;
}
}, retryOptions, logOptions, httpClient, additionalPolicies, configuration);
return new BlobContainerAsyncClient(new AzureBlobStorageBuilder()
.url(String.format("%s/%s", endpoint, containerName))
.pipeline(pipeline)
.build(), customerProvidedKey, accountName);
}
/**
* Sets the service endpoint, additionally parses it for information (SAS token, container name)
*
* @param endpoint URL of the service
* @return the updated BlobContainerClientBuilder object
* @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL.
*/
/**
* Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server.
*
* @param customerProvidedKey Customer provided key containing the encryption key information.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) {
if (customerProvidedKey == null) {
this.customerProvidedKey = null;
} else {
this.customerProvidedKey = new CpkInfo()
.setEncryptionKey(customerProvidedKey.getKey())
.setEncryptionKeySha256(customerProvidedKey.getKeySHA256())
.setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm());
}
return this;
}
/**
* Sets the {@link SharedKeyCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public BlobContainerClientBuilder credential(SharedKeyCredential credential) {
this.sharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public BlobContainerClientBuilder credential(TokenCredential credential) {
this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.sharedKeyCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
* @return the updated BlobContainerClientBuilder
* @throws NullPointerException If {@code sasToken} is {@code null}.
*/
public BlobContainerClientBuilder sasToken(String sasToken) {
this.sasTokenCredential = new SasTokenCredential(Objects.requireNonNull(sasToken,
"'sasToken' cannot be null."));
this.sharedKeyCredential = null;
this.tokenCredential = null;
return this;
}
/**
* Clears the credential used to authorize the request.
*
* <p>This is for containers that are publicly accessible.</p>
*
* @return the updated BlobContainerClientBuilder
*/
public BlobContainerClientBuilder setAnonymousAccess() {
this.sharedKeyCredential = null;
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Constructs a {@link SharedKeyCredential} used to authorize requests sent to the service. Additionally, if the
* connection string contains `DefaultEndpointsProtocol` and `EndpointSuffix` it will set the {@link
*
*
* @param connectionString Connection string of the storage account.
* @return the updated BlobContainerClientBuilder
* @throws IllegalArgumentException If {@code connectionString} doesn't contain `AccountName` or `AccountKey`.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public BlobContainerClientBuilder connectionString(String connectionString) {
BuilderHelper.configureConnectionString(connectionString, (accountName) -> this.accountName = accountName,
this::credential, this::endpoint, logger);
return this;
}
/**
* Sets the name of the container.
*
* @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root},
* will be used.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder containerName(String containerName) {
this.containerName = containerName;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent.
*
* @param pipelinePolicy a pipeline policy
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public BlobContainerClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public BlobContainerClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryOptions The options used to configure retry behavior.
* @return the updated BlobContainerClientBuilder object
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public BlobContainerClientBuilder retryOptions(RequestRetryOptions retryOptions) {
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobContainerClientBuilder object
*/
public BlobContainerClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
} |
These are only used once. Do we need variables for these two? | private AzureBlobStorageImpl constructImpl() {
Objects.requireNonNull(blobName, "'blobName' cannot be null.");
checkValidEncryptionParameters();
/*
Implicit and explicit root container access are functionally equivalent, but explicit references are easier
to read and debug.
*/
if (ImplUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
if (httpPipeline != null) {
return new AzureBlobStorageBuilder()
.url(String.format("%s/%s/%s", endpoint, containerName, blobName))
.pipeline(httpPipeline)
.build();
}
String userAgentName = BlobCryptographyConfiguration.NAME;
String userAgentVersion = BlobCryptographyConfiguration.VERSION;
Configuration userAgentConfiguration = (configuration == null) ? Configuration.NONE : configuration;
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(userAgentName, userAgentVersion, userAgentConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddDatePolicy());
if (sharedKeyCredential != null) {
policies.add(new SharedKeyCredentialPolicy(sharedKeyCredential));
} else if (tokenCredential != null) {
policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint)));
} else if (sasTokenCredential != null) {
policies.add(new SasTokenCredentialPolicy(sasTokenCredential));
}
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(new RequestRetryPolicy(retryOptions));
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new ResponseValidationPolicyBuilder()
.addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID)
.addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256)
.build());
policies.add(new HttpLoggingPolicy(logOptions));
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return new AzureBlobStorageBuilder()
.url(String.format("%s/%s/%s", endpoint, containerName, blobName))
.pipeline(pipeline)
.build();
} | String userAgentName = BlobCryptographyConfiguration.NAME; | private AzureBlobStorageImpl constructImpl() {
Objects.requireNonNull(blobName, "'blobName' cannot be null.");
checkValidEncryptionParameters();
/*
Implicit and explicit root container access are functionally equivalent, but explicit references are easier
to read and debug.
*/
if (ImplUtils.isNullOrEmpty(containerName)) {
containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME;
}
if (httpPipeline != null) {
return new AzureBlobStorageBuilder()
.url(String.format("%s/%s/%s", endpoint, containerName, blobName))
.pipeline(httpPipeline)
.build();
}
String userAgentName = BlobCryptographyConfiguration.NAME;
String userAgentVersion = BlobCryptographyConfiguration.VERSION;
Configuration userAgentConfiguration = (configuration == null) ? Configuration.NONE : configuration;
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(userAgentName, userAgentVersion, userAgentConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddDatePolicy());
if (sharedKeyCredential != null) {
policies.add(new SharedKeyCredentialPolicy(sharedKeyCredential));
} else if (tokenCredential != null) {
policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint)));
} else if (sasTokenCredential != null) {
policies.add(new SasTokenCredentialPolicy(sasTokenCredential));
}
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(new RequestRetryPolicy(retryOptions));
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new ResponseValidationPolicyBuilder()
.addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID)
.addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256)
.build());
policies.add(new HttpLoggingPolicy(logOptions));
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return new AzureBlobStorageBuilder()
.url(String.format("%s/%s/%s", endpoint, containerName, blobName))
.pipeline(pipeline)
.build();
} | class EncryptedBlobClientBuilder {
private final ClientLogger logger = new ClientLogger(EncryptedBlobClientBuilder.class);
private String endpoint;
private String accountName;
private String containerName;
private String blobName;
private String snapshot;
private SharedKeyCredential sharedKeyCredential;
private TokenCredential tokenCredential;
private SasTokenCredential sasTokenCredential;
private HttpClient httpClient;
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private HttpLogOptions logOptions = new HttpLogOptions();
private RequestRetryOptions retryOptions = new RequestRetryOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private AsyncKeyEncryptionKey keyWrapper;
private AsyncKeyEncryptionKeyResolver keyResolver;
private String keyWrapAlgorithm;
/**
* Creates a new instance of the EncryptedBlobClientBuilder
*/
public EncryptedBlobClientBuilder() {
}
/**
* Creates a {@link EncryptedBlobClient} based on options set in the Builder.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient}
*
* @return a {@link EncryptedBlobClient} created from the configurations in this builder.
* @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
*/
public EncryptedBlobClient buildEncryptedBlobClient() {
return new EncryptedBlobClient(buildEncryptedBlobAsyncClient());
}
/**
* Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient}
*
* @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder.
* @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
*/
public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() {
return new EncryptedBlobAsyncClient(constructImpl(), snapshot, accountName, keyWrapper, keyWrapAlgorithm);
}
protected void addOptionalEncryptionPolicy(List<HttpPipelinePolicy> policies) {
BlobDecryptionPolicy decryptionPolicy = new BlobDecryptionPolicy(keyWrapper, keyResolver);
policies.add(decryptionPolicy);
}
/**
* Sets the encryption key parameters for the client
*
* @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption
* key
* @param keyWrapAlgorithm The {@link String} used to wrap the key.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) {
this.keyWrapper = key;
this.keyWrapAlgorithm = keyWrapAlgorithm;
return this;
}
/**
* Sets the encryption parameters for this client
*
* @param keyResolver The key resolver used to select the correct key for decrypting existing blobs.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) {
this.keyResolver = keyResolver;
return this;
}
private void checkValidEncryptionParameters() {
if (this.keyWrapper == null && this.keyResolver == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null"));
}
if (this.keyWrapper != null && this.keyWrapAlgorithm == null) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Key Wrap Algorithm must be specified with a Key."));
}
}
/**
* Sets the {@link SharedKeyCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated EncryptedBlobClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public EncryptedBlobClientBuilder credential(SharedKeyCredential credential) {
this.sharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated EncryptedBlobClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public EncryptedBlobClientBuilder credential(TokenCredential credential) {
this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.sharedKeyCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
* @return the updated EncryptedBlobClientBuilder
* @throws NullPointerException If {@code sasToken} is {@code null}.
*/
public EncryptedBlobClientBuilder sasToken(String sasToken) {
this.sasTokenCredential = new SasTokenCredential(Objects.requireNonNull(sasToken,
"'sasToken' cannot be null."));
this.sharedKeyCredential = null;
this.tokenCredential = null;
return this;
}
/**
* Clears the credential used to authorize the request.
*
* <p>This is for blobs that are publicly accessible.</p>
*
* @return the updated EncryptedBlobClientBuilder
*/
public EncryptedBlobClientBuilder setAnonymousAccess() {
this.sharedKeyCredential = null;
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Constructs a {@link SharedKeyCredential} used to authorize requests sent to the service. Additionally, if the
* connection string contains `DefaultEndpointsProtocol` and `EndpointSuffix` it will set the {@link
*
*
* @param connectionString Connection string of the storage account.
* @return the updated EncryptedBlobClientBuilder
* @throws IllegalArgumentException If {@code connectionString} doesn't contain `AccountName` or `AccountKey`.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public EncryptedBlobClientBuilder connectionString(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Map<String, String> connectionStringPieces = Utility.parseConnectionString(connectionString);
String accountName = connectionStringPieces.get(Constants.ConnectionStringConstants.ACCOUNT_NAME);
String accountKey = connectionStringPieces.get(Constants.ConnectionStringConstants.ACCOUNT_KEY);
if (ImplUtils.isNullOrEmpty(accountName) || ImplUtils.isNullOrEmpty(accountKey)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'connectionString' must contain 'AccountName' and 'AccountKey'."));
}
String endpointProtocol = connectionStringPieces.get(Constants.ConnectionStringConstants.ENDPOINT_PROTOCOL);
String endpointSuffix = connectionStringPieces.get(Constants.ConnectionStringConstants.ENDPOINT_SUFFIX);
if (!ImplUtils.isNullOrEmpty(endpointProtocol) && !ImplUtils.isNullOrEmpty(endpointSuffix)) {
endpoint(String.format("%s:
endpointSuffix.replaceFirst("^\\.", "")));
}
this.accountName = accountName;
return credential(new SharedKeyCredential(accountName, accountKey));
}
/**
* Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name)
*
* <p>If the endpoint is to a blob in the root container, this method will fail as it will interpret the blob name
* as the container name. With only one path element, it is impossible to distinguish between a container name and a
* blob in the root container, so it is assumed to be the container name as this is much more common. When working
* with blobs in the root container, it is best to set the endpoint to the account url and specify the blob name
* separately using the {@link EncryptedBlobClientBuilder
*
* @param endpoint URL of the service
* @return the updated EncryptedBlobClientBuilder object
* @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL.
*/
public EncryptedBlobClientBuilder endpoint(String endpoint) {
try {
URL url = new URL(endpoint);
BlobUrlParts parts = BlobUrlParts.parse(url);
this.accountName = parts.getAccountName();
this.endpoint = parts.getScheme() + ":
this.containerName = parts.getBlobContainerName();
this.blobName = parts.getBlobName();
this.snapshot = parts.getSnapshot();
String sasToken = parts.getSasQueryParameters().encode();
if (!ImplUtils.isNullOrEmpty(sasToken)) {
this.sasToken(sasToken);
}
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(
new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."));
}
return this;
}
/**
* Sets the name of the container that contains the blob.
*
* @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root},
* will be used.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder containerName(String containerName) {
this.containerName = containerName;
return this;
}
/**
* Sets the name of the blob.
*
* @param blobName Name of the blob.
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code blobName} is {@code null}
*/
public EncryptedBlobClientBuilder blobName(String blobName) {
this.blobName = Objects.requireNonNull(blobName, "'blobName' cannot be null.");
return this;
}
/**
* Sets the snapshot identifier of the blob.
*
* @param snapshot Snapshot identifier for the blob.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder snapshot(String snapshot) {
this.snapshot = snapshot;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent.
*
* @param pipelinePolicy a pipeline policy
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public EncryptedBlobClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public EncryptedBlobClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryOptions The options used to configure retry behavior.
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public EncryptedBlobClientBuilder retryOptions(RequestRetryOptions retryOptions) {
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
} | class EncryptedBlobClientBuilder {
private final ClientLogger logger = new ClientLogger(EncryptedBlobClientBuilder.class);
private String endpoint;
private String accountName;
private String containerName;
private String blobName;
private String snapshot;
private SharedKeyCredential sharedKeyCredential;
private TokenCredential tokenCredential;
private SasTokenCredential sasTokenCredential;
private HttpClient httpClient;
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private HttpLogOptions logOptions = new HttpLogOptions();
private RequestRetryOptions retryOptions = new RequestRetryOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private AsyncKeyEncryptionKey keyWrapper;
private AsyncKeyEncryptionKeyResolver keyResolver;
private String keyWrapAlgorithm;
/**
* Creates a new instance of the EncryptedBlobClientBuilder
*/
public EncryptedBlobClientBuilder() {
}
/**
* Creates a {@link EncryptedBlobClient} based on options set in the Builder.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient}
*
* @return a {@link EncryptedBlobClient} created from the configurations in this builder.
* @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
*/
public EncryptedBlobClient buildEncryptedBlobClient() {
return new EncryptedBlobClient(buildEncryptedBlobAsyncClient());
}
/**
* Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient}
*
* @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder.
* @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
*/
public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() {
return new EncryptedBlobAsyncClient(constructImpl(), snapshot, accountName, keyWrapper, keyWrapAlgorithm);
}
protected void addOptionalEncryptionPolicy(List<HttpPipelinePolicy> policies) {
BlobDecryptionPolicy decryptionPolicy = new BlobDecryptionPolicy(keyWrapper, keyResolver);
policies.add(decryptionPolicy);
}
/**
* Sets the encryption key parameters for the client
*
* @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption
* key
* @param keyWrapAlgorithm The {@link String} used to wrap the key.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) {
this.keyWrapper = key;
this.keyWrapAlgorithm = keyWrapAlgorithm;
return this;
}
/**
* Sets the encryption parameters for this client
*
* @param keyResolver The key resolver used to select the correct key for decrypting existing blobs.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) {
this.keyResolver = keyResolver;
return this;
}
private void checkValidEncryptionParameters() {
if (this.keyWrapper == null && this.keyResolver == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null"));
}
if (this.keyWrapper != null && this.keyWrapAlgorithm == null) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Key Wrap Algorithm must be specified with a Key."));
}
}
/**
* Sets the {@link SharedKeyCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated EncryptedBlobClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public EncryptedBlobClientBuilder credential(SharedKeyCredential credential) {
this.sharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service.
*
* @param credential The credential to use for authenticating request.
* @return the updated EncryptedBlobClientBuilder
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public EncryptedBlobClientBuilder credential(TokenCredential credential) {
this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.sharedKeyCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
* @return the updated EncryptedBlobClientBuilder
* @throws NullPointerException If {@code sasToken} is {@code null}.
*/
public EncryptedBlobClientBuilder sasToken(String sasToken) {
this.sasTokenCredential = new SasTokenCredential(Objects.requireNonNull(sasToken,
"'sasToken' cannot be null."));
this.sharedKeyCredential = null;
this.tokenCredential = null;
return this;
}
/**
* Clears the credential used to authorize the request.
*
* <p>This is for blobs that are publicly accessible.</p>
*
* @return the updated EncryptedBlobClientBuilder
*/
public EncryptedBlobClientBuilder setAnonymousAccess() {
this.sharedKeyCredential = null;
this.tokenCredential = null;
this.sasTokenCredential = null;
return this;
}
/**
* Constructs a {@link SharedKeyCredential} used to authorize requests sent to the service. Additionally, if the
* connection string contains `DefaultEndpointsProtocol` and `EndpointSuffix` it will set the {@link
*
*
* @param connectionString Connection string of the storage account.
* @return the updated EncryptedBlobClientBuilder
* @throws IllegalArgumentException If {@code connectionString} doesn't contain `AccountName` or `AccountKey`.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public EncryptedBlobClientBuilder connectionString(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Map<String, String> connectionStringPieces = Utility.parseConnectionString(connectionString);
String accountName = connectionStringPieces.get(Constants.ConnectionStringConstants.ACCOUNT_NAME);
String accountKey = connectionStringPieces.get(Constants.ConnectionStringConstants.ACCOUNT_KEY);
if (ImplUtils.isNullOrEmpty(accountName) || ImplUtils.isNullOrEmpty(accountKey)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'connectionString' must contain 'AccountName' and 'AccountKey'."));
}
String endpointProtocol = connectionStringPieces.get(Constants.ConnectionStringConstants.ENDPOINT_PROTOCOL);
String endpointSuffix = connectionStringPieces.get(Constants.ConnectionStringConstants.ENDPOINT_SUFFIX);
if (!ImplUtils.isNullOrEmpty(endpointProtocol) && !ImplUtils.isNullOrEmpty(endpointSuffix)) {
endpoint(String.format("%s:
endpointSuffix.replaceFirst("^\\.", "")));
}
this.accountName = accountName;
return credential(new SharedKeyCredential(accountName, accountKey));
}
/**
* Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name)
*
* <p>If the endpoint is to a blob in the root container, this method will fail as it will interpret the blob name
* as the container name. With only one path element, it is impossible to distinguish between a container name and a
* blob in the root container, so it is assumed to be the container name as this is much more common. When working
* with blobs in the root container, it is best to set the endpoint to the account url and specify the blob name
* separately using the {@link EncryptedBlobClientBuilder
*
* @param endpoint URL of the service
* @return the updated EncryptedBlobClientBuilder object
* @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL.
*/
public EncryptedBlobClientBuilder endpoint(String endpoint) {
try {
URL url = new URL(endpoint);
BlobUrlParts parts = BlobUrlParts.parse(url);
this.accountName = parts.getAccountName();
this.endpoint = parts.getScheme() + ":
this.containerName = parts.getBlobContainerName();
this.blobName = parts.getBlobName();
this.snapshot = parts.getSnapshot();
String sasToken = parts.getSasQueryParameters().encode();
if (!ImplUtils.isNullOrEmpty(sasToken)) {
this.sasToken(sasToken);
}
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(
new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."));
}
return this;
}
/**
* Sets the name of the container that contains the blob.
*
* @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root},
* will be used.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder containerName(String containerName) {
this.containerName = containerName;
return this;
}
/**
* Sets the name of the blob.
*
* @param blobName Name of the blob.
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code blobName} is {@code null}
*/
public EncryptedBlobClientBuilder blobName(String blobName) {
this.blobName = Objects.requireNonNull(blobName, "'blobName' cannot be null.");
return this;
}
/**
* Sets the snapshot identifier of the blob.
*
* @param snapshot Snapshot identifier for the blob.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder snapshot(String snapshot) {
this.snapshot = snapshot;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent.
*
* @param pipelinePolicy a pipeline policy
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public EncryptedBlobClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public EncryptedBlobClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryOptions The options used to configure retry behavior.
* @return the updated EncryptedBlobClientBuilder object
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public EncryptedBlobClientBuilder retryOptions(RequestRetryOptions retryOptions) {
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated EncryptedBlobClientBuilder object
*/
public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
} |
This usecase ,user stop polling after N second. I think user is not calling `cancelOperation` . Should we remove the call to `cancelOperation()` here ? | public void subscribeToAllPollEventStopPollingAfterNSecondsTest() {
Duration pollInterval = Duration.ofSeconds(1);
Duration waitTime = Duration.ofSeconds(3);
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgress), Mono.just(inProgress), Mono.just(success));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation, null,
ignored -> new PollResponse<Response>(OperationStatus.USER_CANCELLED, null));
StepVerifier.create(poller.getObserver())
.expectNext(inProgress)
.then(() -> poller.setAutoPollingEnabled(false))
.expectNoEvent(waitTime)
.then(() -> poller.cancelOperation())
.verifyError();
Assert.assertEquals(OperationStatus.IN_PROGRESS, poller.getStatus());
Assert.assertFalse(poller.isAutoPollingEnabled());
} | .verifyError(); | public void subscribeToAllPollEventStopPollingAfterNSecondsTest() {
Duration pollInterval = Duration.ofSeconds(1);
Duration waitTime = Duration.ofSeconds(3);
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgress), Mono.just(inProgress), Mono.just(success));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation, null,
ignored -> new PollResponse<Response>(OperationStatus.USER_CANCELLED, null));
StepVerifier.create(poller.getObserver())
.expectNext(inProgress)
.then(() -> poller.setAutoPollingEnabled(false))
.expectNoEvent(waitTime)
.thenCancel()
.verify();
Assert.assertEquals(OperationStatus.IN_PROGRESS, poller.getStatus());
Assert.assertFalse(poller.isAutoPollingEnabled());
} | class PollerTests {
@Mock
private Function<PollResponse<Response>, Mono<PollResponse<Response>>> pollOperation;
@Mock
private Consumer<Poller<Response>> cancelOperation;
@Before
public void beforeTest() {
MockitoAnnotations.initMocks(this);
}
@After
public void afterTest() {
Mockito.framework().clearInlineMocks();
}
/* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate few in-progress response followed by few OTHER responses and finally successfully completed response.
* The sdk client will only subscribe for a specific OTHER response and final successful response.
**/
@Test
public void subscribeToSpecificOtherOperationStatusTest() {
final Duration retryAfter = Duration.ofMillis(100);
final Duration pollInterval = Duration.ofMillis(250);
final List<PollResponse<Response>> responses = new ArrayList<>();
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("0"), retryAfter));
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("1"), retryAfter));
responses.add(new PollResponse<>(OperationStatus.fromString("OTHER_1"), new Response("2")));
responses.add(new PollResponse<>(OperationStatus.fromString("OTHER_2"), new Response("3")));
responses.add(new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("4"), retryAfter));
when(pollOperation.apply(any())).thenReturn(
Mono.just(responses.get(0)),
Mono.just(responses.get(1)),
Mono.just(responses.get(2)),
Mono.just(responses.get(3)),
Mono.just(responses.get(4)));
final Poller<Response> pollerObserver = new Poller<>(pollInterval, pollOperation);
StepVerifier.create(pollerObserver.getObserver())
.expectNext(responses.get(0))
.expectNext(responses.get(1))
.expectNext(responses.get(2))
.expectNext(responses.get(3))
.expectNext(responses.get(4))
.verifyComplete();
Assert.assertEquals(pollerObserver.getStatus(), OperationStatus.SUCCESSFULLY_COMPLETED);
}
/* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate few in-progress response followed by few OTHER status responses and finally successfully completed response.
* The sdk client will block for a specific OTHER status.
**/
@Test
public void blockForCustomOperationStatusTest() {
final OperationStatus expected = OperationStatus.fromString("OTHER_2");
PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A"));
PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
PollResponse<Response> other1PollResponse = new PollResponse<>(OperationStatus.fromString("OTHER_1"), new Response("Starting : Cert A"));
PollResponse<Response> other2PollResponse = new PollResponse<>(expected, new Response("Starting : Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse),
Mono.just(inProgressPollResponse), Mono.just(other1PollResponse), Mono.just(other2PollResponse),
Mono.just(successPollResponse));
final Poller<Response> createCertPoller = new Poller<>(Duration.ofMillis(100), pollOperation);
final PollResponse<Response> pollResponse = createCertPoller.blockUntil(expected);
Assert.assertEquals(pollResponse.getStatus(), expected);
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate successful response returned
* after few in-progress response. But the sdk client will stop polling in between
* and activate polling in between. The client will miss few in progress response and
* subscriber will get get final successful response.
**/
@Ignore("When auto-subscription is turned off, the observer still polls. https:
@Test
public void subscribeToAllPollEventStopPollingAfterNSecondsAndRestartedTest() {
final PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A"), Duration.ofSeconds(1));
final PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
final Duration pollInterval = Duration.ofMillis(100);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse), Mono.just(successPollResponse));
final Poller<Response> poller = new Poller<>(pollInterval, pollOperation);
StepVerifier.create(poller.getObserver())
.expectNext(inProgressPollResponse)
.then(() -> poller.setAutoPollingEnabled(false))
.expectNoEvent(Duration.ofSeconds(3))
.then(() -> poller.setAutoPollingEnabled(true))
.expectNext(successPollResponse)
.verifyComplete();
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
}
/*
* The test is setup where user will disable auto polling after creating poller.
* The user will enable polling after LRO is expected to complete.
* We want to ensure that if user enable polling after LRO is complete, user can
* final polling status.
*/
@Test
public void disableAutoPollAndEnableAfterCompletionSuccessfullyDone() {
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting: Cert A"));
PollResponse<Response> initial = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("First: Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(initial), Mono.just(inProgress), Mono.just(success));
Poller<Response> poller = new Poller<>(Duration.ofSeconds(1), pollOperation);
poller.setAutoPollingEnabled(false);
StepVerifier.create(poller.getObserver())
.then(() -> poller.setAutoPollingEnabled(true))
.expectNext(inProgress)
.expectNext(success)
.verifyComplete();
Assert.assertSame(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
}
/*
* Test where SDK Client is subscribed all responses.
* The last response in this case will be OperationStatus.SUCCESSFULLY_COMPLETED
* This scenario is setup where source will generate successful response returned after few in-progress response.
**/
@Test
public void autoStartPollingAndSuccessfullyComplete() throws Exception {
PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
Duration pollInterval = Duration.ofSeconds(1);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse), Mono.just(successPollResponse));
Poller<Response> createCertPoller = new Poller<>(pollInterval, pollOperation);
while (createCertPoller.getStatus() != OperationStatus.SUCCESSFULLY_COMPLETED) {
Thread.sleep(pollInterval.toMillis());
}
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, createCertPoller.getStatus());
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate successful response returned
* after few in-progress response. But the sdk client will stop polling in between
* and subscriber should never get final successful response.
**/
@Ignore("https:
@Test
/**
* Test where SDK Client is subscribed all responses. This scenario is setup where source will generate successful
* response returned after few in-progress response. The sdk client will stop auto polling. It will subscribe and
* start receiving responses .The subscriber will get final successful response.
*/
@Test
public void stopAutoPollAndManualPoll() {
final List<PollResponse<Response>> responses = new ArrayList<>();
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A")));
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Middle: Cert A")));
responses.add(new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A")));
long totalTimeoutInMillis = 1000;
Duration pollInterval = Duration.ofMillis(totalTimeoutInMillis / 20);
when(pollOperation.apply(any())).thenReturn(Mono.just(responses.get(0)), Mono.just(responses.get(1)), Mono.just(responses.get(2)));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation);
poller.setAutoPollingEnabled(false);
int counter = 0;
while (poller.getStatus() != OperationStatus.SUCCESSFULLY_COMPLETED) {
counter++;
PollResponse<Response> pollResponse = poller.poll().block();
Assert.assertSame("Counter: " + counter + " did not match.", responses.get(counter), pollResponse);
}
Assert.assertSame(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertFalse(poller.isAutoPollingEnabled());
}
/**
* Test where SDK Client is subscribed all responses. This scenario is setup where source will generate user
* cancelled response returned after few in-progress response. The sdk client will wait for it to cancel get final
* USER_CANCELLED response.
*/
@Test
public void subscribeToAllPollEventCancelOperationTest() {
Duration pollInterval = Duration.ofMillis(500);
PollResponse<Response> cancellation = new PollResponse<>(OperationStatus.USER_CANCELLED, new Response("Created : Cert A"));
PollResponse<Response> first = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting: Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(first), Mono.just(cancellation));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation, null, cancelOperation);
StepVerifier.create(poller.getObserver())
.expectNext(first)
.then(() -> poller.cancelOperation())
.thenCancel()
.verify();
Assert.assertEquals(OperationStatus.USER_CANCELLED, poller.block().getStatus());
Assert.assertEquals(OperationStatus.USER_CANCELLED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
verify(cancelOperation, Mockito.times(1)).accept(poller);
}
public static class Response {
private final String response;
public Response(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
@Override
public String toString() {
return "Response: " + response;
}
}
} | class PollerTests {
@Mock
private Function<PollResponse<Response>, Mono<PollResponse<Response>>> pollOperation;
@Mock
private Consumer<Poller<Response>> cancelOperation;
@Before
public void beforeTest() {
MockitoAnnotations.initMocks(this);
}
@After
public void afterTest() {
Mockito.framework().clearInlineMocks();
}
/**
* Verify we cannot pass in poll duration of {@link Duration
*/
@Test(expected = IllegalArgumentException.class)
public void constructorPollIntervalZero() {
new Poller<>(Duration.ZERO, pollOperation, () -> Mono.just(new Response("Foo")), cancelOperation);
}
/**
* Verify we cannot pass in poll negative duration.
*/
@Test(expected = IllegalArgumentException.class)
public void constructorPollIntervalNegative() {
new Poller<>(Duration.ofSeconds(-1), pollOperation, () -> Mono.just(new Response("Foo")), cancelOperation);
}
/**
* Verify we cannot pass in null pollInterval.
*/
@Test(expected = NullPointerException.class)
public void constructorPollIntervalNull() {
new Poller<>(null, pollOperation, () -> Mono.just(new Response("Foo")), cancelOperation);
}
/**
* Verify we cannot pass in null pollInterval.
*/
@Test(expected = NullPointerException.class)
public void constructorPollOperationNull() {
new Poller<>(Duration.ofSeconds(1), null, () -> Mono.just(new Response("Foo")), cancelOperation);
}
/**
* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate few in-progress response followed by few OTHER responses and finally successfully completed response.
* The sdk client will only subscribe for a specific OTHER response and final successful response.
*/
@Test
public void subscribeToSpecificOtherOperationStatusTest() {
final Duration retryAfter = Duration.ofMillis(100);
final Duration pollInterval = Duration.ofMillis(250);
final List<PollResponse<Response>> responses = new ArrayList<>();
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("0"), retryAfter));
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("1"), retryAfter));
responses.add(new PollResponse<>(OperationStatus.fromString("OTHER_1"), new Response("2")));
responses.add(new PollResponse<>(OperationStatus.fromString("OTHER_2"), new Response("3")));
responses.add(new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("4"), retryAfter));
when(pollOperation.apply(any())).thenReturn(
Mono.just(responses.get(0)),
Mono.just(responses.get(1)),
Mono.just(responses.get(2)),
Mono.just(responses.get(3)),
Mono.just(responses.get(4)));
final Poller<Response> pollerObserver = new Poller<>(pollInterval, pollOperation);
StepVerifier.create(pollerObserver.getObserver())
.expectNext(responses.get(0))
.expectNext(responses.get(1))
.expectNext(responses.get(2))
.expectNext(responses.get(3))
.expectNext(responses.get(4))
.verifyComplete();
Assert.assertEquals(pollerObserver.getStatus(), OperationStatus.SUCCESSFULLY_COMPLETED);
}
/**
* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate few in-progress response followed by few OTHER status responses and finally successfully completed response.
* The sdk client will block for a specific OTHER status.
*/
@Test
public void blockForCustomOperationStatusTest() {
final OperationStatus expected = OperationStatus.fromString("OTHER_2");
PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A"));
PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
PollResponse<Response> other1PollResponse = new PollResponse<>(OperationStatus.fromString("OTHER_1"), new Response("Starting : Cert A"));
PollResponse<Response> other2PollResponse = new PollResponse<>(expected, new Response("Starting : Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse),
Mono.just(inProgressPollResponse), Mono.just(other1PollResponse), Mono.just(other2PollResponse),
Mono.just(successPollResponse));
final Poller<Response> createCertPoller = new Poller<>(Duration.ofMillis(100), pollOperation);
final PollResponse<Response> pollResponse = createCertPoller.blockUntil(expected);
Assert.assertEquals(pollResponse.getStatus(), expected);
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/**
* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate successful response returned
* after few in-progress response. But the sdk client will stop polling in between
* and activate polling in between. The client will miss few in progress response and
* subscriber will get get final successful response.
*/
@Ignore("When auto-subscription is turned off, the observer still polls. https:
@Test
public void subscribeToAllPollEventStopPollingAfterNSecondsAndRestartedTest() {
final PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A"), Duration.ofSeconds(1));
final PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
final Duration pollInterval = Duration.ofMillis(100);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse), Mono.just(successPollResponse));
final Poller<Response> poller = new Poller<>(pollInterval, pollOperation);
StepVerifier.create(poller.getObserver())
.expectNext(inProgressPollResponse)
.then(() -> poller.setAutoPollingEnabled(false))
.expectNoEvent(Duration.ofSeconds(3))
.then(() -> poller.setAutoPollingEnabled(true))
.expectNext(successPollResponse)
.verifyComplete();
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
}
/*
* The test is setup where user will disable auto polling after creating poller.
* The user will enable polling after LRO is expected to complete.
* We want to ensure that if user enable polling after LRO is complete, user can
* final polling status.
*/
@Test
public void disableAutoPollAndEnableAfterCompletionSuccessfullyDone() {
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting: Cert A"));
PollResponse<Response> initial = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("First: Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(initial), Mono.just(inProgress), Mono.just(success));
Poller<Response> poller = new Poller<>(Duration.ofSeconds(1), pollOperation);
poller.setAutoPollingEnabled(false);
StepVerifier.create(poller.getObserver())
.then(() -> poller.setAutoPollingEnabled(true))
.expectNext(inProgress)
.expectNext(success)
.verifyComplete();
Assert.assertSame(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
}
/*
* Test where SDK Client is subscribed all responses.
* The last response in this case will be OperationStatus.SUCCESSFULLY_COMPLETED
* This scenario is setup where source will generate successful response returned after few in-progress response.
**/
@Test
public void autoStartPollingAndSuccessfullyComplete() throws Exception {
PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
Duration pollInterval = Duration.ofSeconds(1);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse), Mono.just(successPollResponse));
Poller<Response> createCertPoller = new Poller<>(pollInterval, pollOperation);
while (createCertPoller.getStatus() != OperationStatus.SUCCESSFULLY_COMPLETED) {
Thread.sleep(pollInterval.toMillis());
}
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, createCertPoller.getStatus());
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/** Test where SDK Client is subscribed to only final/last response.
* The last response in this case will be PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED
* This scenario is setup where source will generate successful response returned after few in progress response.
* But the subscriber is only interested in last response, The test will ensure subscriber
* only gets last PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED.
*/
@Test
public void subscribeToOnlyFinalEventSuccessfullyCompleteInNSecondsTest() {
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
Duration pollInterval = Duration.ofMillis(500);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgress), Mono.just(success));
Poller<Response> createCertPoller = new Poller<>(pollInterval, pollOperation);
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, createCertPoller.block().getStatus());
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, createCertPoller.getStatus());
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/**
* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate successful response returned
* after few in-progress response. But the sdk client will stop polling in between
* and subscriber should never get final successful response.
*/
@Ignore("https:
@Test
/**
* Test where SDK Client is subscribed all responses. This scenario is setup where source will generate successful
* response returned after few in-progress response. The sdk client will stop auto polling. It will subscribe and
* start receiving responses .The subscriber will get final successful response.
*/
@Test
public void stopAutoPollAndManualPoll() {
final List<PollResponse<Response>> responses = new ArrayList<>();
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A")));
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Middle: Cert A")));
responses.add(new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A")));
long totalTimeoutInMillis = 1000;
Duration pollInterval = Duration.ofMillis(totalTimeoutInMillis / 20);
when(pollOperation.apply(any())).thenReturn(Mono.just(responses.get(0)), Mono.just(responses.get(1)), Mono.just(responses.get(2)));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation);
poller.setAutoPollingEnabled(false);
int counter = 0;
while (poller.getStatus() != OperationStatus.SUCCESSFULLY_COMPLETED) {
counter++;
PollResponse<Response> pollResponse = poller.poll().block();
Assert.assertSame("Counter: " + counter + " did not match.", responses.get(counter), pollResponse);
}
Assert.assertSame(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertFalse(poller.isAutoPollingEnabled());
}
/**
* Test where SDK Client is subscribed all responses. This scenario is setup where source will generate user
* cancelled response returned after few in-progress response. The sdk client will wait for it to cancel get final
* USER_CANCELLED response.
*/
@Test
public void subscribeToAllPollEventCancelOperationTest() {
Duration pollInterval = Duration.ofMillis(500);
PollResponse<Response> cancellation = new PollResponse<>(OperationStatus.USER_CANCELLED, new Response("Created : Cert A"));
PollResponse<Response> first = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting: Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(first), Mono.just(cancellation));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation, null, cancelOperation);
StepVerifier.create(poller.getObserver())
.expectNext(first)
.then(() -> poller.cancelOperation())
.thenCancel()
.verify();
Assert.assertEquals(OperationStatus.USER_CANCELLED, poller.block().getStatus());
Assert.assertEquals(OperationStatus.USER_CANCELLED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
verify(cancelOperation, Mockito.times(1)).accept(poller);
}
public static class Response {
private final String response;
public Response(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
@Override
public String toString() {
return "Response: " + response;
}
}
} |
Fixed. | public void subscribeToAllPollEventStopPollingAfterNSecondsTest() {
Duration pollInterval = Duration.ofSeconds(1);
Duration waitTime = Duration.ofSeconds(3);
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgress), Mono.just(inProgress), Mono.just(success));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation, null,
ignored -> new PollResponse<Response>(OperationStatus.USER_CANCELLED, null));
StepVerifier.create(poller.getObserver())
.expectNext(inProgress)
.then(() -> poller.setAutoPollingEnabled(false))
.expectNoEvent(waitTime)
.then(() -> poller.cancelOperation())
.verifyError();
Assert.assertEquals(OperationStatus.IN_PROGRESS, poller.getStatus());
Assert.assertFalse(poller.isAutoPollingEnabled());
} | .verifyError(); | public void subscribeToAllPollEventStopPollingAfterNSecondsTest() {
Duration pollInterval = Duration.ofSeconds(1);
Duration waitTime = Duration.ofSeconds(3);
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgress), Mono.just(inProgress), Mono.just(success));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation, null,
ignored -> new PollResponse<Response>(OperationStatus.USER_CANCELLED, null));
StepVerifier.create(poller.getObserver())
.expectNext(inProgress)
.then(() -> poller.setAutoPollingEnabled(false))
.expectNoEvent(waitTime)
.thenCancel()
.verify();
Assert.assertEquals(OperationStatus.IN_PROGRESS, poller.getStatus());
Assert.assertFalse(poller.isAutoPollingEnabled());
} | class PollerTests {
@Mock
private Function<PollResponse<Response>, Mono<PollResponse<Response>>> pollOperation;
@Mock
private Consumer<Poller<Response>> cancelOperation;
@Before
public void beforeTest() {
MockitoAnnotations.initMocks(this);
}
@After
public void afterTest() {
Mockito.framework().clearInlineMocks();
}
/* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate few in-progress response followed by few OTHER responses and finally successfully completed response.
* The sdk client will only subscribe for a specific OTHER response and final successful response.
**/
@Test
public void subscribeToSpecificOtherOperationStatusTest() {
final Duration retryAfter = Duration.ofMillis(100);
final Duration pollInterval = Duration.ofMillis(250);
final List<PollResponse<Response>> responses = new ArrayList<>();
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("0"), retryAfter));
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("1"), retryAfter));
responses.add(new PollResponse<>(OperationStatus.fromString("OTHER_1"), new Response("2")));
responses.add(new PollResponse<>(OperationStatus.fromString("OTHER_2"), new Response("3")));
responses.add(new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("4"), retryAfter));
when(pollOperation.apply(any())).thenReturn(
Mono.just(responses.get(0)),
Mono.just(responses.get(1)),
Mono.just(responses.get(2)),
Mono.just(responses.get(3)),
Mono.just(responses.get(4)));
final Poller<Response> pollerObserver = new Poller<>(pollInterval, pollOperation);
StepVerifier.create(pollerObserver.getObserver())
.expectNext(responses.get(0))
.expectNext(responses.get(1))
.expectNext(responses.get(2))
.expectNext(responses.get(3))
.expectNext(responses.get(4))
.verifyComplete();
Assert.assertEquals(pollerObserver.getStatus(), OperationStatus.SUCCESSFULLY_COMPLETED);
}
/* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate few in-progress response followed by few OTHER status responses and finally successfully completed response.
* The sdk client will block for a specific OTHER status.
**/
@Test
public void blockForCustomOperationStatusTest() {
final OperationStatus expected = OperationStatus.fromString("OTHER_2");
PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A"));
PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
PollResponse<Response> other1PollResponse = new PollResponse<>(OperationStatus.fromString("OTHER_1"), new Response("Starting : Cert A"));
PollResponse<Response> other2PollResponse = new PollResponse<>(expected, new Response("Starting : Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse),
Mono.just(inProgressPollResponse), Mono.just(other1PollResponse), Mono.just(other2PollResponse),
Mono.just(successPollResponse));
final Poller<Response> createCertPoller = new Poller<>(Duration.ofMillis(100), pollOperation);
final PollResponse<Response> pollResponse = createCertPoller.blockUntil(expected);
Assert.assertEquals(pollResponse.getStatus(), expected);
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate successful response returned
* after few in-progress response. But the sdk client will stop polling in between
* and activate polling in between. The client will miss few in progress response and
* subscriber will get get final successful response.
**/
@Ignore("When auto-subscription is turned off, the observer still polls. https:
@Test
public void subscribeToAllPollEventStopPollingAfterNSecondsAndRestartedTest() {
final PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A"), Duration.ofSeconds(1));
final PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
final Duration pollInterval = Duration.ofMillis(100);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse), Mono.just(successPollResponse));
final Poller<Response> poller = new Poller<>(pollInterval, pollOperation);
StepVerifier.create(poller.getObserver())
.expectNext(inProgressPollResponse)
.then(() -> poller.setAutoPollingEnabled(false))
.expectNoEvent(Duration.ofSeconds(3))
.then(() -> poller.setAutoPollingEnabled(true))
.expectNext(successPollResponse)
.verifyComplete();
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
}
/*
* The test is setup where user will disable auto polling after creating poller.
* The user will enable polling after LRO is expected to complete.
* We want to ensure that if user enable polling after LRO is complete, user can
* final polling status.
*/
@Test
public void disableAutoPollAndEnableAfterCompletionSuccessfullyDone() {
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting: Cert A"));
PollResponse<Response> initial = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("First: Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(initial), Mono.just(inProgress), Mono.just(success));
Poller<Response> poller = new Poller<>(Duration.ofSeconds(1), pollOperation);
poller.setAutoPollingEnabled(false);
StepVerifier.create(poller.getObserver())
.then(() -> poller.setAutoPollingEnabled(true))
.expectNext(inProgress)
.expectNext(success)
.verifyComplete();
Assert.assertSame(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
}
/*
* Test where SDK Client is subscribed all responses.
* The last response in this case will be OperationStatus.SUCCESSFULLY_COMPLETED
* This scenario is setup where source will generate successful response returned after few in-progress response.
**/
@Test
public void autoStartPollingAndSuccessfullyComplete() throws Exception {
PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
Duration pollInterval = Duration.ofSeconds(1);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse), Mono.just(successPollResponse));
Poller<Response> createCertPoller = new Poller<>(pollInterval, pollOperation);
while (createCertPoller.getStatus() != OperationStatus.SUCCESSFULLY_COMPLETED) {
Thread.sleep(pollInterval.toMillis());
}
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, createCertPoller.getStatus());
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate successful response returned
* after few in-progress response. But the sdk client will stop polling in between
* and subscriber should never get final successful response.
**/
@Ignore("https:
@Test
/**
* Test where SDK Client is subscribed all responses. This scenario is setup where source will generate successful
* response returned after few in-progress response. The sdk client will stop auto polling. It will subscribe and
* start receiving responses .The subscriber will get final successful response.
*/
@Test
public void stopAutoPollAndManualPoll() {
final List<PollResponse<Response>> responses = new ArrayList<>();
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A")));
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Middle: Cert A")));
responses.add(new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A")));
long totalTimeoutInMillis = 1000;
Duration pollInterval = Duration.ofMillis(totalTimeoutInMillis / 20);
when(pollOperation.apply(any())).thenReturn(Mono.just(responses.get(0)), Mono.just(responses.get(1)), Mono.just(responses.get(2)));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation);
poller.setAutoPollingEnabled(false);
int counter = 0;
while (poller.getStatus() != OperationStatus.SUCCESSFULLY_COMPLETED) {
counter++;
PollResponse<Response> pollResponse = poller.poll().block();
Assert.assertSame("Counter: " + counter + " did not match.", responses.get(counter), pollResponse);
}
Assert.assertSame(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertFalse(poller.isAutoPollingEnabled());
}
/**
* Test where SDK Client is subscribed all responses. This scenario is setup where source will generate user
* cancelled response returned after few in-progress response. The sdk client will wait for it to cancel get final
* USER_CANCELLED response.
*/
@Test
public void subscribeToAllPollEventCancelOperationTest() {
Duration pollInterval = Duration.ofMillis(500);
PollResponse<Response> cancellation = new PollResponse<>(OperationStatus.USER_CANCELLED, new Response("Created : Cert A"));
PollResponse<Response> first = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting: Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(first), Mono.just(cancellation));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation, null, cancelOperation);
StepVerifier.create(poller.getObserver())
.expectNext(first)
.then(() -> poller.cancelOperation())
.thenCancel()
.verify();
Assert.assertEquals(OperationStatus.USER_CANCELLED, poller.block().getStatus());
Assert.assertEquals(OperationStatus.USER_CANCELLED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
verify(cancelOperation, Mockito.times(1)).accept(poller);
}
public static class Response {
private final String response;
public Response(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
@Override
public String toString() {
return "Response: " + response;
}
}
} | class PollerTests {
@Mock
private Function<PollResponse<Response>, Mono<PollResponse<Response>>> pollOperation;
@Mock
private Consumer<Poller<Response>> cancelOperation;
@Before
public void beforeTest() {
MockitoAnnotations.initMocks(this);
}
@After
public void afterTest() {
Mockito.framework().clearInlineMocks();
}
/**
* Verify we cannot pass in poll duration of {@link Duration
*/
@Test(expected = IllegalArgumentException.class)
public void constructorPollIntervalZero() {
new Poller<>(Duration.ZERO, pollOperation, () -> Mono.just(new Response("Foo")), cancelOperation);
}
/**
* Verify we cannot pass in poll negative duration.
*/
@Test(expected = IllegalArgumentException.class)
public void constructorPollIntervalNegative() {
new Poller<>(Duration.ofSeconds(-1), pollOperation, () -> Mono.just(new Response("Foo")), cancelOperation);
}
/**
* Verify we cannot pass in null pollInterval.
*/
@Test(expected = NullPointerException.class)
public void constructorPollIntervalNull() {
new Poller<>(null, pollOperation, () -> Mono.just(new Response("Foo")), cancelOperation);
}
/**
* Verify we cannot pass in null pollInterval.
*/
@Test(expected = NullPointerException.class)
public void constructorPollOperationNull() {
new Poller<>(Duration.ofSeconds(1), null, () -> Mono.just(new Response("Foo")), cancelOperation);
}
/**
* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate few in-progress response followed by few OTHER responses and finally successfully completed response.
* The sdk client will only subscribe for a specific OTHER response and final successful response.
*/
@Test
public void subscribeToSpecificOtherOperationStatusTest() {
final Duration retryAfter = Duration.ofMillis(100);
final Duration pollInterval = Duration.ofMillis(250);
final List<PollResponse<Response>> responses = new ArrayList<>();
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("0"), retryAfter));
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("1"), retryAfter));
responses.add(new PollResponse<>(OperationStatus.fromString("OTHER_1"), new Response("2")));
responses.add(new PollResponse<>(OperationStatus.fromString("OTHER_2"), new Response("3")));
responses.add(new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("4"), retryAfter));
when(pollOperation.apply(any())).thenReturn(
Mono.just(responses.get(0)),
Mono.just(responses.get(1)),
Mono.just(responses.get(2)),
Mono.just(responses.get(3)),
Mono.just(responses.get(4)));
final Poller<Response> pollerObserver = new Poller<>(pollInterval, pollOperation);
StepVerifier.create(pollerObserver.getObserver())
.expectNext(responses.get(0))
.expectNext(responses.get(1))
.expectNext(responses.get(2))
.expectNext(responses.get(3))
.expectNext(responses.get(4))
.verifyComplete();
Assert.assertEquals(pollerObserver.getStatus(), OperationStatus.SUCCESSFULLY_COMPLETED);
}
/**
* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate few in-progress response followed by few OTHER status responses and finally successfully completed response.
* The sdk client will block for a specific OTHER status.
*/
@Test
public void blockForCustomOperationStatusTest() {
final OperationStatus expected = OperationStatus.fromString("OTHER_2");
PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A"));
PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
PollResponse<Response> other1PollResponse = new PollResponse<>(OperationStatus.fromString("OTHER_1"), new Response("Starting : Cert A"));
PollResponse<Response> other2PollResponse = new PollResponse<>(expected, new Response("Starting : Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse),
Mono.just(inProgressPollResponse), Mono.just(other1PollResponse), Mono.just(other2PollResponse),
Mono.just(successPollResponse));
final Poller<Response> createCertPoller = new Poller<>(Duration.ofMillis(100), pollOperation);
final PollResponse<Response> pollResponse = createCertPoller.blockUntil(expected);
Assert.assertEquals(pollResponse.getStatus(), expected);
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/**
* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate successful response returned
* after few in-progress response. But the sdk client will stop polling in between
* and activate polling in between. The client will miss few in progress response and
* subscriber will get get final successful response.
*/
@Ignore("When auto-subscription is turned off, the observer still polls. https:
@Test
public void subscribeToAllPollEventStopPollingAfterNSecondsAndRestartedTest() {
final PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A"), Duration.ofSeconds(1));
final PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
final Duration pollInterval = Duration.ofMillis(100);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse), Mono.just(successPollResponse));
final Poller<Response> poller = new Poller<>(pollInterval, pollOperation);
StepVerifier.create(poller.getObserver())
.expectNext(inProgressPollResponse)
.then(() -> poller.setAutoPollingEnabled(false))
.expectNoEvent(Duration.ofSeconds(3))
.then(() -> poller.setAutoPollingEnabled(true))
.expectNext(successPollResponse)
.verifyComplete();
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
}
/*
* The test is setup where user will disable auto polling after creating poller.
* The user will enable polling after LRO is expected to complete.
* We want to ensure that if user enable polling after LRO is complete, user can
* final polling status.
*/
@Test
public void disableAutoPollAndEnableAfterCompletionSuccessfullyDone() {
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting: Cert A"));
PollResponse<Response> initial = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("First: Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(initial), Mono.just(inProgress), Mono.just(success));
Poller<Response> poller = new Poller<>(Duration.ofSeconds(1), pollOperation);
poller.setAutoPollingEnabled(false);
StepVerifier.create(poller.getObserver())
.then(() -> poller.setAutoPollingEnabled(true))
.expectNext(inProgress)
.expectNext(success)
.verifyComplete();
Assert.assertSame(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
}
/*
* Test where SDK Client is subscribed all responses.
* The last response in this case will be OperationStatus.SUCCESSFULLY_COMPLETED
* This scenario is setup where source will generate successful response returned after few in-progress response.
**/
@Test
public void autoStartPollingAndSuccessfullyComplete() throws Exception {
PollResponse<Response> successPollResponse = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgressPollResponse = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
Duration pollInterval = Duration.ofSeconds(1);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgressPollResponse), Mono.just(successPollResponse));
Poller<Response> createCertPoller = new Poller<>(pollInterval, pollOperation);
while (createCertPoller.getStatus() != OperationStatus.SUCCESSFULLY_COMPLETED) {
Thread.sleep(pollInterval.toMillis());
}
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, createCertPoller.getStatus());
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/** Test where SDK Client is subscribed to only final/last response.
* The last response in this case will be PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED
* This scenario is setup where source will generate successful response returned after few in progress response.
* But the subscriber is only interested in last response, The test will ensure subscriber
* only gets last PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED.
*/
@Test
public void subscribeToOnlyFinalEventSuccessfullyCompleteInNSecondsTest() {
PollResponse<Response> success = new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created: Cert A"));
PollResponse<Response> inProgress = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A"));
Duration pollInterval = Duration.ofMillis(500);
when(pollOperation.apply(any())).thenReturn(Mono.just(inProgress), Mono.just(success));
Poller<Response> createCertPoller = new Poller<>(pollInterval, pollOperation);
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, createCertPoller.block().getStatus());
Assert.assertEquals(OperationStatus.SUCCESSFULLY_COMPLETED, createCertPoller.getStatus());
Assert.assertTrue(createCertPoller.isAutoPollingEnabled());
}
/**
* Test where SDK Client is subscribed all responses.
* This scenario is setup where source will generate successful response returned
* after few in-progress response. But the sdk client will stop polling in between
* and subscriber should never get final successful response.
*/
@Ignore("https:
@Test
/**
* Test where SDK Client is subscribed all responses. This scenario is setup where source will generate successful
* response returned after few in-progress response. The sdk client will stop auto polling. It will subscribe and
* start receiving responses .The subscriber will get final successful response.
*/
@Test
public void stopAutoPollAndManualPoll() {
final List<PollResponse<Response>> responses = new ArrayList<>();
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting : Cert A")));
responses.add(new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Middle: Cert A")));
responses.add(new PollResponse<>(OperationStatus.SUCCESSFULLY_COMPLETED, new Response("Created : Cert A")));
long totalTimeoutInMillis = 1000;
Duration pollInterval = Duration.ofMillis(totalTimeoutInMillis / 20);
when(pollOperation.apply(any())).thenReturn(Mono.just(responses.get(0)), Mono.just(responses.get(1)), Mono.just(responses.get(2)));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation);
poller.setAutoPollingEnabled(false);
int counter = 0;
while (poller.getStatus() != OperationStatus.SUCCESSFULLY_COMPLETED) {
counter++;
PollResponse<Response> pollResponse = poller.poll().block();
Assert.assertSame("Counter: " + counter + " did not match.", responses.get(counter), pollResponse);
}
Assert.assertSame(OperationStatus.SUCCESSFULLY_COMPLETED, poller.getStatus());
Assert.assertFalse(poller.isAutoPollingEnabled());
}
/**
* Test where SDK Client is subscribed all responses. This scenario is setup where source will generate user
* cancelled response returned after few in-progress response. The sdk client will wait for it to cancel get final
* USER_CANCELLED response.
*/
@Test
public void subscribeToAllPollEventCancelOperationTest() {
Duration pollInterval = Duration.ofMillis(500);
PollResponse<Response> cancellation = new PollResponse<>(OperationStatus.USER_CANCELLED, new Response("Created : Cert A"));
PollResponse<Response> first = new PollResponse<>(OperationStatus.IN_PROGRESS, new Response("Starting: Cert A"));
when(pollOperation.apply(any())).thenReturn(Mono.just(first), Mono.just(cancellation));
Poller<Response> poller = new Poller<>(pollInterval, pollOperation, null, cancelOperation);
StepVerifier.create(poller.getObserver())
.expectNext(first)
.then(() -> poller.cancelOperation())
.thenCancel()
.verify();
Assert.assertEquals(OperationStatus.USER_CANCELLED, poller.block().getStatus());
Assert.assertEquals(OperationStatus.USER_CANCELLED, poller.getStatus());
Assert.assertTrue(poller.isAutoPollingEnabled());
verify(cancelOperation, Mockito.times(1)).accept(poller);
}
public static class Response {
private final String response;
public Response(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
@Override
public String toString() {
return "Response: " + response;
}
}
} |
Null check? | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
status.completed = isComplete;
return status;
} | OperationStatus status = fromString(name, OperationStatus.class); | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
if (operationStatusMap != null && operationStatusMap.containsKey(name)) {
OperationStatus operationStatus = operationStatusMap.get(name);
if (operationStatus.isComplete() != isComplete) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for operation"
+ "status %s", isComplete, name));
}
}
status.completed = isComplete;
}
return status;
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
private static Map<String, OperationStatus> operationStatusMap;
static {
Map<String, OperationStatus> opStatusMap = new HashMap<>();
opStatusMap.put(NOT_STARTED.toString(), NOT_STARTED);
opStatusMap.put(IN_PROGRESS.toString(), IN_PROGRESS);
opStatusMap.put(SUCCESSFULLY_COMPLETED.toString(), SUCCESSFULLY_COMPLETED);
opStatusMap.put(FAILED.toString(), FAILED);
opStatusMap.put(USER_CANCELLED.toString(), USER_CANCELLED);
operationStatusMap = Collections.unmodifiableMap(opStatusMap);
}
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if {@code name} matches a pre-configured {@link OperationStatus} but
* {@code isComplete} doesn't match its pre-configured complete status.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} |
nit: double space. | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
status.completed = isComplete;
return status;
} | OperationStatus status = fromString(name, OperationStatus.class); | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
if (operationStatusMap != null && operationStatusMap.containsKey(name)) {
OperationStatus operationStatus = operationStatusMap.get(name);
if (operationStatus.isComplete() != isComplete) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for operation"
+ "status %s", isComplete, name));
}
}
status.completed = isComplete;
}
return status;
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
private static Map<String, OperationStatus> operationStatusMap;
static {
Map<String, OperationStatus> opStatusMap = new HashMap<>();
opStatusMap.put(NOT_STARTED.toString(), NOT_STARTED);
opStatusMap.put(IN_PROGRESS.toString(), IN_PROGRESS);
opStatusMap.put(SUCCESSFULLY_COMPLETED.toString(), SUCCESSFULLY_COMPLETED);
opStatusMap.put(FAILED.toString(), FAILED);
opStatusMap.put(USER_CANCELLED.toString(), USER_CANCELLED);
operationStatusMap = Collections.unmodifiableMap(opStatusMap);
}
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if {@code name} matches a pre-configured {@link OperationStatus} but
* {@code isComplete} doesn't match its pre-configured complete status.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} |
What if cancelOepration throws an exception? | public Mono<T> cancelOperation() throws UnsupportedOperationException {
if (this.cancelOperation == null) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Cancel operation is not supported on this service/resource."));
}
final PollResponse<T> response = this.pollResponse;
if (response != null && response.getStatus() != OperationStatus.IN_PROGRESS) {
return Mono.empty();
}
return this.cancelOperation.apply(this);
} | return this.cancelOperation.apply(this); | public Mono<T> cancelOperation() {
if (this.cancelOperation == null) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(
"Cancel operation is not supported on this service/resource.")));
}
final PollResponse<T> response = this.pollResponse;
if (response != null && response.getStatus() != OperationStatus.IN_PROGRESS) {
return Mono.empty();
}
return this.cancelOperation.apply(this);
} | class Poller<T, R> {
private final ClientLogger logger = new ClientLogger(Poller.class);
/*
* poll operation is a function that takes the previous PollResponse, and returns a new Mono of PollResponse to
* represent the current state
*/
private final Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation;
/*
* poll interval before next auto poll. This value will be used if the PollResponse does not include retryAfter
* from the service.
*/
private final Duration pollInterval;
/*
* This will be called when cancel operation is triggered.
*/
private final Function<Poller<T, R>, Mono<T>> cancelOperation;
/*
* Indicate to poll automatically or not when poller is created.
* default value is false;
*/
private boolean autoPollingEnabled;
/*
* This will be called when final result needs to be retrieved after polling has completed.
*/
private final Supplier<Mono<R>> fetchResultOperation;
/*
* This handle to Flux allow us to perform polling operation in asynchronous manner.
* This could be shared among many subscriber. One of the subscriber will be this poller itself.
* Once subscribed, this Flux will continue to poll for status until poll operation is done/complete.
*/
private final Flux<PollResponse<T>> fluxHandle;
/*
* This will save last poll response.
*/
private volatile PollResponse<T> pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, null);
/*
* Since constructor create a subscriber and start auto polling. This handle will be used to dispose the subscriber
* when client disable auto polling.
*/
private Disposable fluxDisposable;
/**
* Creates a {@link Poller} instance with poll interval and poll operation. The polling starts immediately by
* invoking {@code pollOperation}. The next poll cycle will be defined by {@code retryAfter} value in
* {@link PollResponse}. In absence of {@code retryAfter}, the {@link Poller} will use {@code pollInterval}.
*
* <p><strong>Create poller object</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.initialize.interval.polloperation}
*
* @param pollInterval Non null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono
* to poll.
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero.
* @throws NullPointerException if {@code pollInterval} or {@code pollOperation} is {@code null}.
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation) {
this(pollInterval, pollOperation, fetchResultOperation, null, null);
}
/**
* Creates a {@link Poller} instance with poll interval, poll operation, and optional cancel operation. Polling
* starts immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value in
* {@link PollResponse}. In absence of {@link PollResponse
* {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono
* to poll.
* @param activationOperation The activation operation to be called by the {@link Poller} instance before
* calling {@code pollOperation}. It can be {@code null} which will indicate to the {@link Poller} that
* {@code pollOperation} can be called straight away.
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @param cancelOperation Cancel operation if cancellation is supported by the service. If it is {@code null}, then
* the cancel operation is not supported.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation, Supplier<Mono<T>> activationOperation,
Function<Poller<T, R>, Mono<T>> cancelOperation) {
Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null.");
Objects.requireNonNull(fetchResultOperation, "'fetchResultOperation' cannot be null.");
if (pollInterval.compareTo(Duration.ZERO) <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Negative or zero value for 'pollInterval' is not allowed."));
}
this.pollInterval = pollInterval;
this.fetchResultOperation = fetchResultOperation;
this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null.");
final Mono<T> onActivation = activationOperation == null
? Mono.empty()
: activationOperation.get().map(response -> {
this.pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, response);
return response;
});
this.fluxHandle = asyncPollRequestWithDelay()
.flux()
.repeat()
.takeUntil(pollResponse -> isComplete())
.share()
.delaySubscription(onActivation);
this.fluxDisposable = fluxHandle.subscribe();
this.autoPollingEnabled = true;
this.cancelOperation = cancelOperation;
}
/**
* Create a {@link Poller} instance with poll interval, poll operation and cancel operation. The polling starts
* immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value
* in {@link PollResponse}. In absence of {@link PollResponse
* will use {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This is a callback into
* the client library, which must never return {@code null}, and which must always have a non-null
* {@link OperationStatus}. {@link Mono} returned from poll operation should never return
* {@link Mono
* client library and return a valid {@link PollResponse}. However if poll operation returns
* {@link Mono
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @param cancelOperation cancel operation if cancellation is supported by the service. It can be {@code null}
* which will indicate to the {@link Poller} that cancel operation is not supported by Azure service.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation, Function<Poller<T, R>, Mono<T>> cancelOperation) {
this(pollInterval, pollOperation, fetchResultOperation, null, cancelOperation);
}
/**
* Attempts to cancel the long-running operation that this {@link Poller} represents. This is possible only if the
* service supports it, otherwise an {@code UnsupportedOperationException} will be thrown.
* <p>
* It will call cancelOperation if status is {@link OperationStatus
*
* @throws UnsupportedOperationException when the cancel operation is not supported by the Azure service.
* @return A {@link Mono} containing the response.
*/
/**
* Returns the final result if the polling operation has been completed.
* @return A {@link Mono} containing the final output.
*/
public Mono<R> result() {
if (getStatus() == null || !getStatus().equals(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED)) {
return Mono.error(new IllegalAccessException("The poll operation has not successfully completed."));
}
return fetchResultOperation.get();
}
/**
* This method returns a {@link Flux} that can be subscribed to, enabling a subscriber to receive notification of
* every {@link PollResponse}, as it is received.
*
* @return A {@link Flux} that can be subscribed to receive poll responses as the long-running operation executes.
*/
public Flux<PollResponse<T>> getObserver() {
return this.fluxHandle;
}
/**
* Enables user to take control of polling and trigger manual poll operation. It will call poll operation once.
* This will not turn off auto polling.
*
* <p><strong>Manual polling</strong></p>
* <p>
* {@codesnippet com.azure.core.util.polling.poller.poll-indepth}
*
* @return A {@link Mono} that returns {@link PollResponse}. This will call poll operation once.
*/
public Mono<PollResponse<T>> poll() {
return pollOperation.apply(this.pollResponse)
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
});
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on the status defined
* in {@link OperationStatus}.
*
* <p>It will enable auto-polling if it was disabled by the user.
*
* @return The final output once Polling completes.
*/
public R block() {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
this.fluxHandle.blockLast();
return result().block();
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on status defined in
* {@link OperationStatus}.
* <p>It will enable auto-polling if it was disable by user.
*
* @param timeout The duration for which execution is blocked and waits for polling to complete.
* @return The final output once Polling completes.
*/
public R block(Duration timeout) {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
this.fluxHandle.blockLast(timeout);
return result().block();
}
/**
* Blocks indefinitely until given {@link OperationStatus} is received.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for.
* @return {@link PollResponse} whose {@link PollResponse
* @throws IllegalArgumentException If {@code statusToBlockFor} is {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor) {
return blockUntil(statusToBlockFor, null);
}
/**
* Blocks until given {@code statusToBlockFor} is received or the {@code timeout} elapses. If a {@code null}
* {@code timeout} is given, it will block indefinitely.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for and it can be any valid
* {@link OperationStatus} value.
* @param timeout The time after which it will stop blocking. A {@code null} value will cause to block
* indefinitely. Zero or negative are not valid values.
* @return {@link PollResponse} for matching desired status to block for.
* @throws IllegalArgumentException if {@code timeout} is zero or negative and if {@code statusToBlockFor} is
* {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor, Duration timeout) {
if (statusToBlockFor == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("Null value for status is not allowed."));
}
if (timeout != null && timeout.toNanos() <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Negative or zero value for timeout is not allowed."));
}
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
if (timeout != null) {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst(timeout);
} else {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst();
}
}
/*
* Indicate that the {@link PollResponse} matches with the status to block for.
* @param currentPollResponse The poll response which we have received from the flux.
* @param statusToBlockFor The {@link OperationStatus} to block and it can be any valid {@link OperationStatus}
* value.
* @return True if the {@link PollResponse} return status matches the status to block for.
*/
private boolean matchStatus(PollResponse<T> currentPollResponse, OperationStatus statusToBlockFor) {
if (currentPollResponse == null || statusToBlockFor == null) {
return false;
}
if (statusToBlockFor == currentPollResponse.getStatus()) {
return true;
}
return false;
}
/*
* This function will apply delay and call poll operation function async.
* We expect Mono from pollOperation should never return Mono.error(). If any unexpected
* scenario happens in pollOperation, it should catch it and return a valid PollResponse.
* This is because poller does not know what to do in case on Mono.error.
* This function will return empty mono in case of Mono.error() returned by poll operation.
*
* @return mono of poll response
*/
private Mono<PollResponse<T>> asyncPollRequestWithDelay() {
return Mono.defer(() -> this.pollOperation.apply(this.pollResponse)
.delaySubscription(getCurrentDelay())
.onErrorResume(throwable -> {
return Mono.empty();
})
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
}));
}
/**
* We will use {@link PollResponse
*/
private Duration getCurrentDelay() {
final PollResponse<T> current = pollResponse;
return (current != null
&& current.getRetryAfter() != null
&& current.getRetryAfter().compareTo(Duration.ZERO) > 0) ? current.getRetryAfter() : pollInterval;
}
/**
* Controls whether auto-polling is enabled or disabled. Refer to the {@link Poller} class-level JavaDoc for more
* details on auto-polling.
*
* <p><strong>Disable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.disableautopolling}
*
* <p><strong>Enable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.enableautopolling}
*
* @param autoPollingEnabled If true, auto-polling will occur transparently in the background, otherwise it
* requires manual polling by the user to get the latest state.
*/
public final void setAutoPollingEnabled(boolean autoPollingEnabled) {
this.autoPollingEnabled = autoPollingEnabled;
if (this.autoPollingEnabled) {
if (!activeSubscriber()) {
this.fluxDisposable = this.fluxHandle.subscribe(pr -> this.pollResponse = pr);
}
} else {
if (activeSubscriber()) {
this.fluxDisposable.dispose();
}
}
}
/**
* An operation will be considered complete if it is in some custom complete state or in one of the following state:
* <ul>
* <li>SUCCESSFULLY_COMPLETED</li>
* <li>USER_CANCELLED</li>
* <li>FAILED</li>
* </ul>
* Also see {@link OperationStatus}
* @return true if operation is done/complete.
*/
public boolean isComplete() {
final PollResponse<T> current = this.pollResponse;
return current != null && current.getStatus().isComplete();
}
/**
* Get the last poll response.
* @return the last poll response.
*/
public PollResponse<T> getLastPollResponse() {
return this.pollResponse;
}
/*
* Determine if this poller's internal subscriber exists and active.
*/
private boolean activeSubscriber() {
return (this.fluxDisposable != null && !this.fluxDisposable.isDisposed());
}
/**
* Indicates if auto polling is enabled. Refer to the {@link Poller} class-level JavaDoc for more details on
* auto-polling.
*
* @return {@code true} if auto-polling is enabled and {@code false} otherwise.
*/
public boolean isAutoPollingEnabled() {
return this.autoPollingEnabled;
}
/**
* Current known status as a result of last poll event or last response from a manual polling.
*
* @return Current status or {@code null} if no status is available.
*/
public OperationStatus getStatus() {
final PollResponse<T> current = this.pollResponse;
return current != null ? current.getStatus() : null;
}
} | class Poller<T, R> {
private final ClientLogger logger = new ClientLogger(Poller.class);
/*
* poll operation is a function that takes the previous PollResponse, and returns a new Mono of PollResponse to
* represent the current state
*/
private final Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation;
/*
* poll interval before next auto poll. This value will be used if the PollResponse does not include retryAfter
* from the service.
*/
private final Duration pollInterval;
/*
* This will be called when cancel operation is triggered.
*/
private final Function<Poller<T, R>, Mono<T>> cancelOperation;
/*
* This will be called when final result needs to be retrieved after polling has completed.
*/
private final Supplier<Mono<R>> fetchResultOperation;
/*
* This handle to Flux allow us to perform polling operation in asynchronous manner.
* This could be shared among many subscriber. One of the subscriber will be this poller itself.
* Once subscribed, this Flux will continue to poll for status until poll operation is done/complete.
*/
private final Flux<PollResponse<T>> fluxHandle;
/*
* This will save last poll response.
*/
private volatile PollResponse<T> pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, null);
/*
* Since constructor create a subscriber and start auto polling. This handle will be used to dispose the subscriber
* when client disable auto polling.
*/
private Disposable fluxDisposable;
/*
* Indicate to poll automatically or not when poller is created.
* default value is false;
*/
private boolean autoPollingEnabled;
/**
* Creates a {@link Poller} instance with poll interval and poll operation. The polling starts immediately by
* invoking {@code pollOperation}. The next poll cycle will be defined by {@code retryAfter} value in
* {@link PollResponse}. In absence of {@code retryAfter}, the {@link Poller} will use {@code pollInterval}.
*
* <p><strong>Create poller object</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.initialize.interval.polloperation}
*
* @param pollInterval Non null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono
* to poll.
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero.
* @throws NullPointerException if {@code pollInterval} or {@code pollOperation} is {@code null}.
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation) {
this(pollInterval, pollOperation, fetchResultOperation, null, null);
}
/**
* Creates a {@link Poller} instance with poll interval, poll operation, and optional cancel operation. Polling
* starts immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value in
* {@link PollResponse}. In absence of {@link PollResponse
* {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono
* to poll.
* @param activationOperation The activation operation to be called by the {@link Poller} instance before
* calling {@code pollOperation}. It can be {@code null} which will indicate to the {@link Poller} that
* {@code pollOperation} can be called straight away.
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @param cancelOperation Cancel operation if cancellation is supported by the service. If it is {@code null}, then
* the cancel operation is not supported.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation, Supplier<Mono<T>> activationOperation,
Function<Poller<T, R>, Mono<T>> cancelOperation) {
Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null.");
Objects.requireNonNull(fetchResultOperation, "'fetchResultOperation' cannot be null.");
if (pollInterval.compareTo(Duration.ZERO) <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Negative or zero value for 'pollInterval' is not allowed."));
}
this.pollInterval = pollInterval;
this.fetchResultOperation = fetchResultOperation;
this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null.");
final Mono<T> onActivation = activationOperation == null
? Mono.empty()
: activationOperation.get().doOnError(ex -> this.pollResponse = new PollResponse<>(FAILED, null))
.onErrorStop()
.map(response -> {
this.pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, response);
return response;
});
this.fluxHandle = asyncPollRequestWithDelay()
.flux()
.repeat()
.takeUntil(pollResponse -> isComplete())
.share()
.delaySubscription(onActivation);
this.fluxDisposable = fluxHandle.subscribe();
this.autoPollingEnabled = true;
this.cancelOperation = cancelOperation;
}
/**
* Create a {@link Poller} instance with poll interval, poll operation and cancel operation. The polling starts
* immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value
* in {@link PollResponse}. In absence of {@link PollResponse
* will use {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This is a callback into
* the client library, which must never return {@code null}, and which must always have a non-null
* {@link OperationStatus}. {@link Mono} returned from poll operation should never return
* {@link Mono
* client library and return a valid {@link PollResponse}. However if poll operation returns
* {@link Mono
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @param cancelOperation cancel operation if cancellation is supported by the service. It can be {@code null}
* which will indicate to the {@link Poller} that cancel operation is not supported by Azure service.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation, Function<Poller<T, R>, Mono<T>> cancelOperation) {
this(pollInterval, pollOperation, fetchResultOperation, null, cancelOperation);
}
/**
* Attempts to cancel the long-running operation that this {@link Poller} represents. This is possible only if the
* service supports it, otherwise an {@code UnsupportedOperationException} will be thrown.
* <p>
* It will call cancelOperation if status is {@link OperationStatus
*
* @return A {@link Mono} containing the poller response.
*/
/**
* Returns the final result if the polling operation has been completed. An empty {@link Mono} will be returned if
* the polling operation has not completed.
* @return A {@link Mono} containing the final output.
*/
public Mono<R> getResult() {
if (getStatus() == null || !isComplete()) {
return Mono.empty();
}
return fetchResultOperation.get();
}
/**
* This method returns a {@link Flux} that can be subscribed to, enabling a subscriber to receive notification of
* every {@link PollResponse}, as it is received.
*
* @return A {@link Flux} that can be subscribed to receive poll responses as the long-running operation executes.
*/
public Flux<PollResponse<T>> getObserver() {
return this.fluxHandle;
}
/**
* Enables user to take control of polling and trigger manual poll operation. It will call poll operation once.
* This will not turn off auto polling.
*
* <p><strong>Manual polling</strong></p>
* <p>
* {@codesnippet com.azure.core.util.polling.poller.poll-indepth}
*
* @return A {@link Mono} that returns {@link PollResponse}. This will call poll operation once.
*/
public Mono<PollResponse<T>> poll() {
return pollOperation.apply(this.pollResponse)
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
});
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on the status defined
* in {@link OperationStatus}.
*
* <p>It will enable auto-polling if it was disabled by the user.
*
* @return The final output once polling completes.
*/
public R block() {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
this.fluxHandle.blockLast();
return getResult().block();
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on status defined in
* {@link OperationStatus}.
* <p>It will enable auto-polling if it was disable by user.
*
* @param timeout The duration for which execution is blocked and waits for polling to complete.
* @return The final output once polling completes.
*/
public R block(Duration timeout) {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
this.fluxHandle.blockLast(timeout);
return getResult().block();
}
/**
* Blocks indefinitely until given {@link OperationStatus} is received.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for.
* @return {@link PollResponse} whose {@link PollResponse
* @throws IllegalArgumentException If {@code statusToBlockFor} is {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor) {
return blockUntil(statusToBlockFor, null);
}
/**
* Blocks until given {@code statusToBlockFor} is received or the {@code timeout} elapses. If a {@code null}
* {@code timeout} is given, it will block indefinitely.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for and it can be any valid
* {@link OperationStatus} value.
* @param timeout The time after which it will stop blocking. A {@code null} value will cause to block
* indefinitely. Zero or negative are not valid values.
* @return {@link PollResponse} for matching desired status to block for.
* @throws IllegalArgumentException if {@code timeout} is zero or negative and if {@code statusToBlockFor} is
* {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor, Duration timeout) {
if (statusToBlockFor == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("Null value for status is not allowed."));
}
if (timeout != null && timeout.toNanos() <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Negative or zero value for timeout is not allowed."));
}
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
if (timeout != null) {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst(timeout);
} else {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst();
}
}
/*
* Indicate that the {@link PollResponse} matches with the status to block for.
* @param currentPollResponse The poll response which we have received from the flux.
* @param statusToBlockFor The {@link OperationStatus} to block and it can be any valid {@link OperationStatus}
* value.
* @return True if the {@link PollResponse} return status matches the status to block for.
*/
private boolean matchStatus(PollResponse<T> currentPollResponse, OperationStatus statusToBlockFor) {
if (currentPollResponse == null || statusToBlockFor == null) {
return false;
}
if (statusToBlockFor == currentPollResponse.getStatus()) {
return true;
}
return false;
}
/*
* This function will apply delay and call poll operation function async.
* We expect Mono from pollOperation should never return Mono.error(). If any unexpected
* scenario happens in pollOperation, it should catch it and return a valid PollResponse.
* This is because poller does not know what to do in case on Mono.error.
* This function will return empty mono in case of Mono.error() returned by poll operation.
*
* @return mono of poll response
*/
private Mono<PollResponse<T>> asyncPollRequestWithDelay() {
return Mono.defer(() -> this.pollOperation.apply(this.pollResponse)
.delaySubscription(getCurrentDelay())
.onErrorResume(throwable -> {
return Mono.empty();
})
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
}));
}
/**
* We will use {@link PollResponse
*/
private Duration getCurrentDelay() {
final PollResponse<T> current = pollResponse;
return (current != null
&& current.getRetryAfter() != null
&& current.getRetryAfter().compareTo(Duration.ZERO) > 0) ? current.getRetryAfter() : pollInterval;
}
/**
* Controls whether auto-polling is enabled or disabled. Refer to the {@link Poller} class-level JavaDoc for more
* details on auto-polling.
*
* <p><strong>Disable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.disableautopolling}
*
* <p><strong>Enable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.enableautopolling}
*
* @param autoPollingEnabled If true, auto-polling will occur transparently in the background, otherwise it
* requires manual polling by the user to get the latest state.
*/
public final void setAutoPollingEnabled(boolean autoPollingEnabled) {
this.autoPollingEnabled = autoPollingEnabled;
if (this.autoPollingEnabled) {
if (!activeSubscriber()) {
this.fluxDisposable = this.fluxHandle.subscribe(pr -> this.pollResponse = pr);
}
} else {
if (activeSubscriber()) {
this.fluxDisposable.dispose();
}
}
}
/**
* An operation will be considered complete if it is in some custom complete state or in one of the following state:
* <ul>
* <li>SUCCESSFULLY_COMPLETED</li>
* <li>USER_CANCELLED</li>
* <li>FAILED</li>
* </ul>
* Also see {@link OperationStatus}
* @return true if operation is done/complete.
*/
public boolean isComplete() {
final PollResponse<T> current = this.pollResponse;
return current != null && current.getStatus().isComplete();
}
/**
* Get the last poll response.
* @return the last poll response.
*/
public PollResponse<T> getLastPollResponse() {
return this.pollResponse;
}
/*
* Determine if this poller's internal subscriber exists and active.
*/
private boolean activeSubscriber() {
return (this.fluxDisposable != null && !this.fluxDisposable.isDisposed());
}
/**
* Indicates if auto polling is enabled. Refer to the {@link Poller} class-level JavaDoc for more details on
* auto-polling.
*
* @return {@code true} if auto-polling is enabled and {@code false} otherwise.
*/
public boolean isAutoPollingEnabled() {
return this.autoPollingEnabled;
}
/**
* Current known status as a result of last poll event or last response from a manual polling.
*
* @return Current status or {@code null} if no status is available.
*/
public OperationStatus getStatus() {
final PollResponse<T> current = this.pollResponse;
return current != null ? current.getStatus() : null;
}
} |
If its a REST call in cancelOperation then the behavoiur will be same as an API call. User can specify .onError on the Mono returned to them from cancelOperation. if needed in CancelOperation, Mono.error should be returned there. | public Mono<T> cancelOperation() throws UnsupportedOperationException {
if (this.cancelOperation == null) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"Cancel operation is not supported on this service/resource."));
}
final PollResponse<T> response = this.pollResponse;
if (response != null && response.getStatus() != OperationStatus.IN_PROGRESS) {
return Mono.empty();
}
return this.cancelOperation.apply(this);
} | return this.cancelOperation.apply(this); | public Mono<T> cancelOperation() {
if (this.cancelOperation == null) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(
"Cancel operation is not supported on this service/resource.")));
}
final PollResponse<T> response = this.pollResponse;
if (response != null && response.getStatus() != OperationStatus.IN_PROGRESS) {
return Mono.empty();
}
return this.cancelOperation.apply(this);
} | class Poller<T, R> {
private final ClientLogger logger = new ClientLogger(Poller.class);
/*
* poll operation is a function that takes the previous PollResponse, and returns a new Mono of PollResponse to
* represent the current state
*/
private final Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation;
/*
* poll interval before next auto poll. This value will be used if the PollResponse does not include retryAfter
* from the service.
*/
private final Duration pollInterval;
/*
* This will be called when cancel operation is triggered.
*/
private final Function<Poller<T, R>, Mono<T>> cancelOperation;
/*
* Indicate to poll automatically or not when poller is created.
* default value is false;
*/
private boolean autoPollingEnabled;
/*
* This will be called when final result needs to be retrieved after polling has completed.
*/
private final Supplier<Mono<R>> fetchResultOperation;
/*
* This handle to Flux allow us to perform polling operation in asynchronous manner.
* This could be shared among many subscriber. One of the subscriber will be this poller itself.
* Once subscribed, this Flux will continue to poll for status until poll operation is done/complete.
*/
private final Flux<PollResponse<T>> fluxHandle;
/*
* This will save last poll response.
*/
private volatile PollResponse<T> pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, null);
/*
* Since constructor create a subscriber and start auto polling. This handle will be used to dispose the subscriber
* when client disable auto polling.
*/
private Disposable fluxDisposable;
/**
* Creates a {@link Poller} instance with poll interval and poll operation. The polling starts immediately by
* invoking {@code pollOperation}. The next poll cycle will be defined by {@code retryAfter} value in
* {@link PollResponse}. In absence of {@code retryAfter}, the {@link Poller} will use {@code pollInterval}.
*
* <p><strong>Create poller object</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.initialize.interval.polloperation}
*
* @param pollInterval Non null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono
* to poll.
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero.
* @throws NullPointerException if {@code pollInterval} or {@code pollOperation} is {@code null}.
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation) {
this(pollInterval, pollOperation, fetchResultOperation, null, null);
}
/**
* Creates a {@link Poller} instance with poll interval, poll operation, and optional cancel operation. Polling
* starts immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value in
* {@link PollResponse}. In absence of {@link PollResponse
* {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono
* to poll.
* @param activationOperation The activation operation to be called by the {@link Poller} instance before
* calling {@code pollOperation}. It can be {@code null} which will indicate to the {@link Poller} that
* {@code pollOperation} can be called straight away.
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @param cancelOperation Cancel operation if cancellation is supported by the service. If it is {@code null}, then
* the cancel operation is not supported.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation, Supplier<Mono<T>> activationOperation,
Function<Poller<T, R>, Mono<T>> cancelOperation) {
Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null.");
Objects.requireNonNull(fetchResultOperation, "'fetchResultOperation' cannot be null.");
if (pollInterval.compareTo(Duration.ZERO) <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Negative or zero value for 'pollInterval' is not allowed."));
}
this.pollInterval = pollInterval;
this.fetchResultOperation = fetchResultOperation;
this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null.");
final Mono<T> onActivation = activationOperation == null
? Mono.empty()
: activationOperation.get().map(response -> {
this.pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, response);
return response;
});
this.fluxHandle = asyncPollRequestWithDelay()
.flux()
.repeat()
.takeUntil(pollResponse -> isComplete())
.share()
.delaySubscription(onActivation);
this.fluxDisposable = fluxHandle.subscribe();
this.autoPollingEnabled = true;
this.cancelOperation = cancelOperation;
}
/**
* Create a {@link Poller} instance with poll interval, poll operation and cancel operation. The polling starts
* immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value
* in {@link PollResponse}. In absence of {@link PollResponse
* will use {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This is a callback into
* the client library, which must never return {@code null}, and which must always have a non-null
* {@link OperationStatus}. {@link Mono} returned from poll operation should never return
* {@link Mono
* client library and return a valid {@link PollResponse}. However if poll operation returns
* {@link Mono
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @param cancelOperation cancel operation if cancellation is supported by the service. It can be {@code null}
* which will indicate to the {@link Poller} that cancel operation is not supported by Azure service.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation, Function<Poller<T, R>, Mono<T>> cancelOperation) {
this(pollInterval, pollOperation, fetchResultOperation, null, cancelOperation);
}
/**
* Attempts to cancel the long-running operation that this {@link Poller} represents. This is possible only if the
* service supports it, otherwise an {@code UnsupportedOperationException} will be thrown.
* <p>
* It will call cancelOperation if status is {@link OperationStatus
*
* @throws UnsupportedOperationException when the cancel operation is not supported by the Azure service.
* @return A {@link Mono} containing the response.
*/
/**
* Returns the final result if the polling operation has been completed.
* @return A {@link Mono} containing the final output.
*/
public Mono<R> result() {
if (getStatus() == null || !getStatus().equals(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED)) {
return Mono.error(new IllegalAccessException("The poll operation has not successfully completed."));
}
return fetchResultOperation.get();
}
/**
* This method returns a {@link Flux} that can be subscribed to, enabling a subscriber to receive notification of
* every {@link PollResponse}, as it is received.
*
* @return A {@link Flux} that can be subscribed to receive poll responses as the long-running operation executes.
*/
public Flux<PollResponse<T>> getObserver() {
return this.fluxHandle;
}
/**
* Enables user to take control of polling and trigger manual poll operation. It will call poll operation once.
* This will not turn off auto polling.
*
* <p><strong>Manual polling</strong></p>
* <p>
* {@codesnippet com.azure.core.util.polling.poller.poll-indepth}
*
* @return A {@link Mono} that returns {@link PollResponse}. This will call poll operation once.
*/
public Mono<PollResponse<T>> poll() {
return pollOperation.apply(this.pollResponse)
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
});
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on the status defined
* in {@link OperationStatus}.
*
* <p>It will enable auto-polling if it was disabled by the user.
*
* @return The final output once Polling completes.
*/
public R block() {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
this.fluxHandle.blockLast();
return result().block();
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on status defined in
* {@link OperationStatus}.
* <p>It will enable auto-polling if it was disable by user.
*
* @param timeout The duration for which execution is blocked and waits for polling to complete.
* @return The final output once Polling completes.
*/
public R block(Duration timeout) {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
this.fluxHandle.blockLast(timeout);
return result().block();
}
/**
* Blocks indefinitely until given {@link OperationStatus} is received.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for.
* @return {@link PollResponse} whose {@link PollResponse
* @throws IllegalArgumentException If {@code statusToBlockFor} is {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor) {
return blockUntil(statusToBlockFor, null);
}
/**
* Blocks until given {@code statusToBlockFor} is received or the {@code timeout} elapses. If a {@code null}
* {@code timeout} is given, it will block indefinitely.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for and it can be any valid
* {@link OperationStatus} value.
* @param timeout The time after which it will stop blocking. A {@code null} value will cause to block
* indefinitely. Zero or negative are not valid values.
* @return {@link PollResponse} for matching desired status to block for.
* @throws IllegalArgumentException if {@code timeout} is zero or negative and if {@code statusToBlockFor} is
* {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor, Duration timeout) {
if (statusToBlockFor == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("Null value for status is not allowed."));
}
if (timeout != null && timeout.toNanos() <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Negative or zero value for timeout is not allowed."));
}
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
if (timeout != null) {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst(timeout);
} else {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst();
}
}
/*
* Indicate that the {@link PollResponse} matches with the status to block for.
* @param currentPollResponse The poll response which we have received from the flux.
* @param statusToBlockFor The {@link OperationStatus} to block and it can be any valid {@link OperationStatus}
* value.
* @return True if the {@link PollResponse} return status matches the status to block for.
*/
private boolean matchStatus(PollResponse<T> currentPollResponse, OperationStatus statusToBlockFor) {
if (currentPollResponse == null || statusToBlockFor == null) {
return false;
}
if (statusToBlockFor == currentPollResponse.getStatus()) {
return true;
}
return false;
}
/*
* This function will apply delay and call poll operation function async.
* We expect Mono from pollOperation should never return Mono.error(). If any unexpected
* scenario happens in pollOperation, it should catch it and return a valid PollResponse.
* This is because poller does not know what to do in case on Mono.error.
* This function will return empty mono in case of Mono.error() returned by poll operation.
*
* @return mono of poll response
*/
private Mono<PollResponse<T>> asyncPollRequestWithDelay() {
return Mono.defer(() -> this.pollOperation.apply(this.pollResponse)
.delaySubscription(getCurrentDelay())
.onErrorResume(throwable -> {
return Mono.empty();
})
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
}));
}
/**
* We will use {@link PollResponse
*/
private Duration getCurrentDelay() {
final PollResponse<T> current = pollResponse;
return (current != null
&& current.getRetryAfter() != null
&& current.getRetryAfter().compareTo(Duration.ZERO) > 0) ? current.getRetryAfter() : pollInterval;
}
/**
* Controls whether auto-polling is enabled or disabled. Refer to the {@link Poller} class-level JavaDoc for more
* details on auto-polling.
*
* <p><strong>Disable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.disableautopolling}
*
* <p><strong>Enable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.enableautopolling}
*
* @param autoPollingEnabled If true, auto-polling will occur transparently in the background, otherwise it
* requires manual polling by the user to get the latest state.
*/
public final void setAutoPollingEnabled(boolean autoPollingEnabled) {
this.autoPollingEnabled = autoPollingEnabled;
if (this.autoPollingEnabled) {
if (!activeSubscriber()) {
this.fluxDisposable = this.fluxHandle.subscribe(pr -> this.pollResponse = pr);
}
} else {
if (activeSubscriber()) {
this.fluxDisposable.dispose();
}
}
}
/**
* An operation will be considered complete if it is in some custom complete state or in one of the following state:
* <ul>
* <li>SUCCESSFULLY_COMPLETED</li>
* <li>USER_CANCELLED</li>
* <li>FAILED</li>
* </ul>
* Also see {@link OperationStatus}
* @return true if operation is done/complete.
*/
public boolean isComplete() {
final PollResponse<T> current = this.pollResponse;
return current != null && current.getStatus().isComplete();
}
/**
* Get the last poll response.
* @return the last poll response.
*/
public PollResponse<T> getLastPollResponse() {
return this.pollResponse;
}
/*
* Determine if this poller's internal subscriber exists and active.
*/
private boolean activeSubscriber() {
return (this.fluxDisposable != null && !this.fluxDisposable.isDisposed());
}
/**
* Indicates if auto polling is enabled. Refer to the {@link Poller} class-level JavaDoc for more details on
* auto-polling.
*
* @return {@code true} if auto-polling is enabled and {@code false} otherwise.
*/
public boolean isAutoPollingEnabled() {
return this.autoPollingEnabled;
}
/**
* Current known status as a result of last poll event or last response from a manual polling.
*
* @return Current status or {@code null} if no status is available.
*/
public OperationStatus getStatus() {
final PollResponse<T> current = this.pollResponse;
return current != null ? current.getStatus() : null;
}
} | class Poller<T, R> {
private final ClientLogger logger = new ClientLogger(Poller.class);
/*
* poll operation is a function that takes the previous PollResponse, and returns a new Mono of PollResponse to
* represent the current state
*/
private final Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation;
/*
* poll interval before next auto poll. This value will be used if the PollResponse does not include retryAfter
* from the service.
*/
private final Duration pollInterval;
/*
* This will be called when cancel operation is triggered.
*/
private final Function<Poller<T, R>, Mono<T>> cancelOperation;
/*
* This will be called when final result needs to be retrieved after polling has completed.
*/
private final Supplier<Mono<R>> fetchResultOperation;
/*
* This handle to Flux allow us to perform polling operation in asynchronous manner.
* This could be shared among many subscriber. One of the subscriber will be this poller itself.
* Once subscribed, this Flux will continue to poll for status until poll operation is done/complete.
*/
private final Flux<PollResponse<T>> fluxHandle;
/*
* This will save last poll response.
*/
private volatile PollResponse<T> pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, null);
/*
* Since constructor create a subscriber and start auto polling. This handle will be used to dispose the subscriber
* when client disable auto polling.
*/
private Disposable fluxDisposable;
/*
* Indicate to poll automatically or not when poller is created.
* default value is false;
*/
private boolean autoPollingEnabled;
/**
* Creates a {@link Poller} instance with poll interval and poll operation. The polling starts immediately by
* invoking {@code pollOperation}. The next poll cycle will be defined by {@code retryAfter} value in
* {@link PollResponse}. In absence of {@code retryAfter}, the {@link Poller} will use {@code pollInterval}.
*
* <p><strong>Create poller object</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.initialize.interval.polloperation}
*
* @param pollInterval Non null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono
* to poll.
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero.
* @throws NullPointerException if {@code pollInterval} or {@code pollOperation} is {@code null}.
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation) {
this(pollInterval, pollOperation, fetchResultOperation, null, null);
}
/**
* Creates a {@link Poller} instance with poll interval, poll operation, and optional cancel operation. Polling
* starts immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value in
* {@link PollResponse}. In absence of {@link PollResponse
* {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This must never return
* {@code null} and always have a non-null {@link OperationStatus}. {@link Mono} returned from poll operation
* should never return {@link Mono
* operation, it should be handled by the client library and return a valid {@link PollResponse}. However if
* the poll operation returns {@link Mono
* to poll.
* @param activationOperation The activation operation to be called by the {@link Poller} instance before
* calling {@code pollOperation}. It can be {@code null} which will indicate to the {@link Poller} that
* {@code pollOperation} can be called straight away.
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @param cancelOperation Cancel operation if cancellation is supported by the service. If it is {@code null}, then
* the cancel operation is not supported.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation, Supplier<Mono<T>> activationOperation,
Function<Poller<T, R>, Mono<T>> cancelOperation) {
Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null.");
Objects.requireNonNull(fetchResultOperation, "'fetchResultOperation' cannot be null.");
if (pollInterval.compareTo(Duration.ZERO) <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Negative or zero value for 'pollInterval' is not allowed."));
}
this.pollInterval = pollInterval;
this.fetchResultOperation = fetchResultOperation;
this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null.");
final Mono<T> onActivation = activationOperation == null
? Mono.empty()
: activationOperation.get().doOnError(ex -> this.pollResponse = new PollResponse<>(FAILED, null))
.onErrorStop()
.map(response -> {
this.pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, response);
return response;
});
this.fluxHandle = asyncPollRequestWithDelay()
.flux()
.repeat()
.takeUntil(pollResponse -> isComplete())
.share()
.delaySubscription(onActivation);
this.fluxDisposable = fluxHandle.subscribe();
this.autoPollingEnabled = true;
this.cancelOperation = cancelOperation;
}
/**
* Create a {@link Poller} instance with poll interval, poll operation and cancel operation. The polling starts
* immediately by invoking {@code pollOperation}. The next poll cycle will be defined by retryAfter value
* in {@link PollResponse}. In absence of {@link PollResponse
* will use {@code pollInterval}.
*
* @param pollInterval Not-null and greater than zero poll interval.
* @param pollOperation The polling operation to be called by the {@link Poller} instance. This is a callback into
* the client library, which must never return {@code null}, and which must always have a non-null
* {@link OperationStatus}. {@link Mono} returned from poll operation should never return
* {@link Mono
* client library and return a valid {@link PollResponse}. However if poll operation returns
* {@link Mono
* @param fetchResultOperation The operation to be called to fetch final result after polling has been completed.
* @param cancelOperation cancel operation if cancellation is supported by the service. It can be {@code null}
* which will indicate to the {@link Poller} that cancel operation is not supported by Azure service.
* @throws IllegalArgumentException if {@code pollInterval} is less than or equal to zero and if
* {@code pollInterval} or {@code pollOperation} are {@code null}
*/
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation,
Supplier<Mono<R>> fetchResultOperation, Function<Poller<T, R>, Mono<T>> cancelOperation) {
this(pollInterval, pollOperation, fetchResultOperation, null, cancelOperation);
}
/**
* Attempts to cancel the long-running operation that this {@link Poller} represents. This is possible only if the
* service supports it, otherwise an {@code UnsupportedOperationException} will be thrown.
* <p>
* It will call cancelOperation if status is {@link OperationStatus
*
* @return A {@link Mono} containing the poller response.
*/
/**
* Returns the final result if the polling operation has been completed. An empty {@link Mono} will be returned if
* the polling operation has not completed.
* @return A {@link Mono} containing the final output.
*/
public Mono<R> getResult() {
if (getStatus() == null || !isComplete()) {
return Mono.empty();
}
return fetchResultOperation.get();
}
/**
* This method returns a {@link Flux} that can be subscribed to, enabling a subscriber to receive notification of
* every {@link PollResponse}, as it is received.
*
* @return A {@link Flux} that can be subscribed to receive poll responses as the long-running operation executes.
*/
public Flux<PollResponse<T>> getObserver() {
return this.fluxHandle;
}
/**
* Enables user to take control of polling and trigger manual poll operation. It will call poll operation once.
* This will not turn off auto polling.
*
* <p><strong>Manual polling</strong></p>
* <p>
* {@codesnippet com.azure.core.util.polling.poller.poll-indepth}
*
* @return A {@link Mono} that returns {@link PollResponse}. This will call poll operation once.
*/
public Mono<PollResponse<T>> poll() {
return pollOperation.apply(this.pollResponse)
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
});
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on the status defined
* in {@link OperationStatus}.
*
* <p>It will enable auto-polling if it was disabled by the user.
*
* @return The final output once polling completes.
*/
public R block() {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
this.fluxHandle.blockLast();
return getResult().block();
}
/**
* Blocks execution and wait for polling to complete. The polling is considered complete based on status defined in
* {@link OperationStatus}.
* <p>It will enable auto-polling if it was disable by user.
*
* @param timeout The duration for which execution is blocked and waits for polling to complete.
* @return The final output once polling completes.
*/
public R block(Duration timeout) {
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
this.fluxHandle.blockLast(timeout);
return getResult().block();
}
/**
* Blocks indefinitely until given {@link OperationStatus} is received.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for.
* @return {@link PollResponse} whose {@link PollResponse
* @throws IllegalArgumentException If {@code statusToBlockFor} is {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor) {
return blockUntil(statusToBlockFor, null);
}
/**
* Blocks until given {@code statusToBlockFor} is received or the {@code timeout} elapses. If a {@code null}
* {@code timeout} is given, it will block indefinitely.
*
* @param statusToBlockFor The desired {@link OperationStatus} to block for and it can be any valid
* {@link OperationStatus} value.
* @param timeout The time after which it will stop blocking. A {@code null} value will cause to block
* indefinitely. Zero or negative are not valid values.
* @return {@link PollResponse} for matching desired status to block for.
* @throws IllegalArgumentException if {@code timeout} is zero or negative and if {@code statusToBlockFor} is
* {@code null}.
*/
public PollResponse<T> blockUntil(OperationStatus statusToBlockFor, Duration timeout) {
if (statusToBlockFor == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("Null value for status is not allowed."));
}
if (timeout != null && timeout.toNanos() <= 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException(
"Negative or zero value for timeout is not allowed."));
}
if (!isAutoPollingEnabled()) {
setAutoPollingEnabled(true);
}
if (timeout != null) {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst(timeout);
} else {
return this.fluxHandle
.filter(tPollResponse -> matchStatus(tPollResponse, statusToBlockFor)).blockFirst();
}
}
/*
* Indicate that the {@link PollResponse} matches with the status to block for.
* @param currentPollResponse The poll response which we have received from the flux.
* @param statusToBlockFor The {@link OperationStatus} to block and it can be any valid {@link OperationStatus}
* value.
* @return True if the {@link PollResponse} return status matches the status to block for.
*/
private boolean matchStatus(PollResponse<T> currentPollResponse, OperationStatus statusToBlockFor) {
if (currentPollResponse == null || statusToBlockFor == null) {
return false;
}
if (statusToBlockFor == currentPollResponse.getStatus()) {
return true;
}
return false;
}
/*
* This function will apply delay and call poll operation function async.
* We expect Mono from pollOperation should never return Mono.error(). If any unexpected
* scenario happens in pollOperation, it should catch it and return a valid PollResponse.
* This is because poller does not know what to do in case on Mono.error.
* This function will return empty mono in case of Mono.error() returned by poll operation.
*
* @return mono of poll response
*/
private Mono<PollResponse<T>> asyncPollRequestWithDelay() {
return Mono.defer(() -> this.pollOperation.apply(this.pollResponse)
.delaySubscription(getCurrentDelay())
.onErrorResume(throwable -> {
return Mono.empty();
})
.doOnEach(pollResponseSignal -> {
if (pollResponseSignal.get() != null) {
this.pollResponse = pollResponseSignal.get();
}
}));
}
/**
* We will use {@link PollResponse
*/
private Duration getCurrentDelay() {
final PollResponse<T> current = pollResponse;
return (current != null
&& current.getRetryAfter() != null
&& current.getRetryAfter().compareTo(Duration.ZERO) > 0) ? current.getRetryAfter() : pollInterval;
}
/**
* Controls whether auto-polling is enabled or disabled. Refer to the {@link Poller} class-level JavaDoc for more
* details on auto-polling.
*
* <p><strong>Disable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.disableautopolling}
*
* <p><strong>Enable auto polling</strong></p>
* {@codesnippet com.azure.core.util.polling.poller.enableautopolling}
*
* @param autoPollingEnabled If true, auto-polling will occur transparently in the background, otherwise it
* requires manual polling by the user to get the latest state.
*/
public final void setAutoPollingEnabled(boolean autoPollingEnabled) {
this.autoPollingEnabled = autoPollingEnabled;
if (this.autoPollingEnabled) {
if (!activeSubscriber()) {
this.fluxDisposable = this.fluxHandle.subscribe(pr -> this.pollResponse = pr);
}
} else {
if (activeSubscriber()) {
this.fluxDisposable.dispose();
}
}
}
/**
* An operation will be considered complete if it is in some custom complete state or in one of the following state:
* <ul>
* <li>SUCCESSFULLY_COMPLETED</li>
* <li>USER_CANCELLED</li>
* <li>FAILED</li>
* </ul>
* Also see {@link OperationStatus}
* @return true if operation is done/complete.
*/
public boolean isComplete() {
final PollResponse<T> current = this.pollResponse;
return current != null && current.getStatus().isComplete();
}
/**
* Get the last poll response.
* @return the last poll response.
*/
public PollResponse<T> getLastPollResponse() {
return this.pollResponse;
}
/*
* Determine if this poller's internal subscriber exists and active.
*/
private boolean activeSubscriber() {
return (this.fluxDisposable != null && !this.fluxDisposable.isDisposed());
}
/**
* Indicates if auto polling is enabled. Refer to the {@link Poller} class-level JavaDoc for more details on
* auto-polling.
*
* @return {@code true} if auto-polling is enabled and {@code false} otherwise.
*/
public boolean isAutoPollingEnabled() {
return this.autoPollingEnabled;
}
/**
* Current known status as a result of last poll event or last response from a manual polling.
*
* @return Current status or {@code null} if no status is available.
*/
public OperationStatus getStatus() {
final PollResponse<T> current = this.pollResponse;
return current != null ? current.getStatus() : null;
}
} |
fixed. | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
status.completed = isComplete;
return status;
} | OperationStatus status = fromString(name, OperationStatus.class); | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
if (operationStatusMap != null && operationStatusMap.containsKey(name)) {
OperationStatus operationStatus = operationStatusMap.get(name);
if (operationStatus.isComplete() != isComplete) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for operation"
+ "status %s", isComplete, name));
}
}
status.completed = isComplete;
}
return status;
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
private static Map<String, OperationStatus> operationStatusMap;
static {
Map<String, OperationStatus> opStatusMap = new HashMap<>();
opStatusMap.put(NOT_STARTED.toString(), NOT_STARTED);
opStatusMap.put(IN_PROGRESS.toString(), IN_PROGRESS);
opStatusMap.put(SUCCESSFULLY_COMPLETED.toString(), SUCCESSFULLY_COMPLETED);
opStatusMap.put(FAILED.toString(), FAILED);
opStatusMap.put(USER_CANCELLED.toString(), USER_CANCELLED);
operationStatusMap = Collections.unmodifiableMap(opStatusMap);
}
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if {@code name} matches a pre-configured {@link OperationStatus} but
* {@code isComplete} doesn't match its pre-configured complete status.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} |
if status == null, I think we should throw something because this should not happen. Not sure what you'd do with a null status. | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
for (OperationStatus opStatus : values(OperationStatus.class)) {
if (opStatus.toString().equals(name)) {
if (!(opStatus.isComplete() == isComplete)) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for"
+ " operation status %s", isComplete, name));
}
}
}
status.completed = isComplete;
}
return status;
} | if (status != null) { | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
if (operationStatusMap != null && operationStatusMap.containsKey(name)) {
OperationStatus operationStatus = operationStatusMap.get(name);
if (operationStatus.isComplete() != isComplete) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for operation"
+ "status %s", isComplete, name));
}
}
status.completed = isComplete;
}
return status;
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if invalid {2code isComplete} is provided for a pre-configured
* {@link OperationStatus} with {@code name}
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
private static Map<String, OperationStatus> operationStatusMap;
static {
Map<String, OperationStatus> opStatusMap = new HashMap<>();
opStatusMap.put(NOT_STARTED.toString(), NOT_STARTED);
opStatusMap.put(IN_PROGRESS.toString(), IN_PROGRESS);
opStatusMap.put(SUCCESSFULLY_COMPLETED.toString(), SUCCESSFULLY_COMPLETED);
opStatusMap.put(FAILED.toString(), FAILED);
opStatusMap.put(USER_CANCELLED.toString(), USER_CANCELLED);
operationStatusMap = Collections.unmodifiableMap(opStatusMap);
}
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if {@code name} matches a pre-configured {@link OperationStatus} but
* {@code isComplete} doesn't match its pre-configured complete status.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} |
Why a for loop? The one returned `fromString(name, OperationStatus.class)` will return one from the dictionary if it was added before. Then you can do: ```java OperationStatus status = fromString(name, OperationStatus.class); if (status.isComplete() != isComplete) { // throw. } return status; ``` | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
for (OperationStatus opStatus : values(OperationStatus.class)) {
if (opStatus.toString().equals(name)) {
if (!(opStatus.isComplete() == isComplete)) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for"
+ " operation status %s", isComplete, name));
}
}
}
status.completed = isComplete;
}
return status;
} | for (OperationStatus opStatus : values(OperationStatus.class)) { | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
if (operationStatusMap != null && operationStatusMap.containsKey(name)) {
OperationStatus operationStatus = operationStatusMap.get(name);
if (operationStatus.isComplete() != isComplete) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for operation"
+ "status %s", isComplete, name));
}
}
status.completed = isComplete;
}
return status;
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if invalid {2code isComplete} is provided for a pre-configured
* {@link OperationStatus} with {@code name}
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
private static Map<String, OperationStatus> operationStatusMap;
static {
Map<String, OperationStatus> opStatusMap = new HashMap<>();
opStatusMap.put(NOT_STARTED.toString(), NOT_STARTED);
opStatusMap.put(IN_PROGRESS.toString(), IN_PROGRESS);
opStatusMap.put(SUCCESSFULLY_COMPLETED.toString(), SUCCESSFULLY_COMPLETED);
opStatusMap.put(FAILED.toString(), FAILED);
opStatusMap.put(USER_CANCELLED.toString(), USER_CANCELLED);
operationStatusMap = Collections.unmodifiableMap(opStatusMap);
}
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if {@code name} matches a pre-configured {@link OperationStatus} but
* {@code isComplete} doesn't match its pre-configured complete status.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} |
The intention is to check against only defined by us. So replaced with a static map and check against it. | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
for (OperationStatus opStatus : values(OperationStatus.class)) {
if (opStatus.toString().equals(name)) {
if (!(opStatus.isComplete() == isComplete)) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for"
+ " operation status %s", isComplete, name));
}
}
}
status.completed = isComplete;
}
return status;
} | for (OperationStatus opStatus : values(OperationStatus.class)) { | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
if (operationStatusMap != null && operationStatusMap.containsKey(name)) {
OperationStatus operationStatus = operationStatusMap.get(name);
if (operationStatus.isComplete() != isComplete) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for operation"
+ "status %s", isComplete, name));
}
}
status.completed = isComplete;
}
return status;
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if invalid {2code isComplete} is provided for a pre-configured
* {@link OperationStatus} with {@code name}
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
private static Map<String, OperationStatus> operationStatusMap;
static {
Map<String, OperationStatus> opStatusMap = new HashMap<>();
opStatusMap.put(NOT_STARTED.toString(), NOT_STARTED);
opStatusMap.put(IN_PROGRESS.toString(), IN_PROGRESS);
opStatusMap.put(SUCCESSFULLY_COMPLETED.toString(), SUCCESSFULLY_COMPLETED);
opStatusMap.put(FAILED.toString(), FAILED);
opStatusMap.put(USER_CANCELLED.toString(), USER_CANCELLED);
operationStatusMap = Collections.unmodifiableMap(opStatusMap);
}
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if {@code name} matches a pre-configured {@link OperationStatus} but
* {@code isComplete} doesn't match its pre-configured complete status.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} |
looking at expandable String enum code, it returns null if String name is null. So, we are returning null for null name input, across all classes who extend ExpandableStringEnum. This code will be consistent too. | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
for (OperationStatus opStatus : values(OperationStatus.class)) {
if (opStatus.toString().equals(name)) {
if (!(opStatus.isComplete() == isComplete)) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for"
+ " operation status %s", isComplete, name));
}
}
}
status.completed = isComplete;
}
return status;
} | if (status != null) { | public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
if (operationStatusMap != null && operationStatusMap.containsKey(name)) {
OperationStatus operationStatus = operationStatusMap.get(name);
if (operationStatus.isComplete() != isComplete) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for operation"
+ "status %s", isComplete, name));
}
}
status.completed = isComplete;
}
return status;
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if invalid {2code isComplete} is provided for a pre-configured
* {@link OperationStatus} with {@code name}
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} | class OperationStatus extends ExpandableStringEnum<OperationStatus> {
private boolean completed;
/** Represents that polling has not yet started for this long-running operation. */
public static final OperationStatus NOT_STARTED = fromString("NOT_STARTED", false);
/** Represents that this long-running operation is in progress and not yet complete. */
public static final OperationStatus IN_PROGRESS = fromString("IN_PROGRESS", false);
/** Represent that this long-running operation is completed successfully. */
public static final OperationStatus SUCCESSFULLY_COMPLETED = fromString("SUCCESSFULLY_COMPLETED",
true);
/**
* Represents that this long-running operation has failed to successfully complete, however this is still
* considered as complete long-running operation, meaning that the {@link Poller} instance will report that it
* is complete.
*/
public static final OperationStatus FAILED = fromString("FAILED", true);
/**
* Represents that this long-running operation is cancelled by user, however this is still
* considered as complete long-running operation.
*/
public static final OperationStatus USER_CANCELLED = fromString("USER_CANCELLED", true);
private static Map<String, OperationStatus> operationStatusMap;
static {
Map<String, OperationStatus> opStatusMap = new HashMap<>();
opStatusMap.put(NOT_STARTED.toString(), NOT_STARTED);
opStatusMap.put(IN_PROGRESS.toString(), IN_PROGRESS);
opStatusMap.put(SUCCESSFULLY_COMPLETED.toString(), SUCCESSFULLY_COMPLETED);
opStatusMap.put(FAILED.toString(), FAILED);
opStatusMap.put(USER_CANCELLED.toString(), USER_CANCELLED);
operationStatusMap = Collections.unmodifiableMap(opStatusMap);
}
/**
* Creates or finds a {@link OperationStatus} from its string representation.
* @param name a name to look for
* @param isComplete a status to indicate if the operation is complete or not.
* @throws IllegalArgumentException if {@code name} matches a pre-configured {@link OperationStatus} but
* {@code isComplete} doesn't match its pre-configured complete status.
* @return the corresponding {@link OperationStatus}
*/
public boolean isComplete() {
return completed;
}
} |
We add code snippets for aborting/cancelling the copy operation. | public void startCopyFromURL() {
final Poller<BlobCopyInfo, Void> poller = client.beginCopyFromUrl(url);
poller.getObserver().subscribe(response -> {
System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId());
});
} | public void startCopyFromURL() {
final Poller<BlobCopyInfo, Void> poller = client.beginCopy(url, Duration.ofSeconds(2));
poller.getObserver().subscribe(response -> {
System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId());
});
} | class BlobClientBaseJavaDocCodeSnippets {
private BlobClientBase client = new BlobClientBase(null);
private String leaseId = "leaseId";
private String copyId = "copyId";
private URL url = new URL("https:
private String file = "file";
private Duration timeout = Duration.ofSeconds(30);
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* @throws MalformedURLException Ignore
*/
public BlobClientBaseJavaDocCodeSnippets() throws MalformedURLException {
}
/**
* Code snippets for {@link BlobClientBase
*/
public void existsCodeSnippet() {
System.out.printf("Exists? %b%n", client.exists());
}
/**
* Code snippets for {@link BlobClientBase
*/
/**
* Code snippets for {@link BlobClientBase
*/
public void abortCopyFromURL() {
client.abortCopyFromURL(copyId);
System.out.println("Aborted copy completed.");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void copyFromURL() {
System.out.printf("Copy identifier: %s%n", client.copyFromURL(url));
}
/**
* Code snippets for {@link BlobClientBase
*/
public void download() {
client.download(new ByteArrayOutputStream());
System.out.println("Download completed.");
}
/**
* Code snippets for {@link BlobClientBase
* {@link BlobClientBase
* boolean, Duration, Context)}
*/
public void downloadToFile() {
client.downloadToFile(file);
System.out.println("Completed download to file");
BlobRange range = new BlobRange(1024, 2048L);
ReliableDownloadOptions options = new ReliableDownloadOptions().maxRetryRequests(5);
client.downloadToFileWithResponse(file, range, new ParallelTransferOptions().setBlockSize(4 * Constants.MB),
options, null, false, timeout, new Context(key2, value2));
System.out.println("Completed download to file");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setDelete() {
client.delete();
System.out.println("Delete completed.");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void getProperties() {
BlobProperties properties = client.getProperties();
System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setHTTPHeaders() {
client.setHTTPHeaders(new BlobHTTPHeaders()
.setBlobContentLanguage("en-US")
.setBlobContentType("binary"));
System.out.println("Set HTTP headers completed");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setMetadata() {
client.setMetadata(Collections.singletonMap("metadata", "value"));
System.out.println("Set metadata completed");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void createSnapshot() {
System.out.printf("Identifier for the snapshot is %s%n", client.createSnapshot().getSnapshotId());
}
/**
* Code snippets for {@link BlobClientBase
* {@link BlobClientBase
*/
public void setTier() {
System.out.printf("Set tier completed with status code %d%n",
client.setAccessTierWithResponse(AccessTier.HOT, null, null, null, null).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void unsetDelete() {
client.undelete();
System.out.println("Undelete completed");
}
/**
* Code snippet for {@link BlobClientBase
*/
public void getAccountInfo() {
StorageAccountInfo accountInfo = client.getAccountInfo();
System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void existsWithResponseCodeSnippet() {
System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, new Context(key2, value2)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
* ModifiedAccessConditions, BlobAccessConditions)}
*/
public void beginCopyFromUrl() {
Map<String, String> metadata = Collections.singletonMap("metadata", "value");
ModifiedAccessConditions modifiedAccessConditions = new ModifiedAccessConditions()
.setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7));
BlobAccessConditions blobAccessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
Poller<BlobCopyInfo, Void> poller = client.beginCopyFromUrl(url, metadata, AccessTier.HOT, RehydratePriority.STANDARD,
modifiedAccessConditions, blobAccessConditions);
PollResponse<BlobCopyInfo> response = poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void abortCopyFromURLWithResponseCodeSnippets() {
LeaseAccessConditions leaseAccessConditions = new LeaseAccessConditions().setLeaseId(leaseId);
System.out.printf("Aborted copy completed with status %d%n",
client.abortCopyFromURLWithResponse(copyId, leaseAccessConditions, timeout,
new Context(key2, value2)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* BlobAccessConditions, Duration, Context)}
*/
public void copyFromURLWithResponseCodeSnippets() {
Map<String, String> metadata = Collections.singletonMap("metadata", "value");
ModifiedAccessConditions modifiedAccessConditions = new ModifiedAccessConditions()
.setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7));
BlobAccessConditions blobAccessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Copy identifier: %s%n",
client.copyFromURLWithResponse(url, metadata, AccessTier.HOT, modifiedAccessConditions,
blobAccessConditions, timeout,
new Context(key1, value1)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
* BlobAccessConditions, boolean, Duration, Context)}
* @throws UncheckedIOException If an I/O error occurs
*/
public void downloadWithResponseCodeSnippets() {
BlobRange range = new BlobRange(1024, 2048L);
ReliableDownloadOptions options = new ReliableDownloadOptions().maxRetryRequests(5);
System.out.printf("Download completed with status %d%n",
client.downloadWithResponse(new ByteArrayOutputStream(), range, options, null, false,
timeout, new Context(key2, value2)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void deleteWithResponseCodeSnippets() {
System.out.printf("Delete completed with status %d%n",
client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void getPropertiesWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions()
.setLeaseAccessConditions(new LeaseAccessConditions().setLeaseId(leaseId));
BlobProperties properties = client.getPropertiesWithResponse(accessConditions, timeout,
new Context(key2, value2)).getValue();
System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void setHTTPHeadersWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions()
.setLeaseAccessConditions(new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Set HTTP headers completed with status %d%n",
client.setHTTPHeadersWithResponse(new BlobHTTPHeaders()
.setBlobContentLanguage("en-US")
.setBlobContentType("binary"), accessConditions, timeout, new Context(key1, value1))
.getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setMetadataWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Set metadata completed with status %d%n",
client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), accessConditions, timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void createSnapshotWithResponseCodeSnippets() {
Map<String, String> snapshotMetadata = Collections.singletonMap("metadata", "value");
BlobAccessConditions accessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Identifier for the snapshot is %s%n",
client.createSnapshotWithResponse(snapshotMetadata, accessConditions, timeout,
new Context(key1, value1)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setTierWithResponseCodeSnippets() {
LeaseAccessConditions accessConditions = new LeaseAccessConditions().setLeaseId(leaseId);
System.out.printf("Set tier completed with status code %d%n",
client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, accessConditions, timeout,
new Context(key2, value2)).getStatusCode());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void undeleteWithResponseCodeSnippets() {
System.out.printf("Undelete completed with status %d%n", client.undeleteWithResponse(timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void getAccountInfoWithResponseCodeSnippets() {
StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, new Context(key1, value1)).getValue();
System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName());
}
} | class BlobClientBaseJavaDocCodeSnippets {
private BlobClientBase client = new BlobClientBase(null);
private String leaseId = "leaseId";
private String copyId = "copyId";
private String url = "https:
private String file = "file";
private Duration timeout = Duration.ofSeconds(30);
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Code snippets for {@link BlobClientBase
*/
public void existsCodeSnippet() {
System.out.printf("Exists? %b%n", client.exists());
}
/**
* Code snippets for {@link BlobClientBase
*/
/**
* Code snippets for {@link BlobClientBase
*/
public void abortCopyFromURL() {
client.abortCopyFromURL(copyId);
System.out.println("Aborted copy completed.");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void copyFromURL() {
System.out.printf("Copy identifier: %s%n", client.copyFromURL(url));
}
/**
* Code snippets for {@link BlobClientBase
*/
public void download() {
client.download(new ByteArrayOutputStream());
System.out.println("Download completed.");
}
/**
* Code snippets for {@link BlobClientBase
* {@link BlobClientBase
* boolean, Duration, Context)}
*/
public void downloadToFile() {
client.downloadToFile(file);
System.out.println("Completed download to file");
BlobRange range = new BlobRange(1024, 2048L);
ReliableDownloadOptions options = new ReliableDownloadOptions().maxRetryRequests(5);
client.downloadToFileWithResponse(file, range, new ParallelTransferOptions().setBlockSize(4 * Constants.MB),
options, null, false, timeout, new Context(key2, value2));
System.out.println("Completed download to file");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setDelete() {
client.delete();
System.out.println("Delete completed.");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void getProperties() {
BlobProperties properties = client.getProperties();
System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setHTTPHeaders() {
client.setHttpHeaders(new BlobHttpHeaders()
.setBlobContentLanguage("en-US")
.setBlobContentType("binary"));
System.out.println("Set HTTP headers completed");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setMetadata() {
client.setMetadata(Collections.singletonMap("metadata", "value"));
System.out.println("Set metadata completed");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void createSnapshot() {
System.out.printf("Identifier for the snapshot is %s%n", client.createSnapshot().getSnapshotId());
}
/**
* Code snippets for {@link BlobClientBase
* {@link BlobClientBase
*/
public void setTier() {
System.out.printf("Set tier completed with status code %d%n",
client.setAccessTierWithResponse(AccessTier.HOT, null, null, null, null).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void unsetDelete() {
client.undelete();
System.out.println("Undelete completed");
}
/**
* Code snippet for {@link BlobClientBase
*/
public void getAccountInfo() {
StorageAccountInfo accountInfo = client.getAccountInfo();
System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void existsWithResponseCodeSnippet() {
System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, new Context(key2, value2)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
* ModifiedAccessConditions, BlobAccessConditions, Duration)}
*/
public void beginCopyFromUrl() {
Map<String, String> metadata = Collections.singletonMap("metadata", "value");
ModifiedAccessConditions modifiedAccessConditions = new ModifiedAccessConditions()
.setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7));
BlobAccessConditions blobAccessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
Poller<BlobCopyInfo, Void> poller = client.beginCopy(url, metadata, AccessTier.HOT,
RehydratePriority.STANDARD, modifiedAccessConditions, blobAccessConditions, Duration.ofSeconds(2));
PollResponse<BlobCopyInfo> response = poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void abortCopyFromURLWithResponseCodeSnippets() {
LeaseAccessConditions leaseAccessConditions = new LeaseAccessConditions().setLeaseId(leaseId);
System.out.printf("Aborted copy completed with status %d%n",
client.abortCopyFromURLWithResponse(copyId, leaseAccessConditions, timeout,
new Context(key2, value2)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* BlobAccessConditions, Duration, Context)}
*/
public void copyFromURLWithResponseCodeSnippets() {
Map<String, String> metadata = Collections.singletonMap("metadata", "value");
ModifiedAccessConditions modifiedAccessConditions = new ModifiedAccessConditions()
.setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7));
BlobAccessConditions blobAccessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Copy identifier: %s%n",
client.copyFromURLWithResponse(url, metadata, AccessTier.HOT, modifiedAccessConditions,
blobAccessConditions, timeout,
new Context(key1, value1)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
* BlobAccessConditions, boolean, Duration, Context)}
* @throws UncheckedIOException If an I/O error occurs
*/
public void downloadWithResponseCodeSnippets() {
BlobRange range = new BlobRange(1024, 2048L);
ReliableDownloadOptions options = new ReliableDownloadOptions().maxRetryRequests(5);
System.out.printf("Download completed with status %d%n",
client.downloadWithResponse(new ByteArrayOutputStream(), range, options, null, false,
timeout, new Context(key2, value2)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void deleteWithResponseCodeSnippets() {
System.out.printf("Delete completed with status %d%n",
client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void getPropertiesWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions()
.setLeaseAccessConditions(new LeaseAccessConditions().setLeaseId(leaseId));
BlobProperties properties = client.getPropertiesWithResponse(accessConditions, timeout,
new Context(key2, value2)).getValue();
System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void setHTTPHeadersWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions()
.setLeaseAccessConditions(new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Set HTTP headers completed with status %d%n",
client.setHttpHeadersWithResponse(new BlobHttpHeaders()
.setBlobContentLanguage("en-US")
.setBlobContentType("binary"), accessConditions, timeout, new Context(key1, value1))
.getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setMetadataWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Set metadata completed with status %d%n",
client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), accessConditions, timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void createSnapshotWithResponseCodeSnippets() {
Map<String, String> snapshotMetadata = Collections.singletonMap("metadata", "value");
BlobAccessConditions accessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Identifier for the snapshot is %s%n",
client.createSnapshotWithResponse(snapshotMetadata, accessConditions, timeout,
new Context(key1, value1)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setTierWithResponseCodeSnippets() {
LeaseAccessConditions accessConditions = new LeaseAccessConditions().setLeaseId(leaseId);
System.out.printf("Set tier completed with status code %d%n",
client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, accessConditions, timeout,
new Context(key2, value2)).getStatusCode());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void undeleteWithResponseCodeSnippets() {
System.out.printf("Undelete completed with status %d%n", client.undeleteWithResponse(timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void getAccountInfoWithResponseCodeSnippets() {
StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, new Context(key1, value1)).getValue();
System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName());
}
} | |
We should also add the copy status into this. | public void startCopyFromURL() {
final Poller<BlobCopyInfo, Void> poller = client.beginCopyFromUrl(url);
poller.getObserver().subscribe(response -> {
System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId());
});
} | System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId()); | public void startCopyFromURL() {
final Poller<BlobCopyInfo, Void> poller = client.beginCopy(url, Duration.ofSeconds(2));
poller.getObserver().subscribe(response -> {
System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId());
});
} | class BlobClientBaseJavaDocCodeSnippets {
private BlobClientBase client = new BlobClientBase(null);
private String leaseId = "leaseId";
private String copyId = "copyId";
private URL url = new URL("https:
private String file = "file";
private Duration timeout = Duration.ofSeconds(30);
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* @throws MalformedURLException Ignore
*/
public BlobClientBaseJavaDocCodeSnippets() throws MalformedURLException {
}
/**
* Code snippets for {@link BlobClientBase
*/
public void existsCodeSnippet() {
System.out.printf("Exists? %b%n", client.exists());
}
/**
* Code snippets for {@link BlobClientBase
*/
/**
* Code snippets for {@link BlobClientBase
*/
public void abortCopyFromURL() {
client.abortCopyFromURL(copyId);
System.out.println("Aborted copy completed.");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void copyFromURL() {
System.out.printf("Copy identifier: %s%n", client.copyFromURL(url));
}
/**
* Code snippets for {@link BlobClientBase
*/
public void download() {
client.download(new ByteArrayOutputStream());
System.out.println("Download completed.");
}
/**
* Code snippets for {@link BlobClientBase
* {@link BlobClientBase
* boolean, Duration, Context)}
*/
public void downloadToFile() {
client.downloadToFile(file);
System.out.println("Completed download to file");
BlobRange range = new BlobRange(1024, 2048L);
ReliableDownloadOptions options = new ReliableDownloadOptions().maxRetryRequests(5);
client.downloadToFileWithResponse(file, range, new ParallelTransferOptions().setBlockSize(4 * Constants.MB),
options, null, false, timeout, new Context(key2, value2));
System.out.println("Completed download to file");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setDelete() {
client.delete();
System.out.println("Delete completed.");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void getProperties() {
BlobProperties properties = client.getProperties();
System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setHTTPHeaders() {
client.setHTTPHeaders(new BlobHTTPHeaders()
.setBlobContentLanguage("en-US")
.setBlobContentType("binary"));
System.out.println("Set HTTP headers completed");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setMetadata() {
client.setMetadata(Collections.singletonMap("metadata", "value"));
System.out.println("Set metadata completed");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void createSnapshot() {
System.out.printf("Identifier for the snapshot is %s%n", client.createSnapshot().getSnapshotId());
}
/**
* Code snippets for {@link BlobClientBase
* {@link BlobClientBase
*/
public void setTier() {
System.out.printf("Set tier completed with status code %d%n",
client.setAccessTierWithResponse(AccessTier.HOT, null, null, null, null).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void unsetDelete() {
client.undelete();
System.out.println("Undelete completed");
}
/**
* Code snippet for {@link BlobClientBase
*/
public void getAccountInfo() {
StorageAccountInfo accountInfo = client.getAccountInfo();
System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void existsWithResponseCodeSnippet() {
System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, new Context(key2, value2)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
* ModifiedAccessConditions, BlobAccessConditions)}
*/
public void beginCopyFromUrl() {
Map<String, String> metadata = Collections.singletonMap("metadata", "value");
ModifiedAccessConditions modifiedAccessConditions = new ModifiedAccessConditions()
.setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7));
BlobAccessConditions blobAccessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
Poller<BlobCopyInfo, Void> poller = client.beginCopyFromUrl(url, metadata, AccessTier.HOT, RehydratePriority.STANDARD,
modifiedAccessConditions, blobAccessConditions);
PollResponse<BlobCopyInfo> response = poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void abortCopyFromURLWithResponseCodeSnippets() {
LeaseAccessConditions leaseAccessConditions = new LeaseAccessConditions().setLeaseId(leaseId);
System.out.printf("Aborted copy completed with status %d%n",
client.abortCopyFromURLWithResponse(copyId, leaseAccessConditions, timeout,
new Context(key2, value2)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* BlobAccessConditions, Duration, Context)}
*/
public void copyFromURLWithResponseCodeSnippets() {
Map<String, String> metadata = Collections.singletonMap("metadata", "value");
ModifiedAccessConditions modifiedAccessConditions = new ModifiedAccessConditions()
.setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7));
BlobAccessConditions blobAccessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Copy identifier: %s%n",
client.copyFromURLWithResponse(url, metadata, AccessTier.HOT, modifiedAccessConditions,
blobAccessConditions, timeout,
new Context(key1, value1)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
* BlobAccessConditions, boolean, Duration, Context)}
* @throws UncheckedIOException If an I/O error occurs
*/
public void downloadWithResponseCodeSnippets() {
BlobRange range = new BlobRange(1024, 2048L);
ReliableDownloadOptions options = new ReliableDownloadOptions().maxRetryRequests(5);
System.out.printf("Download completed with status %d%n",
client.downloadWithResponse(new ByteArrayOutputStream(), range, options, null, false,
timeout, new Context(key2, value2)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void deleteWithResponseCodeSnippets() {
System.out.printf("Delete completed with status %d%n",
client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void getPropertiesWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions()
.setLeaseAccessConditions(new LeaseAccessConditions().setLeaseId(leaseId));
BlobProperties properties = client.getPropertiesWithResponse(accessConditions, timeout,
new Context(key2, value2)).getValue();
System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void setHTTPHeadersWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions()
.setLeaseAccessConditions(new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Set HTTP headers completed with status %d%n",
client.setHTTPHeadersWithResponse(new BlobHTTPHeaders()
.setBlobContentLanguage("en-US")
.setBlobContentType("binary"), accessConditions, timeout, new Context(key1, value1))
.getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setMetadataWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Set metadata completed with status %d%n",
client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), accessConditions, timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void createSnapshotWithResponseCodeSnippets() {
Map<String, String> snapshotMetadata = Collections.singletonMap("metadata", "value");
BlobAccessConditions accessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Identifier for the snapshot is %s%n",
client.createSnapshotWithResponse(snapshotMetadata, accessConditions, timeout,
new Context(key1, value1)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setTierWithResponseCodeSnippets() {
LeaseAccessConditions accessConditions = new LeaseAccessConditions().setLeaseId(leaseId);
System.out.printf("Set tier completed with status code %d%n",
client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, accessConditions, timeout,
new Context(key2, value2)).getStatusCode());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void undeleteWithResponseCodeSnippets() {
System.out.printf("Undelete completed with status %d%n", client.undeleteWithResponse(timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void getAccountInfoWithResponseCodeSnippets() {
StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, new Context(key1, value1)).getValue();
System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName());
}
} | class BlobClientBaseJavaDocCodeSnippets {
private BlobClientBase client = new BlobClientBase(null);
private String leaseId = "leaseId";
private String copyId = "copyId";
private String url = "https:
private String file = "file";
private Duration timeout = Duration.ofSeconds(30);
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Code snippets for {@link BlobClientBase
*/
public void existsCodeSnippet() {
System.out.printf("Exists? %b%n", client.exists());
}
/**
* Code snippets for {@link BlobClientBase
*/
/**
* Code snippets for {@link BlobClientBase
*/
public void abortCopyFromURL() {
client.abortCopyFromURL(copyId);
System.out.println("Aborted copy completed.");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void copyFromURL() {
System.out.printf("Copy identifier: %s%n", client.copyFromURL(url));
}
/**
* Code snippets for {@link BlobClientBase
*/
public void download() {
client.download(new ByteArrayOutputStream());
System.out.println("Download completed.");
}
/**
* Code snippets for {@link BlobClientBase
* {@link BlobClientBase
* boolean, Duration, Context)}
*/
public void downloadToFile() {
client.downloadToFile(file);
System.out.println("Completed download to file");
BlobRange range = new BlobRange(1024, 2048L);
ReliableDownloadOptions options = new ReliableDownloadOptions().maxRetryRequests(5);
client.downloadToFileWithResponse(file, range, new ParallelTransferOptions().setBlockSize(4 * Constants.MB),
options, null, false, timeout, new Context(key2, value2));
System.out.println("Completed download to file");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setDelete() {
client.delete();
System.out.println("Delete completed.");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void getProperties() {
BlobProperties properties = client.getProperties();
System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setHTTPHeaders() {
client.setHttpHeaders(new BlobHttpHeaders()
.setBlobContentLanguage("en-US")
.setBlobContentType("binary"));
System.out.println("Set HTTP headers completed");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setMetadata() {
client.setMetadata(Collections.singletonMap("metadata", "value"));
System.out.println("Set metadata completed");
}
/**
* Code snippets for {@link BlobClientBase
*/
public void createSnapshot() {
System.out.printf("Identifier for the snapshot is %s%n", client.createSnapshot().getSnapshotId());
}
/**
* Code snippets for {@link BlobClientBase
* {@link BlobClientBase
*/
public void setTier() {
System.out.printf("Set tier completed with status code %d%n",
client.setAccessTierWithResponse(AccessTier.HOT, null, null, null, null).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void unsetDelete() {
client.undelete();
System.out.println("Undelete completed");
}
/**
* Code snippet for {@link BlobClientBase
*/
public void getAccountInfo() {
StorageAccountInfo accountInfo = client.getAccountInfo();
System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void existsWithResponseCodeSnippet() {
System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, new Context(key2, value2)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
* ModifiedAccessConditions, BlobAccessConditions, Duration)}
*/
public void beginCopyFromUrl() {
Map<String, String> metadata = Collections.singletonMap("metadata", "value");
ModifiedAccessConditions modifiedAccessConditions = new ModifiedAccessConditions()
.setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7));
BlobAccessConditions blobAccessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
Poller<BlobCopyInfo, Void> poller = client.beginCopy(url, metadata, AccessTier.HOT,
RehydratePriority.STANDARD, modifiedAccessConditions, blobAccessConditions, Duration.ofSeconds(2));
PollResponse<BlobCopyInfo> response = poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void abortCopyFromURLWithResponseCodeSnippets() {
LeaseAccessConditions leaseAccessConditions = new LeaseAccessConditions().setLeaseId(leaseId);
System.out.printf("Aborted copy completed with status %d%n",
client.abortCopyFromURLWithResponse(copyId, leaseAccessConditions, timeout,
new Context(key2, value2)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* BlobAccessConditions, Duration, Context)}
*/
public void copyFromURLWithResponseCodeSnippets() {
Map<String, String> metadata = Collections.singletonMap("metadata", "value");
ModifiedAccessConditions modifiedAccessConditions = new ModifiedAccessConditions()
.setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7));
BlobAccessConditions blobAccessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Copy identifier: %s%n",
client.copyFromURLWithResponse(url, metadata, AccessTier.HOT, modifiedAccessConditions,
blobAccessConditions, timeout,
new Context(key1, value1)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
* BlobAccessConditions, boolean, Duration, Context)}
* @throws UncheckedIOException If an I/O error occurs
*/
public void downloadWithResponseCodeSnippets() {
BlobRange range = new BlobRange(1024, 2048L);
ReliableDownloadOptions options = new ReliableDownloadOptions().maxRetryRequests(5);
System.out.printf("Download completed with status %d%n",
client.downloadWithResponse(new ByteArrayOutputStream(), range, options, null, false,
timeout, new Context(key2, value2)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void deleteWithResponseCodeSnippets() {
System.out.printf("Delete completed with status %d%n",
client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void getPropertiesWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions()
.setLeaseAccessConditions(new LeaseAccessConditions().setLeaseId(leaseId));
BlobProperties properties = client.getPropertiesWithResponse(accessConditions, timeout,
new Context(key2, value2)).getValue();
System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void setHTTPHeadersWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions()
.setLeaseAccessConditions(new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Set HTTP headers completed with status %d%n",
client.setHttpHeadersWithResponse(new BlobHttpHeaders()
.setBlobContentLanguage("en-US")
.setBlobContentType("binary"), accessConditions, timeout, new Context(key1, value1))
.getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setMetadataWithResponseCodeSnippets() {
BlobAccessConditions accessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Set metadata completed with status %d%n",
client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), accessConditions, timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippets for {@link BlobClientBase
* Context)}
*/
public void createSnapshotWithResponseCodeSnippets() {
Map<String, String> snapshotMetadata = Collections.singletonMap("metadata", "value");
BlobAccessConditions accessConditions = new BlobAccessConditions().setLeaseAccessConditions(
new LeaseAccessConditions().setLeaseId(leaseId));
System.out.printf("Identifier for the snapshot is %s%n",
client.createSnapshotWithResponse(snapshotMetadata, accessConditions, timeout,
new Context(key1, value1)).getValue());
}
/**
* Code snippets for {@link BlobClientBase
*/
public void setTierWithResponseCodeSnippets() {
LeaseAccessConditions accessConditions = new LeaseAccessConditions().setLeaseId(leaseId);
System.out.printf("Set tier completed with status code %d%n",
client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, accessConditions, timeout,
new Context(key2, value2)).getStatusCode());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void undeleteWithResponseCodeSnippets() {
System.out.printf("Undelete completed with status %d%n", client.undeleteWithResponse(timeout,
new Context(key1, value1)).getStatusCode());
}
/**
* Code snippet for {@link BlobClientBase
*/
public void getAccountInfoWithResponseCodeSnippets() {
StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, new Context(key1, value1)).getValue();
System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName());
}
} |
Does `FAILED` really correspond to `NOT_STARTED`? | private Mono<PollResponse<BlobCopyInfo>> onPoll(PollResponse<BlobCopyInfo> pollResponse) {
if (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED) {
return Mono.just(pollResponse);
}
final BlobCopyInfo lastInfo = pollResponse.getValue();
if (lastInfo == null) {
logger.warning("BlobCopyInfo does not exist. Activation operation failed.");
return Mono.just(new PollResponse<>(
OperationStatus.fromString("COPY_START_FAILED", true), null));
}
return getProperties().map(response -> {
final CopyStatusType status = response.getCopyStatus();
final BlobCopyInfo result = new BlobCopyInfo(response.getCopySource(), response.getCopyId(), status,
response.getETag(), response.getCopyCompletionTime(), response.getCopyStatusDescription());
OperationStatus operationStatus;
switch (status) {
case SUCCESS:
operationStatus = OperationStatus.SUCCESSFULLY_COMPLETED;
break;
case FAILED:
operationStatus = OperationStatus.NOT_STARTED;
break;
case ABORTED:
operationStatus = OperationStatus.USER_CANCELLED;
break;
case PENDING:
operationStatus = OperationStatus.IN_PROGRESS;
break;
default:
throw Exceptions.propagate(logger.logExceptionAsError(new IllegalArgumentException(
"CopyStatusType is not supported. Status: " + status)));
}
return new PollResponse<>(operationStatus, result);
}).onErrorReturn(
new PollResponse<>(OperationStatus.fromString("POLLING_FAILED", true), lastInfo));
} | return new PollResponse<>(operationStatus, result); | return getProperties().map(response -> {
final CopyStatusType status = response.getCopyStatus();
final BlobCopyInfo result = new BlobCopyInfo(response.getCopySource(), response.getCopyId(), status,
response.getETag(), response.getCopyCompletionTime(), response.getCopyStatusDescription());
OperationStatus operationStatus;
switch (status) {
case SUCCESS:
operationStatus = OperationStatus.SUCCESSFULLY_COMPLETED;
break;
case FAILED:
operationStatus = OperationStatus.FAILED;
break;
case ABORTED:
operationStatus = OperationStatus.USER_CANCELLED;
break;
case PENDING:
operationStatus = OperationStatus.IN_PROGRESS;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"CopyStatusType is not supported. Status: " + status));
}
return new PollResponse<>(operationStatus, result);
} | class BlobAsyncClientBase {
private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB;
private final ClientLogger logger = new ClientLogger(BlobAsyncClientBase.class);
protected final AzureBlobStorageImpl azureBlobStorage;
private final String snapshot;
private final CpkInfo customerProvidedKey;
protected final String accountName;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param azureBlobStorage the API client for blob storage
* @param snapshot Optional. The snapshot identifier for the snapshot blob.
* @param customerProvidedKey Optional. Customer provided key used during encryption of the blob's data on the
* server.
* @param accountName The account name for storage account.
*/
protected BlobAsyncClientBase(AzureBlobStorageImpl azureBlobStorage, String snapshot,
CpkInfo customerProvidedKey, String accountName) {
this.azureBlobStorage = azureBlobStorage;
this.snapshot = snapshot;
this.customerProvidedKey = customerProvidedKey;
this.accountName = accountName;
}
/**
* Creates a new {@link BlobAsyncClientBase} linked to the {@code snapshot} of this blob resource.
*
* @param snapshot the identifier for a specific snapshot of this blob
* @return a {@link BlobAsyncClientBase} used to interact with the specific snapshot.
*/
public BlobAsyncClientBase getSnapshotClient(String snapshot) {
return new BlobAsyncClientBase(new AzureBlobStorageBuilder()
.url(getBlobUrl())
.pipeline(azureBlobStorage.getHttpPipeline())
.build(), snapshot, customerProvidedKey, accountName);
}
/**
* Gets the URL of the blob represented by this client.
*
* @return the URL.
*/
public String getBlobUrl() {
if (!this.isSnapshot()) {
return azureBlobStorage.getUrl();
} else {
if (azureBlobStorage.getUrl().contains("?")) {
return String.format("%s&snapshot=%s", azureBlobStorage.getUrl(), snapshot);
} else {
return String.format("%s?snapshot=%s", azureBlobStorage.getUrl(), snapshot);
}
}
}
/**
* Get the container name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName}
*
* @return The name of the container.
*/
public final String getContainerName() {
return BlobUrlParts.parse(this.azureBlobStorage.getUrl(), logger).getBlobContainerName();
}
/**
* Get the blob name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName}
*
* @return The name of the blob.
*/
public final String getBlobName() {
return BlobUrlParts.parse(this.azureBlobStorage.getUrl(), logger).getBlobName();
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the {@link CpkInfo} used to encrypt this blob's content on the server.
*
* @return the customer provided key used for encryption.
*/
public CpkInfo getCustomerProvidedKey() {
return customerProvidedKey;
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Gets the snapshotId for a blob resource
*
* @return A string that represents the snapshotId of the snapshot blob
*/
public String getSnapshotId() {
return this.snapshot;
}
/**
* Determines if a blob is a snapshot
*
* @return A boolean that indicates if a blob is a snapshot
*/
public boolean isSnapshot() {
return this.snapshot != null;
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.exists}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Boolean> exists() {
return existsWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Response<Boolean>> existsWithResponse() {
return withContext(this::existsWithResponse);
}
Mono<Response<Boolean>> existsWithResponse(Context context) {
return this.getPropertiesWithResponse(null, context)
.map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true))
.onErrorResume(t -> t instanceof StorageException && ((StorageException) t).getStatusCode() == 404, t -> {
HttpResponse response = ((StorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false));
});
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrl
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
*
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopyFromUrl(URL sourceUrl) {
return beginCopyFromUrl(sourceUrl, null, null, null, null, null);
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrl
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param priority {@link RehydratePriority} for rehydrating the blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP
* Access conditions related to the modification of data. ETag and LastModifiedTime are used to construct
* conditions related to when the blob was changed relative to the given request. The request will fail if the
* specified condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
*
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopyFromUrl(URL sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destAccessConditions) {
final ModifiedAccessConditions sourceModifiedCondition = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions()
: sourceModifiedAccessConditions;
final BlobAccessConditions destinationAccessConditions = destAccessConditions == null
? new BlobAccessConditions()
: destAccessConditions;
final SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedCondition.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedCondition.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedCondition.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedCondition.getIfNoneMatch());
return new Poller<>(
Duration.ofSeconds(1),
this::onPoll,
Mono::empty,
() -> onStart(sourceUrl, metadata, tier, priority, sourceConditions, destinationAccessConditions),
poller -> {
final PollResponse<BlobCopyInfo> response = poller.getLastPollResponse();
if (response == null || response.getValue() == null) {
return Mono.error(logger.logExceptionAsError(
new IllegalArgumentException("Cannot cancel a poll response that never started.")));
}
final String copyIdentifier = response.getValue().getCopyId();
if (!ImplUtils.isNullOrEmpty(copyIdentifier)) {
logger.info("Cancelling copy operation for copy id: {}", copyIdentifier);
return abortCopyFromURL(copyIdentifier).thenReturn(response.getValue());
}
return Mono.empty();
});
}
private Mono<BlobCopyInfo> onStart(URL sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, SourceModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destinationAccessConditions) {
return withContext(
context -> azureBlobStorage.blobs().startCopyFromURLWithRestResponseAsync(null, null,
sourceUrl, null, metadata, tier, priority, null, sourceModifiedAccessConditions,
destinationAccessConditions.getModifiedAccessConditions(),
destinationAccessConditions.getLeaseAccessConditions(), context))
.map(response -> {
final BlobStartCopyFromURLHeaders headers = response.getDeserializedHeaders();
return new BlobCopyInfo(sourceUrl.toString(), headers.getCopyId(), headers.getCopyStatus(),
headers.getETag(), headers.getLastModified(), headers.getErrorCode());
});
}
private Mono<PollResponse<BlobCopyInfo>> onPoll(PollResponse<BlobCopyInfo> pollResponse) {
if (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED) {
return Mono.just(pollResponse);
}
final BlobCopyInfo lastInfo = pollResponse.getValue();
if (lastInfo == null) {
logger.warning("BlobCopyInfo does not exist. Activation operation failed.");
return Mono.just(new PollResponse<>(
OperationStatus.fromString("COPY_START_FAILED", true), null));
}
).onErrorReturn(
new PollResponse<>(OperationStatus.fromString("POLLING_FAILED", true), lastInfo));
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* @param copyId The id of the copy operation to abort.
* @return A reactive response signalling completion.
*/
public Mono<Void> abortCopyFromURL(String copyId) {
return abortCopyFromURLWithResponse(copyId, null).flatMap(FluxUtil::toMono);
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* @param copyId The id of the copy operation to abort.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId,
LeaseAccessConditions leaseAccessConditions) {
return withContext(context -> abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context));
}
Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions,
Context context) {
return this.azureBlobStorage.blobs().abortCopyFromURLWithRestResponseAsync(
null, null, copyId, null, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<String> copyFromURL(URL copySource) {
return copyFromURLWithResponse(copySource, null, null, null, null).flatMap(FluxUtil::toMono);
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access
* conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions
* related to when the blob was changed relative to the given request. The request will fail if the specified
* condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier,
ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions) {
return withContext(context -> copyFromURLWithResponse(copySource, metadata, tier,
sourceModifiedAccessConditions, destAccessConditions, context));
}
Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier,
ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions,
Context context) {
sourceModifiedAccessConditions = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions() : sourceModifiedAccessConditions;
destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions;
SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch());
return this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync(
null, null, copySource, null, metadata, tier, null, sourceConditions,
destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(),
context).map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId()));
}
/**
* Reads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or
* {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.download}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob data.
*/
public Flux<ByteBuffer> download() {
return downloadWithResponse(null, null, null, false)
.flatMapMany(Response::getValue);
}
/**
* Reads a range of bytes from a blob. Uploading data must be done from the {@link BlockBlobClient}, {@link
* PageBlobClient}, or {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param range {@link BlobRange}
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return A reactive response containing the blob data.
*/
public Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
return withContext(context -> downloadWithResponse(range, options, accessConditions, rangeGetContentMD5,
context));
}
Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
return download(range, accessConditions, rangeGetContentMD5, context)
.map(response -> new SimpleResponse<>(
response.getRawResponse(),
response.body(options).switchIfEmpty(Flux.just(ByteBuffer.wrap(new byte[0])))));
}
/**
* Reads a range of bytes from a blob. The response also includes the blob's properties and metadata. For more
* information, see the <a href="https:
* <p>
* Note that the response body has reliable download functionality built in, meaning that a failed download stream
* will be automatically retried. This behavior may be configured with {@link ReliableDownloadOptions}.
*
* @param range {@link BlobRange}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return Emits the successful response.
*/
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5) {
return withContext(context -> download(range, accessConditions, rangeGetContentMD5, context));
}
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5, Context context) {
range = range == null ? new BlobRange(0) : range;
Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null;
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
HttpGetterInfo info = new HttpGetterInfo()
.setOffset(range.getOffset())
.setCount(range.getCount())
.setETag(accessConditions.getModifiedAccessConditions().getIfMatch());
return this.azureBlobStorage.blobs().downloadWithRestResponseAsync(
null, null, snapshot, null, range.toHeaderValue(), getMD5, null, null,
accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> {
info.setETag(response.getDeserializedHeaders().getETag());
return new DownloadAsyncResponse(response, info,
newInfo ->
this.download(new BlobRange(newInfo.getOffset(), newInfo.getCount()),
new BlobAccessConditions().setModifiedAccessConditions(
new ModifiedAccessConditions().setIfMatch(info.getETag())), false, context));
});
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @return An empty response
*/
public Mono<BlobProperties> downloadToFile(String filePath) {
return downloadToFileWithResponse(filePath, null, null,
null, null, false).flatMap(FluxUtil::toMono);
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra
* call, provide the {@link BlobRange} parameter.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @param range {@link BlobRange}
* @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel
* transfers parameter is ignored.
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return An empty response
* @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB.
* @throws UncheckedIOException If an I/O error occurs.
*/
public Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
return withContext(context -> downloadToFileWithResponse(filePath, range, parallelTransferOptions, options,
accessConditions, rangeGetContentMD5, context));
}
Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
final ParallelTransferOptions finalParallelTransferOptions = parallelTransferOptions == null
? new ParallelTransferOptions()
: parallelTransferOptions;
ProgressReceiver progressReceiver = finalParallelTransferOptions.getProgressReceiver();
AtomicLong totalProgress = new AtomicLong(0);
Lock progressLock = new ReentrantLock();
return Mono.using(() -> downloadToFileResourceSupplier(filePath),
channel -> getPropertiesWithResponse(accessConditions)
.flatMap(response -> processInRange(channel, response,
range, finalParallelTransferOptions.getBlockSize(), options, accessConditions, rangeGetContentMD5,
context, totalProgress, progressLock, progressReceiver)), this::downloadToFileCleanup);
}
private Mono<Response<BlobProperties>> processInRange(AsynchronousFileChannel channel,
Response<BlobProperties> blobPropertiesResponse, BlobRange range, Integer blockSize,
ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5,
Context context, AtomicLong totalProgress, Lock progressLock, ProgressReceiver progressReceiver) {
return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new BlobRange(0,
blobPropertiesResponse.getValue().getBlobSize()))).flatMapMany(rg ->
Flux.fromIterable(sliceBlobRange(rg, blockSize)))
.flatMap(chunk -> this.download(chunk, accessConditions, rangeGetContentMD5, context)
.subscribeOn(Schedulers.elastic())
.flatMap(dar -> {
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
dar.body(options), progressReceiver, progressLock, totalProgress);
return FluxUtil.writeFile(progressData, channel,
chunk.getOffset() - ((range == null) ? 0 : range.getOffset()));
})).then(Mono.just(blobPropertiesResponse));
}
private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath) {
try {
return AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private void downloadToFileCleanup(AsynchronousFileChannel channel) {
try {
channel.close();
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private List<BlobRange> sliceBlobRange(BlobRange blobRange, Integer blockSize) {
if (blockSize == null) {
blockSize = BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE;
}
long offset = blobRange.getOffset();
long length = blobRange.getCount();
List<BlobRange> chunks = new ArrayList<>();
for (long pos = offset; pos < offset + length; pos += blockSize) {
long count = blockSize;
if (pos + count > offset + length) {
count = offset + length - pos;
}
chunks.add(new BlobRange(pos, count));
}
return chunks;
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> delete() {
return deleteWithResponse(null, null).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include}
* will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being
* deleted, you must pass null.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions) {
return withContext(context -> deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context));
}
Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().deleteWithRestResponseAsync(
null, null, snapshot, null, deleteBlobSnapshotOptions,
null, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(),
context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<BlobProperties> getProperties() {
return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono);
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions) {
return withContext(context -> getPropertiesWithResponse(accessConditions, context));
}
Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().getPropertiesWithRestResponseAsync(
null, null, snapshot, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, new BlobProperties(rb.getDeserializedHeaders())));
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeaders
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHTTPHeaders}
* @return A reactive response signalling completion.
*/
public Mono<Void> setHTTPHeaders(BlobHTTPHeaders headers) {
return setHTTPHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono);
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeadersWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHTTPHeaders}
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers,
BlobAccessConditions accessConditions) {
return withContext(context -> setHTTPHeadersWithResponse(headers, accessConditions, context));
}
Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setHTTPHeadersWithRestResponseAsync(
null, null, null, null, headers,
accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @return A reactive response signalling completion.
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono);
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
return withContext(context -> setMetadataWithResponse(metadata, accessConditions, context));
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setMetadataWithRestResponseAsync(
null, null, null, metadata, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<BlobAsyncClientBase> createSnapshot() {
return createSnapshotWithResponse(null, null).flatMap(FluxUtil::toMono);
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob snapshot.
* @param accessConditions {@link BlobAccessConditions}
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
return withContext(context -> createSnapshotWithResponse(metadata, accessConditions, context));
}
Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().createSnapshotWithRestResponseAsync(
null, null, null, metadata, null, customerProvidedKey, accessConditions.getModifiedAccessConditions(),
accessConditions.getLeaseAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.getDeserializedHeaders().getSnapshot())));
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Void> setAccessTier(AccessTier tier) {
return setAccessTierWithResponse(tier, null, null).flatMap(FluxUtil::toMono);
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @param priority Optional priority to set for re-hydrating blobs.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Response<Void>> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions) {
return withContext(context -> setTierWithResponse(tier, priority, leaseAccessConditions, context));
}
Mono<Response<Void>> setTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions, Context context) {
Utility.assertNotNull("tier", tier);
return this.azureBlobStorage.blobs().setTierWithRestResponseAsync(
null, null, tier, null, priority, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> undelete() {
return undeleteWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> undeleteWithResponse() {
return withContext(this::undeleteWithResponse);
}
Mono<Response<Void>> undeleteWithResponse(Context context) {
return this.azureBlobStorage.blobs().undeleteWithRestResponseAsync(null,
null, context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<StorageAccountInfo> getAccountInfo() {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
return withContext(this::getAccountInfoWithResponse);
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
return this.azureBlobStorage.blobs().getAccountInfoWithRestResponseAsync(null, null, context)
.map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.getDeserializedHeaders())));
}
} | class BlobAsyncClientBase {
private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB;
private final ClientLogger logger = new ClientLogger(BlobAsyncClientBase.class);
protected final AzureBlobStorageImpl azureBlobStorage;
private final String snapshot;
private final CpkInfo customerProvidedKey;
protected final String accountName;
protected final String containerName;
protected final String blobName;
protected final BlobServiceVersion serviceVersion;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param containerName The container name.
* @param blobName The blob name.
* @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
*/
protected BlobAsyncClientBase(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion,
String accountName, String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey) {
this.azureBlobStorage = new AzureBlobStorageBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.build();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.containerName = containerName;
this.blobName = blobName;
this.snapshot = snapshot;
this.customerProvidedKey = customerProvidedKey;
}
/**
* Creates a new {@link BlobAsyncClientBase} linked to the {@code snapshot} of this blob resource.
*
* @param snapshot the identifier for a specific snapshot of this blob
* @return a {@link BlobAsyncClientBase} used to interact with the specific snapshot.
*/
public BlobAsyncClientBase getSnapshotClient(String snapshot) {
return new BlobAsyncClientBase(getHttpPipeline(), getBlobUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), snapshot, getCustomerProvidedKey());
}
/**
* Gets the URL of the blob represented by this client.
*
* @return the URL.
*/
public String getBlobUrl() {
if (!this.isSnapshot()) {
return azureBlobStorage.getUrl();
} else {
if (azureBlobStorage.getUrl().contains("?")) {
return String.format("%s&snapshot=%s", azureBlobStorage.getUrl(), snapshot);
} else {
return String.format("%s?snapshot=%s", azureBlobStorage.getUrl(), snapshot);
}
}
}
/**
* Get the container name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName}
*
* @return The name of the container.
*/
public final String getContainerName() {
return containerName;
}
/**
* Get the blob name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName}
*
* @return The name of the blob.
*/
public final String getBlobName() {
return blobName;
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the {@link CpkInfo} used to encrypt this blob's content on the server.
*
* @return the customer provided key used for encryption.
*/
public CpkInfo getCustomerProvidedKey() {
return customerProvidedKey;
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return accountName;
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Gets the snapshotId for a blob resource
*
* @return A string that represents the snapshotId of the snapshot blob
*/
public String getSnapshotId() {
return this.snapshot;
}
/**
* Determines if a blob is a snapshot
*
* @return A boolean that indicates if a blob is a snapshot
*/
public boolean isSnapshot() {
return this.snapshot != null;
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.exists}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Boolean> exists() {
try {
return existsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Response<Boolean>> existsWithResponse() {
try {
return withContext(this::existsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Boolean>> existsWithResponse(Context context) {
return this.getPropertiesWithResponse(null, context)
.map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true))
.onErrorResume(t -> t instanceof BlobStorageException && ((BlobStorageException) t).getStatusCode() == 404,
t -> {
HttpResponse response = ((BlobStorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false));
});
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second
* is used.
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Duration pollInterval) {
return beginCopy(sourceUrl, null, null, null, null, null, pollInterval);
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Starting a copy operation</strong></p>
* Starting a copy operation and polling on the responses.
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy
*
* <p><strong>Cancelling a copy operation</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrlCancel
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param priority {@link RehydratePriority} for rehydrating the blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP
* Access conditions related to the modification of data. ETag and LastModifiedTime are used to construct
* conditions related to when the blob was changed relative to the given request. The request will fail if the
* specified condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
* @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second
* is used.
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destAccessConditions, Duration pollInterval) {
final Duration interval = pollInterval != null ? pollInterval : Duration.ofSeconds(1);
final ModifiedAccessConditions sourceModifiedCondition = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions()
: sourceModifiedAccessConditions;
final BlobAccessConditions destinationAccessConditions = destAccessConditions == null
? new BlobAccessConditions()
: destAccessConditions;
final SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedCondition.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedCondition.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedCondition.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedCondition.getIfNoneMatch());
return new Poller<>(interval,
response -> {
try {
return onPoll(response);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
},
Mono::empty,
() -> {
try {
return onStart(sourceUrl, metadata, tier, priority, sourceConditions, destinationAccessConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
},
poller -> {
final PollResponse<BlobCopyInfo> response = poller.getLastPollResponse();
if (response == null || response.getValue() == null) {
return Mono.error(logger.logExceptionAsError(
new IllegalArgumentException("Cannot cancel a poll response that never started.")));
}
final String copyIdentifier = response.getValue().getCopyId();
if (!ImplUtils.isNullOrEmpty(copyIdentifier)) {
logger.info("Cancelling copy operation for copy id: {}", copyIdentifier);
return abortCopyFromURL(copyIdentifier).thenReturn(response.getValue());
}
return Mono.empty();
});
}
private Mono<BlobCopyInfo> onStart(String sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, SourceModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destinationAccessConditions) {
URL url;
try {
url = new URL(sourceUrl);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sourceUrl' is not a valid url.", ex));
}
return withContext(
context -> azureBlobStorage.blobs().startCopyFromURLWithRestResponseAsync(null, null, url, null, metadata,
tier, priority, null, sourceModifiedAccessConditions,
destinationAccessConditions.getModifiedAccessConditions(),
destinationAccessConditions.getLeaseAccessConditions(), context))
.map(response -> {
final BlobStartCopyFromURLHeaders headers = response.getDeserializedHeaders();
return new BlobCopyInfo(sourceUrl, headers.getCopyId(), headers.getCopyStatus(),
headers.getETag(), headers.getLastModified(), headers.getErrorCode());
});
}
private Mono<PollResponse<BlobCopyInfo>> onPoll(PollResponse<BlobCopyInfo> pollResponse) {
if (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED) {
return Mono.just(pollResponse);
}
final BlobCopyInfo lastInfo = pollResponse.getValue();
if (lastInfo == null) {
logger.warning("BlobCopyInfo does not exist. Activation operation failed.");
return Mono.just(new PollResponse<>(
OperationStatus.fromString("COPY_START_FAILED", true), null));
}
).onErrorReturn(
new PollResponse<>(OperationStatus.fromString("POLLING_FAILED", true), lastInfo));
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* BlobAccessConditions, Duration)
* @param copyId The id of the copy operation to abort.
* @return A reactive response signalling completion.
*/
public Mono<Void> abortCopyFromURL(String copyId) {
try {
return abortCopyFromURLWithResponse(copyId, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* BlobAccessConditions, Duration)
* @param copyId The id of the copy operation to abort.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId,
LeaseAccessConditions leaseAccessConditions) {
try {
return withContext(context -> abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions,
Context context) {
return this.azureBlobStorage.blobs().abortCopyFromURLWithRestResponseAsync(
null, null, copyId, null, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<String> copyFromURL(String copySource) {
try {
return copyFromURLWithResponse(copySource, null, null, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access
* conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions
* related to when the blob was changed relative to the given request. The request will fail if the specified
* condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<Response<String>> copyFromURLWithResponse(String copySource, Map<String, String> metadata,
AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destAccessConditions) {
try {
return withContext(context -> copyFromURLWithResponse(copySource, metadata, tier,
sourceModifiedAccessConditions, destAccessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<String>> copyFromURLWithResponse(String copySource, Map<String, String> metadata, AccessTier tier,
ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions,
Context context) {
sourceModifiedAccessConditions = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions() : sourceModifiedAccessConditions;
destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions;
SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch());
URL url;
try {
url = new URL(copySource);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new IllegalArgumentException("'copySource' is not a valid url."));
}
return this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync(
null, null, url, null, metadata, tier, null, sourceConditions,
destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(),
context).map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId()));
}
/**
* Reads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or
* {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.download}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob data.
*/
public Flux<ByteBuffer> download() {
try {
return downloadWithResponse(null, null, null, false)
.flatMapMany(Response::getValue);
} catch (RuntimeException ex) {
return fluxError(logger, ex);
}
}
/**
* Reads a range of bytes from a blob. Uploading data must be done from the {@link BlockBlobClient}, {@link
* PageBlobClient}, or {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param range {@link BlobRange}
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return A reactive response containing the blob data.
*/
public Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
try {
return withContext(context -> downloadWithResponse(range, options, accessConditions, rangeGetContentMD5,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
return download(range, accessConditions, rangeGetContentMD5, context)
.map(response -> new SimpleResponse<>(
response.getRawResponse(),
response.body(options).switchIfEmpty(Flux.just(ByteBuffer.wrap(new byte[0])))));
}
/**
* Reads a range of bytes from a blob. The response also includes the blob's properties and metadata. For more
* information, see the <a href="https:
* <p>
* Note that the response body has reliable download functionality built in, meaning that a failed download stream
* will be automatically retried. This behavior may be configured with {@link ReliableDownloadOptions}.
*
* @param range {@link BlobRange}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return Emits the successful response.
*/
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5) {
return withContext(context -> download(range, accessConditions, rangeGetContentMD5, context));
}
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5, Context context) {
range = range == null ? new BlobRange(0) : range;
Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null;
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
HttpGetterInfo info = new HttpGetterInfo()
.setOffset(range.getOffset())
.setCount(range.getCount())
.setETag(accessConditions.getModifiedAccessConditions().getIfMatch());
return this.azureBlobStorage.blobs().downloadWithRestResponseAsync(
null, null, snapshot, null, range.toHeaderValue(), getMD5, null, null,
accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> {
info.setETag(response.getDeserializedHeaders().getETag());
return new DownloadAsyncResponse(response, info,
newInfo ->
this.download(new BlobRange(newInfo.getOffset(), newInfo.getCount()),
new BlobAccessConditions().setModifiedAccessConditions(
new ModifiedAccessConditions().setIfMatch(info.getETag())), false, context));
});
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @return An empty response
*/
public Mono<BlobProperties> downloadToFile(String filePath) {
try {
return downloadToFileWithResponse(filePath, null, null,
null, null, false).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra
* call, provide the {@link BlobRange} parameter.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @param range {@link BlobRange}
* @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel
* transfers parameter is ignored.
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return An empty response
* @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB.
* @throws UncheckedIOException If an I/O error occurs.
*/
public Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
try {
return withContext(context -> downloadToFileWithResponse(filePath, range, parallelTransferOptions, options,
accessConditions, rangeGetContentMD5, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
final ParallelTransferOptions finalParallelTransferOptions = parallelTransferOptions == null
? new ParallelTransferOptions()
: parallelTransferOptions;
ProgressReceiver progressReceiver = finalParallelTransferOptions.getProgressReceiver();
AtomicLong totalProgress = new AtomicLong(0);
Lock progressLock = new ReentrantLock();
return Mono.using(() -> downloadToFileResourceSupplier(filePath),
channel -> getPropertiesWithResponse(accessConditions)
.flatMap(response -> processInRange(channel, response,
range, finalParallelTransferOptions.getBlockSize(), options, accessConditions, rangeGetContentMD5,
context, totalProgress, progressLock, progressReceiver)), this::downloadToFileCleanup);
}
private Mono<Response<BlobProperties>> processInRange(AsynchronousFileChannel channel,
Response<BlobProperties> blobPropertiesResponse, BlobRange range, Integer blockSize,
ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5,
Context context, AtomicLong totalProgress, Lock progressLock, ProgressReceiver progressReceiver) {
return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new BlobRange(0,
blobPropertiesResponse.getValue().getBlobSize()))).flatMapMany(rg ->
Flux.fromIterable(sliceBlobRange(rg, blockSize)))
.flatMap(chunk -> this.download(chunk, accessConditions, rangeGetContentMD5, context)
.subscribeOn(Schedulers.elastic())
.flatMap(dar -> {
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
dar.body(options), progressReceiver, progressLock, totalProgress);
return FluxUtil.writeFile(progressData, channel,
chunk.getOffset() - ((range == null) ? 0 : range.getOffset()));
})).then(Mono.just(blobPropertiesResponse));
}
private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath) {
try {
return AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private void downloadToFileCleanup(AsynchronousFileChannel channel) {
try {
channel.close();
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private List<BlobRange> sliceBlobRange(BlobRange blobRange, Integer blockSize) {
if (blockSize == null) {
blockSize = BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE;
}
long offset = blobRange.getOffset();
long length = blobRange.getCount();
List<BlobRange> chunks = new ArrayList<>();
for (long pos = offset; pos < offset + length; pos += blockSize) {
long count = blockSize;
if (pos + count > offset + length) {
count = offset + length - pos;
}
chunks.add(new BlobRange(pos, count));
}
return chunks;
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> delete() {
try {
return deleteWithResponse(null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include}
* will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being
* deleted, you must pass null.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().deleteWithRestResponseAsync(
null, null, snapshot, null, deleteBlobSnapshotOptions,
null, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(),
context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<BlobProperties> getProperties() {
try {
return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions) {
try {
return withContext(context -> getPropertiesWithResponse(accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().getPropertiesWithRestResponseAsync(
null, null, snapshot, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, new BlobProperties(rb.getDeserializedHeaders())));
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeaders
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHttpHeaders}
* @return A reactive response signalling completion.
*/
public Mono<Void> setHttpHeaders(BlobHttpHeaders headers) {
try {
return setHttpHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeadersWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHttpHeaders}
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setHttpHeadersWithResponse(BlobHttpHeaders headers,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> setHttpHeadersWithResponse(headers, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setHttpHeadersWithResponse(BlobHttpHeaders headers, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setHTTPHeadersWithRestResponseAsync(
null, null, null, null, headers,
accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @return A reactive response signalling completion.
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
try {
return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> setMetadataWithResponse(metadata, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setMetadataWithRestResponseAsync(
null, null, null, metadata, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<BlobAsyncClientBase> createSnapshot() {
try {
return createSnapshotWithResponse(null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob snapshot.
* @param accessConditions {@link BlobAccessConditions}
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> createSnapshotWithResponse(metadata, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().createSnapshotWithRestResponseAsync(
null, null, null, metadata, null, customerProvidedKey, accessConditions.getModifiedAccessConditions(),
accessConditions.getLeaseAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.getDeserializedHeaders().getSnapshot())));
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Void> setAccessTier(AccessTier tier) {
try {
return setAccessTierWithResponse(tier, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @param priority Optional priority to set for re-hydrating blobs.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Response<Void>> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions) {
try {
return withContext(context -> setTierWithResponse(tier, priority, leaseAccessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions, Context context) {
StorageImplUtils.assertNotNull("tier", tier);
return this.azureBlobStorage.blobs().setTierWithRestResponseAsync(
null, null, tier, null, priority, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> undelete() {
try {
return undeleteWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> undeleteWithResponse() {
try {
return withContext(this::undeleteWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> undeleteWithResponse(Context context) {
return this.azureBlobStorage.blobs().undeleteWithRestResponseAsync(null,
null, context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
return this.azureBlobStorage.blobs().getAccountInfoWithRestResponseAsync(null, null, context)
.map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.getDeserializedHeaders())));
}
} |
Should these be `CopyStatusType.SUCCESS`? | private Mono<PollResponse<BlobCopyInfo>> onPoll(PollResponse<BlobCopyInfo> pollResponse) {
if (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED) {
return Mono.just(pollResponse);
}
final BlobCopyInfo lastInfo = pollResponse.getValue();
if (lastInfo == null) {
logger.warning("BlobCopyInfo does not exist. Activation operation failed.");
return Mono.just(new PollResponse<>(
OperationStatus.fromString("COPY_START_FAILED", true), null));
}
return getProperties().map(response -> {
final CopyStatusType status = response.getCopyStatus();
final BlobCopyInfo result = new BlobCopyInfo(response.getCopySource(), response.getCopyId(), status,
response.getETag(), response.getCopyCompletionTime(), response.getCopyStatusDescription());
OperationStatus operationStatus;
switch (status) {
case SUCCESS:
operationStatus = OperationStatus.SUCCESSFULLY_COMPLETED;
break;
case FAILED:
operationStatus = OperationStatus.NOT_STARTED;
break;
case ABORTED:
operationStatus = OperationStatus.USER_CANCELLED;
break;
case PENDING:
operationStatus = OperationStatus.IN_PROGRESS;
break;
default:
throw Exceptions.propagate(logger.logExceptionAsError(new IllegalArgumentException(
"CopyStatusType is not supported. Status: " + status)));
}
return new PollResponse<>(operationStatus, result);
}).onErrorReturn(
new PollResponse<>(OperationStatus.fromString("POLLING_FAILED", true), lastInfo));
} | "CopyStatusType is not supported. Status: " + status))); | return getProperties().map(response -> {
final CopyStatusType status = response.getCopyStatus();
final BlobCopyInfo result = new BlobCopyInfo(response.getCopySource(), response.getCopyId(), status,
response.getETag(), response.getCopyCompletionTime(), response.getCopyStatusDescription());
OperationStatus operationStatus;
switch (status) {
case SUCCESS:
operationStatus = OperationStatus.SUCCESSFULLY_COMPLETED;
break;
case FAILED:
operationStatus = OperationStatus.FAILED;
break;
case ABORTED:
operationStatus = OperationStatus.USER_CANCELLED;
break;
case PENDING:
operationStatus = OperationStatus.IN_PROGRESS;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"CopyStatusType is not supported. Status: " + status));
}
return new PollResponse<>(operationStatus, result);
} | class BlobAsyncClientBase {
private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB;
private final ClientLogger logger = new ClientLogger(BlobAsyncClientBase.class);
protected final AzureBlobStorageImpl azureBlobStorage;
private final String snapshot;
private final CpkInfo customerProvidedKey;
protected final String accountName;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param azureBlobStorage the API client for blob storage
* @param snapshot Optional. The snapshot identifier for the snapshot blob.
* @param customerProvidedKey Optional. Customer provided key used during encryption of the blob's data on the
* server.
* @param accountName The account name for storage account.
*/
protected BlobAsyncClientBase(AzureBlobStorageImpl azureBlobStorage, String snapshot,
CpkInfo customerProvidedKey, String accountName) {
this.azureBlobStorage = azureBlobStorage;
this.snapshot = snapshot;
this.customerProvidedKey = customerProvidedKey;
this.accountName = accountName;
}
/**
* Creates a new {@link BlobAsyncClientBase} linked to the {@code snapshot} of this blob resource.
*
* @param snapshot the identifier for a specific snapshot of this blob
* @return a {@link BlobAsyncClientBase} used to interact with the specific snapshot.
*/
public BlobAsyncClientBase getSnapshotClient(String snapshot) {
return new BlobAsyncClientBase(new AzureBlobStorageBuilder()
.url(getBlobUrl())
.pipeline(azureBlobStorage.getHttpPipeline())
.build(), snapshot, customerProvidedKey, accountName);
}
/**
* Gets the URL of the blob represented by this client.
*
* @return the URL.
*/
public String getBlobUrl() {
if (!this.isSnapshot()) {
return azureBlobStorage.getUrl();
} else {
if (azureBlobStorage.getUrl().contains("?")) {
return String.format("%s&snapshot=%s", azureBlobStorage.getUrl(), snapshot);
} else {
return String.format("%s?snapshot=%s", azureBlobStorage.getUrl(), snapshot);
}
}
}
/**
* Get the container name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName}
*
* @return The name of the container.
*/
public final String getContainerName() {
return BlobUrlParts.parse(this.azureBlobStorage.getUrl(), logger).getBlobContainerName();
}
/**
* Get the blob name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName}
*
* @return The name of the blob.
*/
public final String getBlobName() {
return BlobUrlParts.parse(this.azureBlobStorage.getUrl(), logger).getBlobName();
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the {@link CpkInfo} used to encrypt this blob's content on the server.
*
* @return the customer provided key used for encryption.
*/
public CpkInfo getCustomerProvidedKey() {
return customerProvidedKey;
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Gets the snapshotId for a blob resource
*
* @return A string that represents the snapshotId of the snapshot blob
*/
public String getSnapshotId() {
return this.snapshot;
}
/**
* Determines if a blob is a snapshot
*
* @return A boolean that indicates if a blob is a snapshot
*/
public boolean isSnapshot() {
return this.snapshot != null;
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.exists}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Boolean> exists() {
return existsWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Response<Boolean>> existsWithResponse() {
return withContext(this::existsWithResponse);
}
Mono<Response<Boolean>> existsWithResponse(Context context) {
return this.getPropertiesWithResponse(null, context)
.map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true))
.onErrorResume(t -> t instanceof StorageException && ((StorageException) t).getStatusCode() == 404, t -> {
HttpResponse response = ((StorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false));
});
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrl
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
*
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopyFromUrl(URL sourceUrl) {
return beginCopyFromUrl(sourceUrl, null, null, null, null, null);
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrl
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param priority {@link RehydratePriority} for rehydrating the blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP
* Access conditions related to the modification of data. ETag and LastModifiedTime are used to construct
* conditions related to when the blob was changed relative to the given request. The request will fail if the
* specified condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
*
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopyFromUrl(URL sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destAccessConditions) {
final ModifiedAccessConditions sourceModifiedCondition = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions()
: sourceModifiedAccessConditions;
final BlobAccessConditions destinationAccessConditions = destAccessConditions == null
? new BlobAccessConditions()
: destAccessConditions;
final SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedCondition.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedCondition.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedCondition.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedCondition.getIfNoneMatch());
return new Poller<>(
Duration.ofSeconds(1),
this::onPoll,
Mono::empty,
() -> onStart(sourceUrl, metadata, tier, priority, sourceConditions, destinationAccessConditions),
poller -> {
final PollResponse<BlobCopyInfo> response = poller.getLastPollResponse();
if (response == null || response.getValue() == null) {
return Mono.error(logger.logExceptionAsError(
new IllegalArgumentException("Cannot cancel a poll response that never started.")));
}
final String copyIdentifier = response.getValue().getCopyId();
if (!ImplUtils.isNullOrEmpty(copyIdentifier)) {
logger.info("Cancelling copy operation for copy id: {}", copyIdentifier);
return abortCopyFromURL(copyIdentifier).thenReturn(response.getValue());
}
return Mono.empty();
});
}
private Mono<BlobCopyInfo> onStart(URL sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, SourceModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destinationAccessConditions) {
return withContext(
context -> azureBlobStorage.blobs().startCopyFromURLWithRestResponseAsync(null, null,
sourceUrl, null, metadata, tier, priority, null, sourceModifiedAccessConditions,
destinationAccessConditions.getModifiedAccessConditions(),
destinationAccessConditions.getLeaseAccessConditions(), context))
.map(response -> {
final BlobStartCopyFromURLHeaders headers = response.getDeserializedHeaders();
return new BlobCopyInfo(sourceUrl.toString(), headers.getCopyId(), headers.getCopyStatus(),
headers.getETag(), headers.getLastModified(), headers.getErrorCode());
});
}
private Mono<PollResponse<BlobCopyInfo>> onPoll(PollResponse<BlobCopyInfo> pollResponse) {
if (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED) {
return Mono.just(pollResponse);
}
final BlobCopyInfo lastInfo = pollResponse.getValue();
if (lastInfo == null) {
logger.warning("BlobCopyInfo does not exist. Activation operation failed.");
return Mono.just(new PollResponse<>(
OperationStatus.fromString("COPY_START_FAILED", true), null));
}
).onErrorReturn(
new PollResponse<>(OperationStatus.fromString("POLLING_FAILED", true), lastInfo));
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* @param copyId The id of the copy operation to abort.
* @return A reactive response signalling completion.
*/
public Mono<Void> abortCopyFromURL(String copyId) {
return abortCopyFromURLWithResponse(copyId, null).flatMap(FluxUtil::toMono);
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* @param copyId The id of the copy operation to abort.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId,
LeaseAccessConditions leaseAccessConditions) {
return withContext(context -> abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context));
}
Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions,
Context context) {
return this.azureBlobStorage.blobs().abortCopyFromURLWithRestResponseAsync(
null, null, copyId, null, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<String> copyFromURL(URL copySource) {
return copyFromURLWithResponse(copySource, null, null, null, null).flatMap(FluxUtil::toMono);
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access
* conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions
* related to when the blob was changed relative to the given request. The request will fail if the specified
* condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier,
ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions) {
return withContext(context -> copyFromURLWithResponse(copySource, metadata, tier,
sourceModifiedAccessConditions, destAccessConditions, context));
}
Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier,
ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions,
Context context) {
sourceModifiedAccessConditions = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions() : sourceModifiedAccessConditions;
destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions;
SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch());
return this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync(
null, null, copySource, null, metadata, tier, null, sourceConditions,
destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(),
context).map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId()));
}
/**
* Reads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or
* {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.download}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob data.
*/
public Flux<ByteBuffer> download() {
return downloadWithResponse(null, null, null, false)
.flatMapMany(Response::getValue);
}
/**
* Reads a range of bytes from a blob. Uploading data must be done from the {@link BlockBlobClient}, {@link
* PageBlobClient}, or {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param range {@link BlobRange}
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return A reactive response containing the blob data.
*/
public Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
return withContext(context -> downloadWithResponse(range, options, accessConditions, rangeGetContentMD5,
context));
}
Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
return download(range, accessConditions, rangeGetContentMD5, context)
.map(response -> new SimpleResponse<>(
response.getRawResponse(),
response.body(options).switchIfEmpty(Flux.just(ByteBuffer.wrap(new byte[0])))));
}
/**
* Reads a range of bytes from a blob. The response also includes the blob's properties and metadata. For more
* information, see the <a href="https:
* <p>
* Note that the response body has reliable download functionality built in, meaning that a failed download stream
* will be automatically retried. This behavior may be configured with {@link ReliableDownloadOptions}.
*
* @param range {@link BlobRange}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return Emits the successful response.
*/
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5) {
return withContext(context -> download(range, accessConditions, rangeGetContentMD5, context));
}
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5, Context context) {
range = range == null ? new BlobRange(0) : range;
Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null;
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
HttpGetterInfo info = new HttpGetterInfo()
.setOffset(range.getOffset())
.setCount(range.getCount())
.setETag(accessConditions.getModifiedAccessConditions().getIfMatch());
return this.azureBlobStorage.blobs().downloadWithRestResponseAsync(
null, null, snapshot, null, range.toHeaderValue(), getMD5, null, null,
accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> {
info.setETag(response.getDeserializedHeaders().getETag());
return new DownloadAsyncResponse(response, info,
newInfo ->
this.download(new BlobRange(newInfo.getOffset(), newInfo.getCount()),
new BlobAccessConditions().setModifiedAccessConditions(
new ModifiedAccessConditions().setIfMatch(info.getETag())), false, context));
});
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @return An empty response
*/
public Mono<BlobProperties> downloadToFile(String filePath) {
return downloadToFileWithResponse(filePath, null, null,
null, null, false).flatMap(FluxUtil::toMono);
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra
* call, provide the {@link BlobRange} parameter.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @param range {@link BlobRange}
* @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel
* transfers parameter is ignored.
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return An empty response
* @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB.
* @throws UncheckedIOException If an I/O error occurs.
*/
public Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
return withContext(context -> downloadToFileWithResponse(filePath, range, parallelTransferOptions, options,
accessConditions, rangeGetContentMD5, context));
}
Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
final ParallelTransferOptions finalParallelTransferOptions = parallelTransferOptions == null
? new ParallelTransferOptions()
: parallelTransferOptions;
ProgressReceiver progressReceiver = finalParallelTransferOptions.getProgressReceiver();
AtomicLong totalProgress = new AtomicLong(0);
Lock progressLock = new ReentrantLock();
return Mono.using(() -> downloadToFileResourceSupplier(filePath),
channel -> getPropertiesWithResponse(accessConditions)
.flatMap(response -> processInRange(channel, response,
range, finalParallelTransferOptions.getBlockSize(), options, accessConditions, rangeGetContentMD5,
context, totalProgress, progressLock, progressReceiver)), this::downloadToFileCleanup);
}
private Mono<Response<BlobProperties>> processInRange(AsynchronousFileChannel channel,
Response<BlobProperties> blobPropertiesResponse, BlobRange range, Integer blockSize,
ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5,
Context context, AtomicLong totalProgress, Lock progressLock, ProgressReceiver progressReceiver) {
return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new BlobRange(0,
blobPropertiesResponse.getValue().getBlobSize()))).flatMapMany(rg ->
Flux.fromIterable(sliceBlobRange(rg, blockSize)))
.flatMap(chunk -> this.download(chunk, accessConditions, rangeGetContentMD5, context)
.subscribeOn(Schedulers.elastic())
.flatMap(dar -> {
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
dar.body(options), progressReceiver, progressLock, totalProgress);
return FluxUtil.writeFile(progressData, channel,
chunk.getOffset() - ((range == null) ? 0 : range.getOffset()));
})).then(Mono.just(blobPropertiesResponse));
}
private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath) {
try {
return AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private void downloadToFileCleanup(AsynchronousFileChannel channel) {
try {
channel.close();
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private List<BlobRange> sliceBlobRange(BlobRange blobRange, Integer blockSize) {
if (blockSize == null) {
blockSize = BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE;
}
long offset = blobRange.getOffset();
long length = blobRange.getCount();
List<BlobRange> chunks = new ArrayList<>();
for (long pos = offset; pos < offset + length; pos += blockSize) {
long count = blockSize;
if (pos + count > offset + length) {
count = offset + length - pos;
}
chunks.add(new BlobRange(pos, count));
}
return chunks;
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> delete() {
return deleteWithResponse(null, null).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include}
* will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being
* deleted, you must pass null.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions) {
return withContext(context -> deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context));
}
Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().deleteWithRestResponseAsync(
null, null, snapshot, null, deleteBlobSnapshotOptions,
null, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(),
context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<BlobProperties> getProperties() {
return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono);
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions) {
return withContext(context -> getPropertiesWithResponse(accessConditions, context));
}
Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().getPropertiesWithRestResponseAsync(
null, null, snapshot, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, new BlobProperties(rb.getDeserializedHeaders())));
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeaders
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHTTPHeaders}
* @return A reactive response signalling completion.
*/
public Mono<Void> setHTTPHeaders(BlobHTTPHeaders headers) {
return setHTTPHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono);
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeadersWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHTTPHeaders}
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers,
BlobAccessConditions accessConditions) {
return withContext(context -> setHTTPHeadersWithResponse(headers, accessConditions, context));
}
Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setHTTPHeadersWithRestResponseAsync(
null, null, null, null, headers,
accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @return A reactive response signalling completion.
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono);
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
return withContext(context -> setMetadataWithResponse(metadata, accessConditions, context));
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setMetadataWithRestResponseAsync(
null, null, null, metadata, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<BlobAsyncClientBase> createSnapshot() {
return createSnapshotWithResponse(null, null).flatMap(FluxUtil::toMono);
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob snapshot.
* @param accessConditions {@link BlobAccessConditions}
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
return withContext(context -> createSnapshotWithResponse(metadata, accessConditions, context));
}
Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().createSnapshotWithRestResponseAsync(
null, null, null, metadata, null, customerProvidedKey, accessConditions.getModifiedAccessConditions(),
accessConditions.getLeaseAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.getDeserializedHeaders().getSnapshot())));
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Void> setAccessTier(AccessTier tier) {
return setAccessTierWithResponse(tier, null, null).flatMap(FluxUtil::toMono);
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @param priority Optional priority to set for re-hydrating blobs.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Response<Void>> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions) {
return withContext(context -> setTierWithResponse(tier, priority, leaseAccessConditions, context));
}
Mono<Response<Void>> setTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions, Context context) {
Utility.assertNotNull("tier", tier);
return this.azureBlobStorage.blobs().setTierWithRestResponseAsync(
null, null, tier, null, priority, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> undelete() {
return undeleteWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> undeleteWithResponse() {
return withContext(this::undeleteWithResponse);
}
Mono<Response<Void>> undeleteWithResponse(Context context) {
return this.azureBlobStorage.blobs().undeleteWithRestResponseAsync(null,
null, context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<StorageAccountInfo> getAccountInfo() {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
return withContext(this::getAccountInfoWithResponse);
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
return this.azureBlobStorage.blobs().getAccountInfoWithRestResponseAsync(null, null, context)
.map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.getDeserializedHeaders())));
}
} | class BlobAsyncClientBase {
private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB;
private final ClientLogger logger = new ClientLogger(BlobAsyncClientBase.class);
protected final AzureBlobStorageImpl azureBlobStorage;
private final String snapshot;
private final CpkInfo customerProvidedKey;
protected final String accountName;
protected final String containerName;
protected final String blobName;
protected final BlobServiceVersion serviceVersion;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param containerName The container name.
* @param blobName The blob name.
* @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
*/
protected BlobAsyncClientBase(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion,
String accountName, String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey) {
this.azureBlobStorage = new AzureBlobStorageBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.build();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.containerName = containerName;
this.blobName = blobName;
this.snapshot = snapshot;
this.customerProvidedKey = customerProvidedKey;
}
/**
* Creates a new {@link BlobAsyncClientBase} linked to the {@code snapshot} of this blob resource.
*
* @param snapshot the identifier for a specific snapshot of this blob
* @return a {@link BlobAsyncClientBase} used to interact with the specific snapshot.
*/
public BlobAsyncClientBase getSnapshotClient(String snapshot) {
return new BlobAsyncClientBase(getHttpPipeline(), getBlobUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), snapshot, getCustomerProvidedKey());
}
/**
* Gets the URL of the blob represented by this client.
*
* @return the URL.
*/
public String getBlobUrl() {
if (!this.isSnapshot()) {
return azureBlobStorage.getUrl();
} else {
if (azureBlobStorage.getUrl().contains("?")) {
return String.format("%s&snapshot=%s", azureBlobStorage.getUrl(), snapshot);
} else {
return String.format("%s?snapshot=%s", azureBlobStorage.getUrl(), snapshot);
}
}
}
/**
* Get the container name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName}
*
* @return The name of the container.
*/
public final String getContainerName() {
return containerName;
}
/**
* Get the blob name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName}
*
* @return The name of the blob.
*/
public final String getBlobName() {
return blobName;
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the {@link CpkInfo} used to encrypt this blob's content on the server.
*
* @return the customer provided key used for encryption.
*/
public CpkInfo getCustomerProvidedKey() {
return customerProvidedKey;
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return accountName;
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Gets the snapshotId for a blob resource
*
* @return A string that represents the snapshotId of the snapshot blob
*/
public String getSnapshotId() {
return this.snapshot;
}
/**
* Determines if a blob is a snapshot
*
* @return A boolean that indicates if a blob is a snapshot
*/
public boolean isSnapshot() {
return this.snapshot != null;
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.exists}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Boolean> exists() {
try {
return existsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Response<Boolean>> existsWithResponse() {
try {
return withContext(this::existsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Boolean>> existsWithResponse(Context context) {
return this.getPropertiesWithResponse(null, context)
.map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true))
.onErrorResume(t -> t instanceof BlobStorageException && ((BlobStorageException) t).getStatusCode() == 404,
t -> {
HttpResponse response = ((BlobStorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false));
});
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second
* is used.
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Duration pollInterval) {
return beginCopy(sourceUrl, null, null, null, null, null, pollInterval);
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Starting a copy operation</strong></p>
* Starting a copy operation and polling on the responses.
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy
*
* <p><strong>Cancelling a copy operation</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrlCancel
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param priority {@link RehydratePriority} for rehydrating the blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP
* Access conditions related to the modification of data. ETag and LastModifiedTime are used to construct
* conditions related to when the blob was changed relative to the given request. The request will fail if the
* specified condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
* @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second
* is used.
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destAccessConditions, Duration pollInterval) {
final Duration interval = pollInterval != null ? pollInterval : Duration.ofSeconds(1);
final ModifiedAccessConditions sourceModifiedCondition = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions()
: sourceModifiedAccessConditions;
final BlobAccessConditions destinationAccessConditions = destAccessConditions == null
? new BlobAccessConditions()
: destAccessConditions;
final SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedCondition.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedCondition.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedCondition.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedCondition.getIfNoneMatch());
return new Poller<>(interval,
response -> {
try {
return onPoll(response);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
},
Mono::empty,
() -> {
try {
return onStart(sourceUrl, metadata, tier, priority, sourceConditions, destinationAccessConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
},
poller -> {
final PollResponse<BlobCopyInfo> response = poller.getLastPollResponse();
if (response == null || response.getValue() == null) {
return Mono.error(logger.logExceptionAsError(
new IllegalArgumentException("Cannot cancel a poll response that never started.")));
}
final String copyIdentifier = response.getValue().getCopyId();
if (!ImplUtils.isNullOrEmpty(copyIdentifier)) {
logger.info("Cancelling copy operation for copy id: {}", copyIdentifier);
return abortCopyFromURL(copyIdentifier).thenReturn(response.getValue());
}
return Mono.empty();
});
}
private Mono<BlobCopyInfo> onStart(String sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, SourceModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destinationAccessConditions) {
URL url;
try {
url = new URL(sourceUrl);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sourceUrl' is not a valid url.", ex));
}
return withContext(
context -> azureBlobStorage.blobs().startCopyFromURLWithRestResponseAsync(null, null, url, null, metadata,
tier, priority, null, sourceModifiedAccessConditions,
destinationAccessConditions.getModifiedAccessConditions(),
destinationAccessConditions.getLeaseAccessConditions(), context))
.map(response -> {
final BlobStartCopyFromURLHeaders headers = response.getDeserializedHeaders();
return new BlobCopyInfo(sourceUrl, headers.getCopyId(), headers.getCopyStatus(),
headers.getETag(), headers.getLastModified(), headers.getErrorCode());
});
}
private Mono<PollResponse<BlobCopyInfo>> onPoll(PollResponse<BlobCopyInfo> pollResponse) {
if (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED) {
return Mono.just(pollResponse);
}
final BlobCopyInfo lastInfo = pollResponse.getValue();
if (lastInfo == null) {
logger.warning("BlobCopyInfo does not exist. Activation operation failed.");
return Mono.just(new PollResponse<>(
OperationStatus.fromString("COPY_START_FAILED", true), null));
}
).onErrorReturn(
new PollResponse<>(OperationStatus.fromString("POLLING_FAILED", true), lastInfo));
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* BlobAccessConditions, Duration)
* @param copyId The id of the copy operation to abort.
* @return A reactive response signalling completion.
*/
public Mono<Void> abortCopyFromURL(String copyId) {
try {
return abortCopyFromURLWithResponse(copyId, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* BlobAccessConditions, Duration)
* @param copyId The id of the copy operation to abort.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId,
LeaseAccessConditions leaseAccessConditions) {
try {
return withContext(context -> abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions,
Context context) {
return this.azureBlobStorage.blobs().abortCopyFromURLWithRestResponseAsync(
null, null, copyId, null, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<String> copyFromURL(String copySource) {
try {
return copyFromURLWithResponse(copySource, null, null, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access
* conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions
* related to when the blob was changed relative to the given request. The request will fail if the specified
* condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<Response<String>> copyFromURLWithResponse(String copySource, Map<String, String> metadata,
AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destAccessConditions) {
try {
return withContext(context -> copyFromURLWithResponse(copySource, metadata, tier,
sourceModifiedAccessConditions, destAccessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<String>> copyFromURLWithResponse(String copySource, Map<String, String> metadata, AccessTier tier,
ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions,
Context context) {
sourceModifiedAccessConditions = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions() : sourceModifiedAccessConditions;
destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions;
SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch());
URL url;
try {
url = new URL(copySource);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new IllegalArgumentException("'copySource' is not a valid url."));
}
return this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync(
null, null, url, null, metadata, tier, null, sourceConditions,
destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(),
context).map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId()));
}
/**
* Reads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or
* {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.download}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob data.
*/
public Flux<ByteBuffer> download() {
try {
return downloadWithResponse(null, null, null, false)
.flatMapMany(Response::getValue);
} catch (RuntimeException ex) {
return fluxError(logger, ex);
}
}
/**
* Reads a range of bytes from a blob. Uploading data must be done from the {@link BlockBlobClient}, {@link
* PageBlobClient}, or {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param range {@link BlobRange}
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return A reactive response containing the blob data.
*/
public Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
try {
return withContext(context -> downloadWithResponse(range, options, accessConditions, rangeGetContentMD5,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
return download(range, accessConditions, rangeGetContentMD5, context)
.map(response -> new SimpleResponse<>(
response.getRawResponse(),
response.body(options).switchIfEmpty(Flux.just(ByteBuffer.wrap(new byte[0])))));
}
/**
* Reads a range of bytes from a blob. The response also includes the blob's properties and metadata. For more
* information, see the <a href="https:
* <p>
* Note that the response body has reliable download functionality built in, meaning that a failed download stream
* will be automatically retried. This behavior may be configured with {@link ReliableDownloadOptions}.
*
* @param range {@link BlobRange}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return Emits the successful response.
*/
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5) {
return withContext(context -> download(range, accessConditions, rangeGetContentMD5, context));
}
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5, Context context) {
range = range == null ? new BlobRange(0) : range;
Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null;
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
HttpGetterInfo info = new HttpGetterInfo()
.setOffset(range.getOffset())
.setCount(range.getCount())
.setETag(accessConditions.getModifiedAccessConditions().getIfMatch());
return this.azureBlobStorage.blobs().downloadWithRestResponseAsync(
null, null, snapshot, null, range.toHeaderValue(), getMD5, null, null,
accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> {
info.setETag(response.getDeserializedHeaders().getETag());
return new DownloadAsyncResponse(response, info,
newInfo ->
this.download(new BlobRange(newInfo.getOffset(), newInfo.getCount()),
new BlobAccessConditions().setModifiedAccessConditions(
new ModifiedAccessConditions().setIfMatch(info.getETag())), false, context));
});
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @return An empty response
*/
public Mono<BlobProperties> downloadToFile(String filePath) {
try {
return downloadToFileWithResponse(filePath, null, null,
null, null, false).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra
* call, provide the {@link BlobRange} parameter.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @param range {@link BlobRange}
* @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel
* transfers parameter is ignored.
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return An empty response
* @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB.
* @throws UncheckedIOException If an I/O error occurs.
*/
public Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
try {
return withContext(context -> downloadToFileWithResponse(filePath, range, parallelTransferOptions, options,
accessConditions, rangeGetContentMD5, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
final ParallelTransferOptions finalParallelTransferOptions = parallelTransferOptions == null
? new ParallelTransferOptions()
: parallelTransferOptions;
ProgressReceiver progressReceiver = finalParallelTransferOptions.getProgressReceiver();
AtomicLong totalProgress = new AtomicLong(0);
Lock progressLock = new ReentrantLock();
return Mono.using(() -> downloadToFileResourceSupplier(filePath),
channel -> getPropertiesWithResponse(accessConditions)
.flatMap(response -> processInRange(channel, response,
range, finalParallelTransferOptions.getBlockSize(), options, accessConditions, rangeGetContentMD5,
context, totalProgress, progressLock, progressReceiver)), this::downloadToFileCleanup);
}
private Mono<Response<BlobProperties>> processInRange(AsynchronousFileChannel channel,
Response<BlobProperties> blobPropertiesResponse, BlobRange range, Integer blockSize,
ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5,
Context context, AtomicLong totalProgress, Lock progressLock, ProgressReceiver progressReceiver) {
return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new BlobRange(0,
blobPropertiesResponse.getValue().getBlobSize()))).flatMapMany(rg ->
Flux.fromIterable(sliceBlobRange(rg, blockSize)))
.flatMap(chunk -> this.download(chunk, accessConditions, rangeGetContentMD5, context)
.subscribeOn(Schedulers.elastic())
.flatMap(dar -> {
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
dar.body(options), progressReceiver, progressLock, totalProgress);
return FluxUtil.writeFile(progressData, channel,
chunk.getOffset() - ((range == null) ? 0 : range.getOffset()));
})).then(Mono.just(blobPropertiesResponse));
}
private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath) {
try {
return AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private void downloadToFileCleanup(AsynchronousFileChannel channel) {
try {
channel.close();
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private List<BlobRange> sliceBlobRange(BlobRange blobRange, Integer blockSize) {
if (blockSize == null) {
blockSize = BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE;
}
long offset = blobRange.getOffset();
long length = blobRange.getCount();
List<BlobRange> chunks = new ArrayList<>();
for (long pos = offset; pos < offset + length; pos += blockSize) {
long count = blockSize;
if (pos + count > offset + length) {
count = offset + length - pos;
}
chunks.add(new BlobRange(pos, count));
}
return chunks;
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> delete() {
try {
return deleteWithResponse(null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include}
* will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being
* deleted, you must pass null.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().deleteWithRestResponseAsync(
null, null, snapshot, null, deleteBlobSnapshotOptions,
null, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(),
context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<BlobProperties> getProperties() {
try {
return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions) {
try {
return withContext(context -> getPropertiesWithResponse(accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().getPropertiesWithRestResponseAsync(
null, null, snapshot, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, new BlobProperties(rb.getDeserializedHeaders())));
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeaders
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHttpHeaders}
* @return A reactive response signalling completion.
*/
public Mono<Void> setHttpHeaders(BlobHttpHeaders headers) {
try {
return setHttpHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeadersWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHttpHeaders}
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setHttpHeadersWithResponse(BlobHttpHeaders headers,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> setHttpHeadersWithResponse(headers, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setHttpHeadersWithResponse(BlobHttpHeaders headers, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setHTTPHeadersWithRestResponseAsync(
null, null, null, null, headers,
accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @return A reactive response signalling completion.
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
try {
return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> setMetadataWithResponse(metadata, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setMetadataWithRestResponseAsync(
null, null, null, metadata, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<BlobAsyncClientBase> createSnapshot() {
try {
return createSnapshotWithResponse(null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob snapshot.
* @param accessConditions {@link BlobAccessConditions}
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> createSnapshotWithResponse(metadata, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().createSnapshotWithRestResponseAsync(
null, null, null, metadata, null, customerProvidedKey, accessConditions.getModifiedAccessConditions(),
accessConditions.getLeaseAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.getDeserializedHeaders().getSnapshot())));
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Void> setAccessTier(AccessTier tier) {
try {
return setAccessTierWithResponse(tier, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @param priority Optional priority to set for re-hydrating blobs.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Response<Void>> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions) {
try {
return withContext(context -> setTierWithResponse(tier, priority, leaseAccessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions, Context context) {
StorageImplUtils.assertNotNull("tier", tier);
return this.azureBlobStorage.blobs().setTierWithRestResponseAsync(
null, null, tier, null, priority, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> undelete() {
try {
return undeleteWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> undeleteWithResponse() {
try {
return withContext(this::undeleteWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> undeleteWithResponse(Context context) {
return this.azureBlobStorage.blobs().undeleteWithRestResponseAsync(null,
null, context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
return this.azureBlobStorage.blobs().getAccountInfoWithRestResponseAsync(null, null, context)
.map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.getDeserializedHeaders())));
}
} |
I added a static import for CopyStatusType, so it doesn't need it. | private Mono<PollResponse<BlobCopyInfo>> onPoll(PollResponse<BlobCopyInfo> pollResponse) {
if (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED) {
return Mono.just(pollResponse);
}
final BlobCopyInfo lastInfo = pollResponse.getValue();
if (lastInfo == null) {
logger.warning("BlobCopyInfo does not exist. Activation operation failed.");
return Mono.just(new PollResponse<>(
OperationStatus.fromString("COPY_START_FAILED", true), null));
}
return getProperties().map(response -> {
final CopyStatusType status = response.getCopyStatus();
final BlobCopyInfo result = new BlobCopyInfo(response.getCopySource(), response.getCopyId(), status,
response.getETag(), response.getCopyCompletionTime(), response.getCopyStatusDescription());
OperationStatus operationStatus;
switch (status) {
case SUCCESS:
operationStatus = OperationStatus.SUCCESSFULLY_COMPLETED;
break;
case FAILED:
operationStatus = OperationStatus.NOT_STARTED;
break;
case ABORTED:
operationStatus = OperationStatus.USER_CANCELLED;
break;
case PENDING:
operationStatus = OperationStatus.IN_PROGRESS;
break;
default:
throw Exceptions.propagate(logger.logExceptionAsError(new IllegalArgumentException(
"CopyStatusType is not supported. Status: " + status)));
}
return new PollResponse<>(operationStatus, result);
}).onErrorReturn(
new PollResponse<>(OperationStatus.fromString("POLLING_FAILED", true), lastInfo));
} | "CopyStatusType is not supported. Status: " + status))); | return getProperties().map(response -> {
final CopyStatusType status = response.getCopyStatus();
final BlobCopyInfo result = new BlobCopyInfo(response.getCopySource(), response.getCopyId(), status,
response.getETag(), response.getCopyCompletionTime(), response.getCopyStatusDescription());
OperationStatus operationStatus;
switch (status) {
case SUCCESS:
operationStatus = OperationStatus.SUCCESSFULLY_COMPLETED;
break;
case FAILED:
operationStatus = OperationStatus.FAILED;
break;
case ABORTED:
operationStatus = OperationStatus.USER_CANCELLED;
break;
case PENDING:
operationStatus = OperationStatus.IN_PROGRESS;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"CopyStatusType is not supported. Status: " + status));
}
return new PollResponse<>(operationStatus, result);
} | class BlobAsyncClientBase {
private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB;
private final ClientLogger logger = new ClientLogger(BlobAsyncClientBase.class);
protected final AzureBlobStorageImpl azureBlobStorage;
private final String snapshot;
private final CpkInfo customerProvidedKey;
protected final String accountName;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param azureBlobStorage the API client for blob storage
* @param snapshot Optional. The snapshot identifier for the snapshot blob.
* @param customerProvidedKey Optional. Customer provided key used during encryption of the blob's data on the
* server.
* @param accountName The account name for storage account.
*/
protected BlobAsyncClientBase(AzureBlobStorageImpl azureBlobStorage, String snapshot,
CpkInfo customerProvidedKey, String accountName) {
this.azureBlobStorage = azureBlobStorage;
this.snapshot = snapshot;
this.customerProvidedKey = customerProvidedKey;
this.accountName = accountName;
}
/**
* Creates a new {@link BlobAsyncClientBase} linked to the {@code snapshot} of this blob resource.
*
* @param snapshot the identifier for a specific snapshot of this blob
* @return a {@link BlobAsyncClientBase} used to interact with the specific snapshot.
*/
public BlobAsyncClientBase getSnapshotClient(String snapshot) {
return new BlobAsyncClientBase(new AzureBlobStorageBuilder()
.url(getBlobUrl())
.pipeline(azureBlobStorage.getHttpPipeline())
.build(), snapshot, customerProvidedKey, accountName);
}
/**
* Gets the URL of the blob represented by this client.
*
* @return the URL.
*/
public String getBlobUrl() {
if (!this.isSnapshot()) {
return azureBlobStorage.getUrl();
} else {
if (azureBlobStorage.getUrl().contains("?")) {
return String.format("%s&snapshot=%s", azureBlobStorage.getUrl(), snapshot);
} else {
return String.format("%s?snapshot=%s", azureBlobStorage.getUrl(), snapshot);
}
}
}
/**
* Get the container name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName}
*
* @return The name of the container.
*/
public final String getContainerName() {
return BlobUrlParts.parse(this.azureBlobStorage.getUrl(), logger).getBlobContainerName();
}
/**
* Get the blob name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName}
*
* @return The name of the blob.
*/
public final String getBlobName() {
return BlobUrlParts.parse(this.azureBlobStorage.getUrl(), logger).getBlobName();
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the {@link CpkInfo} used to encrypt this blob's content on the server.
*
* @return the customer provided key used for encryption.
*/
public CpkInfo getCustomerProvidedKey() {
return customerProvidedKey;
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return this.accountName;
}
/**
* Gets the snapshotId for a blob resource
*
* @return A string that represents the snapshotId of the snapshot blob
*/
public String getSnapshotId() {
return this.snapshot;
}
/**
* Determines if a blob is a snapshot
*
* @return A boolean that indicates if a blob is a snapshot
*/
public boolean isSnapshot() {
return this.snapshot != null;
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.exists}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Boolean> exists() {
return existsWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Response<Boolean>> existsWithResponse() {
return withContext(this::existsWithResponse);
}
Mono<Response<Boolean>> existsWithResponse(Context context) {
return this.getPropertiesWithResponse(null, context)
.map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true))
.onErrorResume(t -> t instanceof StorageException && ((StorageException) t).getStatusCode() == 404, t -> {
HttpResponse response = ((StorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false));
});
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrl
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
*
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopyFromUrl(URL sourceUrl) {
return beginCopyFromUrl(sourceUrl, null, null, null, null, null);
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrl
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param priority {@link RehydratePriority} for rehydrating the blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP
* Access conditions related to the modification of data. ETag and LastModifiedTime are used to construct
* conditions related to when the blob was changed relative to the given request. The request will fail if the
* specified condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
*
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopyFromUrl(URL sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destAccessConditions) {
final ModifiedAccessConditions sourceModifiedCondition = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions()
: sourceModifiedAccessConditions;
final BlobAccessConditions destinationAccessConditions = destAccessConditions == null
? new BlobAccessConditions()
: destAccessConditions;
final SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedCondition.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedCondition.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedCondition.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedCondition.getIfNoneMatch());
return new Poller<>(
Duration.ofSeconds(1),
this::onPoll,
Mono::empty,
() -> onStart(sourceUrl, metadata, tier, priority, sourceConditions, destinationAccessConditions),
poller -> {
final PollResponse<BlobCopyInfo> response = poller.getLastPollResponse();
if (response == null || response.getValue() == null) {
return Mono.error(logger.logExceptionAsError(
new IllegalArgumentException("Cannot cancel a poll response that never started.")));
}
final String copyIdentifier = response.getValue().getCopyId();
if (!ImplUtils.isNullOrEmpty(copyIdentifier)) {
logger.info("Cancelling copy operation for copy id: {}", copyIdentifier);
return abortCopyFromURL(copyIdentifier).thenReturn(response.getValue());
}
return Mono.empty();
});
}
private Mono<BlobCopyInfo> onStart(URL sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, SourceModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destinationAccessConditions) {
return withContext(
context -> azureBlobStorage.blobs().startCopyFromURLWithRestResponseAsync(null, null,
sourceUrl, null, metadata, tier, priority, null, sourceModifiedAccessConditions,
destinationAccessConditions.getModifiedAccessConditions(),
destinationAccessConditions.getLeaseAccessConditions(), context))
.map(response -> {
final BlobStartCopyFromURLHeaders headers = response.getDeserializedHeaders();
return new BlobCopyInfo(sourceUrl.toString(), headers.getCopyId(), headers.getCopyStatus(),
headers.getETag(), headers.getLastModified(), headers.getErrorCode());
});
}
private Mono<PollResponse<BlobCopyInfo>> onPoll(PollResponse<BlobCopyInfo> pollResponse) {
if (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED) {
return Mono.just(pollResponse);
}
final BlobCopyInfo lastInfo = pollResponse.getValue();
if (lastInfo == null) {
logger.warning("BlobCopyInfo does not exist. Activation operation failed.");
return Mono.just(new PollResponse<>(
OperationStatus.fromString("COPY_START_FAILED", true), null));
}
).onErrorReturn(
new PollResponse<>(OperationStatus.fromString("POLLING_FAILED", true), lastInfo));
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* @param copyId The id of the copy operation to abort.
* @return A reactive response signalling completion.
*/
public Mono<Void> abortCopyFromURL(String copyId) {
return abortCopyFromURLWithResponse(copyId, null).flatMap(FluxUtil::toMono);
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* @param copyId The id of the copy operation to abort.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId,
LeaseAccessConditions leaseAccessConditions) {
return withContext(context -> abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context));
}
Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions,
Context context) {
return this.azureBlobStorage.blobs().abortCopyFromURLWithRestResponseAsync(
null, null, copyId, null, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<String> copyFromURL(URL copySource) {
return copyFromURLWithResponse(copySource, null, null, null, null).flatMap(FluxUtil::toMono);
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access
* conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions
* related to when the blob was changed relative to the given request. The request will fail if the specified
* condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier,
ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions) {
return withContext(context -> copyFromURLWithResponse(copySource, metadata, tier,
sourceModifiedAccessConditions, destAccessConditions, context));
}
Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier,
ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions,
Context context) {
sourceModifiedAccessConditions = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions() : sourceModifiedAccessConditions;
destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions;
SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch());
return this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync(
null, null, copySource, null, metadata, tier, null, sourceConditions,
destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(),
context).map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId()));
}
/**
* Reads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or
* {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.download}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob data.
*/
public Flux<ByteBuffer> download() {
return downloadWithResponse(null, null, null, false)
.flatMapMany(Response::getValue);
}
/**
* Reads a range of bytes from a blob. Uploading data must be done from the {@link BlockBlobClient}, {@link
* PageBlobClient}, or {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param range {@link BlobRange}
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return A reactive response containing the blob data.
*/
public Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
return withContext(context -> downloadWithResponse(range, options, accessConditions, rangeGetContentMD5,
context));
}
Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
return download(range, accessConditions, rangeGetContentMD5, context)
.map(response -> new SimpleResponse<>(
response.getRawResponse(),
response.body(options).switchIfEmpty(Flux.just(ByteBuffer.wrap(new byte[0])))));
}
/**
* Reads a range of bytes from a blob. The response also includes the blob's properties and metadata. For more
* information, see the <a href="https:
* <p>
* Note that the response body has reliable download functionality built in, meaning that a failed download stream
* will be automatically retried. This behavior may be configured with {@link ReliableDownloadOptions}.
*
* @param range {@link BlobRange}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return Emits the successful response.
*/
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5) {
return withContext(context -> download(range, accessConditions, rangeGetContentMD5, context));
}
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5, Context context) {
range = range == null ? new BlobRange(0) : range;
Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null;
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
HttpGetterInfo info = new HttpGetterInfo()
.setOffset(range.getOffset())
.setCount(range.getCount())
.setETag(accessConditions.getModifiedAccessConditions().getIfMatch());
return this.azureBlobStorage.blobs().downloadWithRestResponseAsync(
null, null, snapshot, null, range.toHeaderValue(), getMD5, null, null,
accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> {
info.setETag(response.getDeserializedHeaders().getETag());
return new DownloadAsyncResponse(response, info,
newInfo ->
this.download(new BlobRange(newInfo.getOffset(), newInfo.getCount()),
new BlobAccessConditions().setModifiedAccessConditions(
new ModifiedAccessConditions().setIfMatch(info.getETag())), false, context));
});
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @return An empty response
*/
public Mono<BlobProperties> downloadToFile(String filePath) {
return downloadToFileWithResponse(filePath, null, null,
null, null, false).flatMap(FluxUtil::toMono);
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra
* call, provide the {@link BlobRange} parameter.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @param range {@link BlobRange}
* @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel
* transfers parameter is ignored.
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return An empty response
* @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB.
* @throws UncheckedIOException If an I/O error occurs.
*/
public Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
return withContext(context -> downloadToFileWithResponse(filePath, range, parallelTransferOptions, options,
accessConditions, rangeGetContentMD5, context));
}
Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
final ParallelTransferOptions finalParallelTransferOptions = parallelTransferOptions == null
? new ParallelTransferOptions()
: parallelTransferOptions;
ProgressReceiver progressReceiver = finalParallelTransferOptions.getProgressReceiver();
AtomicLong totalProgress = new AtomicLong(0);
Lock progressLock = new ReentrantLock();
return Mono.using(() -> downloadToFileResourceSupplier(filePath),
channel -> getPropertiesWithResponse(accessConditions)
.flatMap(response -> processInRange(channel, response,
range, finalParallelTransferOptions.getBlockSize(), options, accessConditions, rangeGetContentMD5,
context, totalProgress, progressLock, progressReceiver)), this::downloadToFileCleanup);
}
private Mono<Response<BlobProperties>> processInRange(AsynchronousFileChannel channel,
Response<BlobProperties> blobPropertiesResponse, BlobRange range, Integer blockSize,
ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5,
Context context, AtomicLong totalProgress, Lock progressLock, ProgressReceiver progressReceiver) {
return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new BlobRange(0,
blobPropertiesResponse.getValue().getBlobSize()))).flatMapMany(rg ->
Flux.fromIterable(sliceBlobRange(rg, blockSize)))
.flatMap(chunk -> this.download(chunk, accessConditions, rangeGetContentMD5, context)
.subscribeOn(Schedulers.elastic())
.flatMap(dar -> {
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
dar.body(options), progressReceiver, progressLock, totalProgress);
return FluxUtil.writeFile(progressData, channel,
chunk.getOffset() - ((range == null) ? 0 : range.getOffset()));
})).then(Mono.just(blobPropertiesResponse));
}
private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath) {
try {
return AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private void downloadToFileCleanup(AsynchronousFileChannel channel) {
try {
channel.close();
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private List<BlobRange> sliceBlobRange(BlobRange blobRange, Integer blockSize) {
if (blockSize == null) {
blockSize = BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE;
}
long offset = blobRange.getOffset();
long length = blobRange.getCount();
List<BlobRange> chunks = new ArrayList<>();
for (long pos = offset; pos < offset + length; pos += blockSize) {
long count = blockSize;
if (pos + count > offset + length) {
count = offset + length - pos;
}
chunks.add(new BlobRange(pos, count));
}
return chunks;
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> delete() {
return deleteWithResponse(null, null).flatMap(FluxUtil::toMono);
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include}
* will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being
* deleted, you must pass null.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions) {
return withContext(context -> deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context));
}
Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().deleteWithRestResponseAsync(
null, null, snapshot, null, deleteBlobSnapshotOptions,
null, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(),
context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<BlobProperties> getProperties() {
return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono);
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions) {
return withContext(context -> getPropertiesWithResponse(accessConditions, context));
}
Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().getPropertiesWithRestResponseAsync(
null, null, snapshot, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, new BlobProperties(rb.getDeserializedHeaders())));
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeaders
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHTTPHeaders}
* @return A reactive response signalling completion.
*/
public Mono<Void> setHTTPHeaders(BlobHTTPHeaders headers) {
return setHTTPHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono);
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeadersWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHTTPHeaders}
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers,
BlobAccessConditions accessConditions) {
return withContext(context -> setHTTPHeadersWithResponse(headers, accessConditions, context));
}
Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setHTTPHeadersWithRestResponseAsync(
null, null, null, null, headers,
accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @return A reactive response signalling completion.
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono);
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
return withContext(context -> setMetadataWithResponse(metadata, accessConditions, context));
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setMetadataWithRestResponseAsync(
null, null, null, metadata, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<BlobAsyncClientBase> createSnapshot() {
return createSnapshotWithResponse(null, null).flatMap(FluxUtil::toMono);
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob snapshot.
* @param accessConditions {@link BlobAccessConditions}
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
return withContext(context -> createSnapshotWithResponse(metadata, accessConditions, context));
}
Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().createSnapshotWithRestResponseAsync(
null, null, null, metadata, null, customerProvidedKey, accessConditions.getModifiedAccessConditions(),
accessConditions.getLeaseAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.getDeserializedHeaders().getSnapshot())));
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Void> setAccessTier(AccessTier tier) {
return setAccessTierWithResponse(tier, null, null).flatMap(FluxUtil::toMono);
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @param priority Optional priority to set for re-hydrating blobs.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Response<Void>> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions) {
return withContext(context -> setTierWithResponse(tier, priority, leaseAccessConditions, context));
}
Mono<Response<Void>> setTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions, Context context) {
Utility.assertNotNull("tier", tier);
return this.azureBlobStorage.blobs().setTierWithRestResponseAsync(
null, null, tier, null, priority, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> undelete() {
return undeleteWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> undeleteWithResponse() {
return withContext(this::undeleteWithResponse);
}
Mono<Response<Void>> undeleteWithResponse(Context context) {
return this.azureBlobStorage.blobs().undeleteWithRestResponseAsync(null,
null, context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<StorageAccountInfo> getAccountInfo() {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
return withContext(this::getAccountInfoWithResponse);
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
return this.azureBlobStorage.blobs().getAccountInfoWithRestResponseAsync(null, null, context)
.map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.getDeserializedHeaders())));
}
} | class BlobAsyncClientBase {
private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB;
private final ClientLogger logger = new ClientLogger(BlobAsyncClientBase.class);
protected final AzureBlobStorageImpl azureBlobStorage;
private final String snapshot;
private final CpkInfo customerProvidedKey;
protected final String accountName;
protected final String containerName;
protected final String blobName;
protected final BlobServiceVersion serviceVersion;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param pipeline The pipeline used to send and receive service requests.
* @param url The endpoint where to send service requests.
* @param serviceVersion The version of the service to receive requests.
* @param accountName The storage account name.
* @param containerName The container name.
* @param blobName The blob name.
* @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly.
* @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass
* {@code null} to allow the service to use its own encryption.
*/
protected BlobAsyncClientBase(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion,
String accountName, String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey) {
this.azureBlobStorage = new AzureBlobStorageBuilder()
.pipeline(pipeline)
.url(url)
.version(serviceVersion.getVersion())
.build();
this.serviceVersion = serviceVersion;
this.accountName = accountName;
this.containerName = containerName;
this.blobName = blobName;
this.snapshot = snapshot;
this.customerProvidedKey = customerProvidedKey;
}
/**
* Creates a new {@link BlobAsyncClientBase} linked to the {@code snapshot} of this blob resource.
*
* @param snapshot the identifier for a specific snapshot of this blob
* @return a {@link BlobAsyncClientBase} used to interact with the specific snapshot.
*/
public BlobAsyncClientBase getSnapshotClient(String snapshot) {
return new BlobAsyncClientBase(getHttpPipeline(), getBlobUrl(), getServiceVersion(), getAccountName(),
getContainerName(), getBlobName(), snapshot, getCustomerProvidedKey());
}
/**
* Gets the URL of the blob represented by this client.
*
* @return the URL.
*/
public String getBlobUrl() {
if (!this.isSnapshot()) {
return azureBlobStorage.getUrl();
} else {
if (azureBlobStorage.getUrl().contains("?")) {
return String.format("%s&snapshot=%s", azureBlobStorage.getUrl(), snapshot);
} else {
return String.format("%s?snapshot=%s", azureBlobStorage.getUrl(), snapshot);
}
}
}
/**
* Get the container name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName}
*
* @return The name of the container.
*/
public final String getContainerName() {
return containerName;
}
/**
* Get the blob name.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName}
*
* @return The name of the blob.
*/
public final String getBlobName() {
return blobName;
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
public HttpPipeline getHttpPipeline() {
return azureBlobStorage.getHttpPipeline();
}
/**
* Gets the {@link CpkInfo} used to encrypt this blob's content on the server.
*
* @return the customer provided key used for encryption.
*/
public CpkInfo getCustomerProvidedKey() {
return customerProvidedKey;
}
/**
* Get associated account name.
*
* @return account name associated with this storage resource.
*/
public String getAccountName() {
return accountName;
}
/**
* Gets the service version the client is using.
*
* @return the service version the client is using.
*/
public BlobServiceVersion getServiceVersion() {
return serviceVersion;
}
/**
* Gets the snapshotId for a blob resource
*
* @return A string that represents the snapshotId of the snapshot blob
*/
public String getSnapshotId() {
return this.snapshot;
}
/**
* Determines if a blob is a snapshot
*
* @return A boolean that indicates if a blob is a snapshot
*/
public boolean isSnapshot() {
return this.snapshot != null;
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.exists}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Boolean> exists() {
try {
return existsWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Determines if the blob this client represents exists in the cloud.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse}
*
* @return true if the blob exists, false if it doesn't
*/
public Mono<Response<Boolean>> existsWithResponse() {
try {
return withContext(this::existsWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Boolean>> existsWithResponse(Context context) {
return this.getPropertiesWithResponse(null, context)
.map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true))
.onErrorResume(t -> t instanceof BlobStorageException && ((BlobStorageException) t).getStatusCode() == 404,
t -> {
HttpResponse response = ((BlobStorageException) t).getResponse();
return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false));
});
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second
* is used.
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Duration pollInterval) {
return beginCopy(sourceUrl, null, null, null, null, null, pollInterval);
}
/**
* Copies the data at the source URL to a blob.
*
* <p><strong>Starting a copy operation</strong></p>
* Starting a copy operation and polling on the responses.
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy
*
* <p><strong>Cancelling a copy operation</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrlCancel
*
* <p>For more information, see the
* <a href="https:
*
* @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param priority {@link RehydratePriority} for rehydrating the blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP
* Access conditions related to the modification of data. ETag and LastModifiedTime are used to construct
* conditions related to when the blob was changed relative to the given request. The request will fail if the
* specified condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
* @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second
* is used.
* @return A {@link Poller} that polls the blob copy operation until it has completed, has failed, or has been
* cancelled.
*/
public Poller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destAccessConditions, Duration pollInterval) {
final Duration interval = pollInterval != null ? pollInterval : Duration.ofSeconds(1);
final ModifiedAccessConditions sourceModifiedCondition = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions()
: sourceModifiedAccessConditions;
final BlobAccessConditions destinationAccessConditions = destAccessConditions == null
? new BlobAccessConditions()
: destAccessConditions;
final SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedCondition.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedCondition.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedCondition.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedCondition.getIfNoneMatch());
return new Poller<>(interval,
response -> {
try {
return onPoll(response);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
},
Mono::empty,
() -> {
try {
return onStart(sourceUrl, metadata, tier, priority, sourceConditions, destinationAccessConditions);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
},
poller -> {
final PollResponse<BlobCopyInfo> response = poller.getLastPollResponse();
if (response == null || response.getValue() == null) {
return Mono.error(logger.logExceptionAsError(
new IllegalArgumentException("Cannot cancel a poll response that never started.")));
}
final String copyIdentifier = response.getValue().getCopyId();
if (!ImplUtils.isNullOrEmpty(copyIdentifier)) {
logger.info("Cancelling copy operation for copy id: {}", copyIdentifier);
return abortCopyFromURL(copyIdentifier).thenReturn(response.getValue());
}
return Mono.empty();
});
}
private Mono<BlobCopyInfo> onStart(String sourceUrl, Map<String, String> metadata, AccessTier tier,
RehydratePriority priority, SourceModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destinationAccessConditions) {
URL url;
try {
url = new URL(sourceUrl);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sourceUrl' is not a valid url.", ex));
}
return withContext(
context -> azureBlobStorage.blobs().startCopyFromURLWithRestResponseAsync(null, null, url, null, metadata,
tier, priority, null, sourceModifiedAccessConditions,
destinationAccessConditions.getModifiedAccessConditions(),
destinationAccessConditions.getLeaseAccessConditions(), context))
.map(response -> {
final BlobStartCopyFromURLHeaders headers = response.getDeserializedHeaders();
return new BlobCopyInfo(sourceUrl, headers.getCopyId(), headers.getCopyStatus(),
headers.getETag(), headers.getLastModified(), headers.getErrorCode());
});
}
private Mono<PollResponse<BlobCopyInfo>> onPoll(PollResponse<BlobCopyInfo> pollResponse) {
if (pollResponse.getStatus() == OperationStatus.SUCCESSFULLY_COMPLETED
|| pollResponse.getStatus() == OperationStatus.FAILED) {
return Mono.just(pollResponse);
}
final BlobCopyInfo lastInfo = pollResponse.getValue();
if (lastInfo == null) {
logger.warning("BlobCopyInfo does not exist. Activation operation failed.");
return Mono.just(new PollResponse<>(
OperationStatus.fromString("COPY_START_FAILED", true), null));
}
).onErrorReturn(
new PollResponse<>(OperationStatus.fromString("POLLING_FAILED", true), lastInfo));
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* BlobAccessConditions, Duration)
* @param copyId The id of the copy operation to abort.
* @return A reactive response signalling completion.
*/
public Mono<Void> abortCopyFromURL(String copyId) {
try {
return abortCopyFromURLWithResponse(copyId, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @see
* @see
* @see
* BlobAccessConditions, Duration)
* @param copyId The id of the copy operation to abort.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId,
LeaseAccessConditions leaseAccessConditions) {
try {
return withContext(context -> abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions,
Context context) {
return this.azureBlobStorage.blobs().abortCopyFromURLWithRestResponseAsync(
null, null, copyId, null, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURL
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<String> copyFromURL(String copySource) {
try {
return copyFromURLWithResponse(copySource, null, null, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Copies the data at the source URL to a blob and waits for the copy to complete before returning a response.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURLWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs.
* @param metadata Metadata to associate with the destination blob.
* @param tier {@link AccessTier} for the destination blob.
* @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access
* conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions
* related to when the blob was changed relative to the given request. The request will fail if the specified
* condition is not satisfied.
* @param destAccessConditions {@link BlobAccessConditions} against the destination.
* @return A reactive response containing the copy ID for the long running operation.
*/
public Mono<Response<String>> copyFromURLWithResponse(String copySource, Map<String, String> metadata,
AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions,
BlobAccessConditions destAccessConditions) {
try {
return withContext(context -> copyFromURLWithResponse(copySource, metadata, tier,
sourceModifiedAccessConditions, destAccessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<String>> copyFromURLWithResponse(String copySource, Map<String, String> metadata, AccessTier tier,
ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions,
Context context) {
sourceModifiedAccessConditions = sourceModifiedAccessConditions == null
? new ModifiedAccessConditions() : sourceModifiedAccessConditions;
destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions;
SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions()
.setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince())
.setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince())
.setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch())
.setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch());
URL url;
try {
url = new URL(copySource);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new IllegalArgumentException("'copySource' is not a valid url."));
}
return this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync(
null, null, url, null, metadata, tier, null, sourceConditions,
destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(),
context).map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId()));
}
/**
* Reads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or
* {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.download}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob data.
*/
public Flux<ByteBuffer> download() {
try {
return downloadWithResponse(null, null, null, false)
.flatMapMany(Response::getValue);
} catch (RuntimeException ex) {
return fluxError(logger, ex);
}
}
/**
* Reads a range of bytes from a blob. Uploading data must be done from the {@link BlockBlobClient}, {@link
* PageBlobClient}, or {@link AppendBlobClient}.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param range {@link BlobRange}
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return A reactive response containing the blob data.
*/
public Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
try {
return withContext(context -> downloadWithResponse(range, options, accessConditions, rangeGetContentMD5,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
return download(range, accessConditions, rangeGetContentMD5, context)
.map(response -> new SimpleResponse<>(
response.getRawResponse(),
response.body(options).switchIfEmpty(Flux.just(ByteBuffer.wrap(new byte[0])))));
}
/**
* Reads a range of bytes from a blob. The response also includes the blob's properties and metadata. For more
* information, see the <a href="https:
* <p>
* Note that the response body has reliable download functionality built in, meaning that a failed download stream
* will be automatically retried. This behavior may be configured with {@link ReliableDownloadOptions}.
*
* @param range {@link BlobRange}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return Emits the successful response.
*/
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5) {
return withContext(context -> download(range, accessConditions, rangeGetContentMD5, context));
}
Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions,
boolean rangeGetContentMD5, Context context) {
range = range == null ? new BlobRange(0) : range;
Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null;
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
HttpGetterInfo info = new HttpGetterInfo()
.setOffset(range.getOffset())
.setCount(range.getCount())
.setETag(accessConditions.getModifiedAccessConditions().getIfMatch());
return this.azureBlobStorage.blobs().downloadWithRestResponseAsync(
null, null, snapshot, null, range.toHeaderValue(), getMD5, null, null,
accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> {
info.setETag(response.getDeserializedHeaders().getETag());
return new DownloadAsyncResponse(response, info,
newInfo ->
this.download(new BlobRange(newInfo.getOffset(), newInfo.getCount()),
new BlobAccessConditions().setModifiedAccessConditions(
new ModifiedAccessConditions().setIfMatch(info.getETag())), false, context));
});
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @return An empty response
*/
public Mono<BlobProperties> downloadToFile(String filePath) {
try {
return downloadToFileWithResponse(filePath, null, null,
null, null, false).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Downloads the entire blob into a file specified by the path.
*
* <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException}
* will be thrown.</p>
*
* <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link
* AppendBlobClient}.</p>
*
* <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra
* call, provide the {@link BlobRange} parameter.</p>
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written.
* @param range {@link BlobRange}
* @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel
* transfers parameter is ignored.
* @param options {@link ReliableDownloadOptions}
* @param accessConditions {@link BlobAccessConditions}
* @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned.
* @return An empty response
* @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB.
* @throws UncheckedIOException If an I/O error occurs.
*/
public Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5) {
try {
return withContext(context -> downloadToFileWithResponse(filePath, range, parallelTransferOptions, options,
accessConditions, rangeGetContentMD5, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range,
ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options,
BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) {
final ParallelTransferOptions finalParallelTransferOptions = parallelTransferOptions == null
? new ParallelTransferOptions()
: parallelTransferOptions;
ProgressReceiver progressReceiver = finalParallelTransferOptions.getProgressReceiver();
AtomicLong totalProgress = new AtomicLong(0);
Lock progressLock = new ReentrantLock();
return Mono.using(() -> downloadToFileResourceSupplier(filePath),
channel -> getPropertiesWithResponse(accessConditions)
.flatMap(response -> processInRange(channel, response,
range, finalParallelTransferOptions.getBlockSize(), options, accessConditions, rangeGetContentMD5,
context, totalProgress, progressLock, progressReceiver)), this::downloadToFileCleanup);
}
private Mono<Response<BlobProperties>> processInRange(AsynchronousFileChannel channel,
Response<BlobProperties> blobPropertiesResponse, BlobRange range, Integer blockSize,
ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5,
Context context, AtomicLong totalProgress, Lock progressLock, ProgressReceiver progressReceiver) {
return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new BlobRange(0,
blobPropertiesResponse.getValue().getBlobSize()))).flatMapMany(rg ->
Flux.fromIterable(sliceBlobRange(rg, blockSize)))
.flatMap(chunk -> this.download(chunk, accessConditions, rangeGetContentMD5, context)
.subscribeOn(Schedulers.elastic())
.flatMap(dar -> {
Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting(
dar.body(options), progressReceiver, progressLock, totalProgress);
return FluxUtil.writeFile(progressData, channel,
chunk.getOffset() - ((range == null) ? 0 : range.getOffset()));
})).then(Mono.just(blobPropertiesResponse));
}
private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath) {
try {
return AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private void downloadToFileCleanup(AsynchronousFileChannel channel) {
try {
channel.close();
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private List<BlobRange> sliceBlobRange(BlobRange blobRange, Integer blockSize) {
if (blockSize == null) {
blockSize = BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE;
}
long offset = blobRange.getOffset();
long length = blobRange.getCount();
List<BlobRange> chunks = new ArrayList<>();
for (long pos = offset; pos < offset + length; pos += blockSize) {
long count = blockSize;
if (pos + count > offset + length) {
count = offset + length - pos;
}
chunks.add(new BlobRange(pos, count));
}
return chunks;
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.delete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> delete() {
try {
return deleteWithResponse(null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include}
* will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being
* deleted, you must pass null.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().deleteWithRestResponseAsync(
null, null, snapshot, null, deleteBlobSnapshotOptions,
null, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(),
context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<BlobProperties> getProperties() {
try {
return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the blob's metadata and properties.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response containing the blob properties and metadata.
*/
public Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions) {
try {
return withContext(context -> getPropertiesWithResponse(accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().getPropertiesWithRestResponseAsync(
null, null, snapshot, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, new BlobProperties(rb.getDeserializedHeaders())));
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeaders
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHttpHeaders}
* @return A reactive response signalling completion.
*/
public Mono<Void> setHttpHeaders(BlobHttpHeaders headers) {
try {
return setHttpHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In
* order to preserve existing values, they must be passed alongside the header being changed.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeadersWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param headers {@link BlobHttpHeaders}
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setHttpHeadersWithResponse(BlobHttpHeaders headers,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> setHttpHeadersWithResponse(headers, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setHttpHeadersWithResponse(BlobHttpHeaders headers, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setHTTPHeadersWithRestResponseAsync(
null, null, null, null, headers,
accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @return A reactive response signalling completion.
*/
public Mono<Void> setMetadata(Map<String, String> metadata) {
try {
return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values
* must be preserved, they must be downloaded and included in the call to this method.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob.
* @param accessConditions {@link BlobAccessConditions}
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> setMetadataWithResponse(metadata, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions,
Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().setMetadataWithRestResponseAsync(
null, null, null, metadata, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey,
accessConditions.getModifiedAccessConditions(), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot}
*
* <p>For more information, see the
* <a href="https:
*
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<BlobAsyncClientBase> createSnapshot() {
try {
return createSnapshotWithResponse(null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a read-only snapshot of the blob.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param metadata Metadata to associate with the blob snapshot.
* @param accessConditions {@link BlobAccessConditions}
* @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot,
* use {@link
*/
public Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions) {
try {
return withContext(context -> createSnapshotWithResponse(metadata, accessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata,
BlobAccessConditions accessConditions, Context context) {
accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions;
return this.azureBlobStorage.blobs().createSnapshotWithRestResponseAsync(
null, null, null, metadata, null, customerProvidedKey, accessConditions.getModifiedAccessConditions(),
accessConditions.getLeaseAccessConditions(), context)
.map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.getDeserializedHeaders().getSnapshot())));
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Void> setAccessTier(AccessTier tier) {
try {
return setAccessTierWithResponse(tier, null, null).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in
* a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of
* the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's
* etag.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse
*
* <p>For more information, see the
* <a href="https:
*
* @param tier The new tier for the blob.
* @param priority Optional priority to set for re-hydrating blobs.
* @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does
* not match the active lease on the blob.
* @return A reactive response signalling completion.
* @throws NullPointerException if {@code tier} is null.
*/
public Mono<Response<Void>> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions) {
try {
return withContext(context -> setTierWithResponse(tier, priority, leaseAccessConditions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> setTierWithResponse(AccessTier tier, RehydratePriority priority,
LeaseAccessConditions leaseAccessConditions, Context context) {
StorageImplUtils.assertNotNull("tier", tier);
return this.azureBlobStorage.blobs().setTierWithRestResponseAsync(
null, null, tier, null, priority, null, leaseAccessConditions, context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Void> undelete() {
try {
return undeleteWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return A reactive response signalling completion.
*/
public Mono<Response<Void>> undeleteWithResponse() {
try {
return withContext(this::undeleteWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> undeleteWithResponse(Context context) {
return this.azureBlobStorage.blobs().undeleteWithRestResponseAsync(null,
null, context).map(response -> new SimpleResponse<>(response, null));
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<StorageAccountInfo> getAccountInfo() {
try {
return getAccountInfoWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Returns the sku name and account kind for the account.
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse}
*
* <p>For more information, see the
* <a href="https:
*
* @return a reactor response containing the sku name and account kind.
*/
public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() {
try {
return withContext(this::getAccountInfoWithResponse);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) {
return this.azureBlobStorage.blobs().getAccountInfoWithRestResponseAsync(null, null, context)
.map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.getDeserializedHeaders())));
}
} |
check handled in impl | public void endSpan(Context context, Signal<Void> signal) {
Objects.requireNonNull(context, "'context' cannot be null.");
Objects.requireNonNull(signal, "'signal' cannot be null.");
switch (signal.getType()) {
case ON_COMPLETE:
end("success", null, context);
break;
case ON_ERROR:
String errorCondition = "";
Throwable throwable = null;
if (signal.hasError()) {
throwable = signal.getThrowable();
if (throwable instanceof AmqpException) {
AmqpException exception = (AmqpException) throwable;
errorCondition = exception.getErrorCondition().getErrorCondition();
}
}
end(errorCondition, throwable, context);
break;
default:
break;
}
} | end("success", null, context); | public void endSpan(Context context, Signal<Void> signal) {
Objects.requireNonNull(context, "'context' cannot be null.");
Objects.requireNonNull(signal, "'signal' cannot be null.");
switch (signal.getType()) {
case ON_COMPLETE:
end("success", null, context);
break;
case ON_ERROR:
String errorCondition = "";
Throwable throwable = null;
if (signal.hasError()) {
throwable = signal.getThrowable();
if (throwable instanceof AmqpException) {
AmqpException exception = (AmqpException) throwable;
errorCondition = exception.getErrorCondition().getErrorCondition();
}
}
end(errorCondition, throwable, context);
break;
default:
break;
}
} | class TracerProvider {
private final ClientLogger logger = new ClientLogger(TracerProvider.class);
private final List<Tracer> tracers = new ArrayList<>();
public TracerProvider(Iterable<Tracer> tracers) {
Objects.requireNonNull(tracers, "'tracers' cannot be null.");
tracers.forEach(e -> this.tracers.add(e));
}
public boolean isEnabled() {
return tracers.size() > 0;
}
/**
* For each tracer plugged into the SDK a new tracing span is created.
*
* The {@code context} will be checked for containing information about a parent span. If a parent span is found the
* new span will be added as a child, otherwise the span will be created and added to the context and any downstream
* start calls will use the created span as the parent.
*
* @param context Additional metadata that is passed through the call stack.
* @param processKind the invoking process type.
* @return An updated context object.
*/
public Context startSpan(Context context, ProcessKind processKind) {
Context local = Objects.requireNonNull(context, "'context' cannot be null.");
Objects.requireNonNull(processKind, "'processKind' cannot be null.");
String spanName = getSpanName(processKind);
for (Tracer tracer : tracers) {
local = tracer.start(spanName, local, processKind);
}
return local;
}
/**
* Given a context containing the current tracing span the span is marked completed with status info from
* {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed.
*
* @param context Additional metadata that is passed through the call stack.
* @param signal The signal indicates the status and contains the metadata we need to end the tracing span.
*/
/**
* For each tracer plugged into the SDK a link is created between the parent tracing span and
* the current service call.
*
* @param context Additional metadata that is passed through the call stack.
*/
public void addSpanLinks(Context context) {
Objects.requireNonNull(context, "'context' cannot be null.");
tracers.forEach(tracer -> tracer.addLink(context));
}
/**
* For each tracer plugged into the SDK a new context is extracted from the event's diagnostic Id.
*
* @param diagnosticId Unique identifier of an external call from producer to the queue.
*/
public Context extractContext(String diagnosticId, Context context) {
Context local = Objects.requireNonNull(context, "'context' cannot be null.");
Objects.requireNonNull(diagnosticId, "'diagnosticId' cannot be null.");
for (Tracer tracer : tracers) {
local = tracer.extractContext(diagnosticId, local);
}
return local;
}
private void end(String statusMessage, Throwable throwable, Context context) {
for (Tracer tracer : tracers) {
tracer.end(statusMessage, throwable, context);
}
}
private String getSpanName(ProcessKind processKind) {
String spanName = "Azure.eventhubs.";
switch (processKind) {
case SEND:
spanName += "send";
break;
case RECEIVE:
spanName += "message";
break;
case PROCESS:
spanName += "process";
break;
default:
logger.warning("Unknown processKind type: {}", processKind);
break;
}
return spanName;
}
} | class TracerProvider {
private final ClientLogger logger = new ClientLogger(TracerProvider.class);
private final List<Tracer> tracers = new ArrayList<>();
public TracerProvider(Iterable<Tracer> tracers) {
Objects.requireNonNull(tracers, "'tracers' cannot be null.");
tracers.forEach(e -> this.tracers.add(e));
}
public boolean isEnabled() {
return tracers.size() > 0;
}
/**
* For each tracer plugged into the SDK a new tracing span is created.
*
* The {@code context} will be checked for containing information about a parent span. If a parent span is found the
* new span will be added as a child, otherwise the span will be created and added to the context and any downstream
* start calls will use the created span as the parent.
*
* @param context Additional metadata that is passed through the call stack.
* @param processKind the invoking process type.
* @return An updated context object.
*/
public Context startSpan(Context context, ProcessKind processKind) {
Context local = Objects.requireNonNull(context, "'context' cannot be null.");
Objects.requireNonNull(processKind, "'processKind' cannot be null.");
String spanName = getSpanName(processKind);
for (Tracer tracer : tracers) {
local = tracer.start(spanName, local, processKind);
}
return local;
}
/**
* Given a context containing the current tracing span the span is marked completed with status info from
* {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed.
*
* @param context Additional metadata that is passed through the call stack.
* @param signal The signal indicates the status and contains the metadata we need to end the tracing span.
*/
/**
* For each tracer plugged into the SDK a link is created between the parent tracing span and
* the current service call.
*
* @param context Additional metadata that is passed through the call stack.
*/
public void addSpanLinks(Context context) {
Objects.requireNonNull(context, "'context' cannot be null.");
tracers.forEach(tracer -> tracer.addLink(context));
}
/**
* For each tracer plugged into the SDK a new context is extracted from the event's diagnostic Id.
*
* @param diagnosticId Unique identifier of an external call from producer to the queue.
*/
public Context extractContext(String diagnosticId, Context context) {
Context local = Objects.requireNonNull(context, "'context' cannot be null.");
Objects.requireNonNull(diagnosticId, "'diagnosticId' cannot be null.");
for (Tracer tracer : tracers) {
local = tracer.extractContext(diagnosticId, local);
}
return local;
}
private void end(String statusMessage, Throwable throwable, Context context) {
for (Tracer tracer : tracers) {
tracer.end(statusMessage, throwable, context);
}
}
private String getSpanName(ProcessKind processKind) {
String spanName = "Azure.eventhubs.";
switch (processKind) {
case SEND:
spanName += "send";
break;
case RECEIVE:
spanName += "message";
break;
case PROCESS:
spanName += "process";
break;
default:
logger.warning("Unknown processKind type: {}", processKind);
break;
}
return spanName;
}
} |
You are swallowing the `MalformedURLException` here - you should be sure to include the `e` object as well, either instead of the `IllegalArgumentException`, or as an argument into that exception if it has an appropriate constructor. | public HttpRequest(HttpMethod httpMethod, String url) {
this.httpMethod = httpMethod;
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL"));
}
this.headers = new HttpHeaders();
} | throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL")); | public HttpRequest(HttpMethod httpMethod, String url) {
this.httpMethod = httpMethod;
try {
this.url = new URL(url);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL", ex));
}
this.headers = new HttpHeaders();
} | class HttpRequest implements Serializable {
private static final long serialVersionUID = 6338479743058758810L;
private final ClientLogger logger = new ClientLogger(HttpRequest.class);
private HttpMethod httpMethod;
private URL url;
private HttpHeaders headers;
private Flux<ByteBuffer> body;
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
*/
public HttpRequest(HttpMethod httpMethod, URL url) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = new HttpHeaders();
}
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
*/
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
* @param headers the HTTP headers to use with this request
* @param body the request content
*/
public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = headers;
this.body = body;
}
/**
* Get the request method.
*
* @return the request method
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Set the request method.
*
* @param httpMethod the request method
* @return this HttpRequest
*/
public HttpRequest setHttpMethod(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
return this;
}
/**
* Get the target address.
*
* @return the target address
*/
public URL getUrl() {
return url;
}
/**
* Get the target address as a String.
*
* @return the target address
*/
public String getUrlString() {
return url.toString();
}
/**
* Set the target address to send the request to.
*
* @param url target address as {@link URL}
* @return this HttpRequest
*/
public HttpRequest setUrl(URL url) {
this.url = url;
return this;
}
/**
* Set the target address to send the request to.
*
* @param url target address as a String
* @return this HttpRequest
*/
public HttpRequest setUrl(String url) {
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL."));
}
return this;
}
/**
* Get the request headers.
*
* @return headers to be sent
*/
public HttpHeaders getHeaders() {
return headers;
}
/**
* Set the request headers.
*
* @param headers the set of headers
* @return this HttpRequest
*/
public HttpRequest setHeaders(HttpHeaders headers) {
this.headers = headers;
return this;
}
/**
* Set a request header, replacing any existing value.
* A null for {@code value} will remove the header if one with matching name exists.
*
* @param name the header name
* @param value the header value
* @return this HttpRequest
*/
public HttpRequest setHeader(String name, String value) {
headers.put(name, value);
return this;
}
/**
* Get the request content.
*
* @return the content to be send
*/
public Flux<ByteBuffer> getBody() {
return body;
}
/**
* Set the request content.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(String content) {
final byte[] bodyBytes = content.getBytes(StandardCharsets.UTF_8);
return setBody(bodyBytes);
}
/**
* Set the request content.
* The Content-Length header will be set based on the given content's length
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(byte[] content) {
headers.put("Content-Length", String.valueOf(content.length));
return setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(content))));
}
/**
* Set request content.
*
* Caller must set the Content-Length header to indicate the length of the content,
* or use Transfer-Encoding: chunked.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(Flux<ByteBuffer> content) {
this.body = content;
return this;
}
/**
* Creates a copy of the request.
*
* The main purpose of this is so that this HttpRequest can be changed and the resulting
* HttpRequest can be a backup. This means that the cloned HttpHeaders and body must
* not be able to change from side effects of this HttpRequest.
*
* @return a new HTTP request instance with cloned instances of all mutable properties.
*/
public HttpRequest copy() {
final HttpHeaders bufferedHeaders = new HttpHeaders(headers);
return new HttpRequest(httpMethod, url, bufferedHeaders, body);
}
} | class HttpRequest {
private final ClientLogger logger = new ClientLogger(HttpRequest.class);
private HttpMethod httpMethod;
private URL url;
private HttpHeaders headers;
private Flux<ByteBuffer> body;
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
*/
public HttpRequest(HttpMethod httpMethod, URL url) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = new HttpHeaders();
}
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
* @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL.
*/
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
* @param headers the HTTP headers to use with this request
* @param body the request content
*/
public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = headers;
this.body = body;
}
/**
* Get the request method.
*
* @return the request method
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Set the request method.
*
* @param httpMethod the request method
* @return this HttpRequest
*/
public HttpRequest setHttpMethod(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
return this;
}
/**
* Get the target address.
*
* @return the target address
*/
public URL getUrl() {
return url;
}
/**
* Set the target address to send the request to.
*
* @param url target address as {@link URL}
* @return this HttpRequest
*/
public HttpRequest setUrl(URL url) {
this.url = url;
return this;
}
/**
* Set the target address to send the request to.
*
* @param url target address as a String
* @return this HttpRequest
* @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL.
*/
public HttpRequest setUrl(String url) {
try {
this.url = new URL(url);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex));
}
return this;
}
/**
* Get the request headers.
*
* @return headers to be sent
*/
public HttpHeaders getHeaders() {
return headers;
}
/**
* Set the request headers.
*
* @param headers the set of headers
* @return this HttpRequest
*/
public HttpRequest setHeaders(HttpHeaders headers) {
this.headers = headers;
return this;
}
/**
* Set a request header, replacing any existing value.
* A null for {@code value} will remove the header if one with matching name exists.
*
* @param name the header name
* @param value the header value
* @return this HttpRequest
*/
public HttpRequest setHeader(String name, String value) {
headers.put(name, value);
return this;
}
/**
* Get the request content.
*
* @return the content to be send
*/
public Flux<ByteBuffer> getBody() {
return body;
}
/**
* Set the request content.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(String content) {
final byte[] bodyBytes = content.getBytes(StandardCharsets.UTF_8);
return setBody(bodyBytes);
}
/**
* Set the request content.
* The Content-Length header will be set based on the given content's length
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(byte[] content) {
headers.put("Content-Length", String.valueOf(content.length));
return setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(content))));
}
/**
* Set request content.
*
* Caller must set the Content-Length header to indicate the length of the content,
* or use Transfer-Encoding: chunked.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(Flux<ByteBuffer> content) {
this.body = content;
return this;
}
/**
* Creates a copy of the request.
*
* The main purpose of this is so that this HttpRequest can be changed and the resulting
* HttpRequest can be a backup. This means that the cloned HttpHeaders and body must
* not be able to change from side effects of this HttpRequest.
*
* @return a new HTTP request instance with cloned instances of all mutable properties.
*/
public HttpRequest copy() {
final HttpHeaders bufferedHeaders = new HttpHeaders(headers);
return new HttpRequest(httpMethod, url, bufferedHeaders, body);
}
} |
👍 | public HttpRequest(HttpMethod httpMethod, String url) {
this.httpMethod = httpMethod;
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL"));
}
this.headers = new HttpHeaders();
} | throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL")); | public HttpRequest(HttpMethod httpMethod, String url) {
this.httpMethod = httpMethod;
try {
this.url = new URL(url);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL", ex));
}
this.headers = new HttpHeaders();
} | class HttpRequest implements Serializable {
private static final long serialVersionUID = 6338479743058758810L;
private final ClientLogger logger = new ClientLogger(HttpRequest.class);
private HttpMethod httpMethod;
private URL url;
private HttpHeaders headers;
private Flux<ByteBuffer> body;
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
*/
public HttpRequest(HttpMethod httpMethod, URL url) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = new HttpHeaders();
}
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
*/
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
* @param headers the HTTP headers to use with this request
* @param body the request content
*/
public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = headers;
this.body = body;
}
/**
* Get the request method.
*
* @return the request method
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Set the request method.
*
* @param httpMethod the request method
* @return this HttpRequest
*/
public HttpRequest setHttpMethod(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
return this;
}
/**
* Get the target address.
*
* @return the target address
*/
public URL getUrl() {
return url;
}
/**
* Get the target address as a String.
*
* @return the target address
*/
public String getUrlString() {
return url.toString();
}
/**
* Set the target address to send the request to.
*
* @param url target address as {@link URL}
* @return this HttpRequest
*/
public HttpRequest setUrl(URL url) {
this.url = url;
return this;
}
/**
* Set the target address to send the request to.
*
* @param url target address as a String
* @return this HttpRequest
*/
public HttpRequest setUrl(String url) {
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL."));
}
return this;
}
/**
* Get the request headers.
*
* @return headers to be sent
*/
public HttpHeaders getHeaders() {
return headers;
}
/**
* Set the request headers.
*
* @param headers the set of headers
* @return this HttpRequest
*/
public HttpRequest setHeaders(HttpHeaders headers) {
this.headers = headers;
return this;
}
/**
* Set a request header, replacing any existing value.
* A null for {@code value} will remove the header if one with matching name exists.
*
* @param name the header name
* @param value the header value
* @return this HttpRequest
*/
public HttpRequest setHeader(String name, String value) {
headers.put(name, value);
return this;
}
/**
* Get the request content.
*
* @return the content to be send
*/
public Flux<ByteBuffer> getBody() {
return body;
}
/**
* Set the request content.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(String content) {
final byte[] bodyBytes = content.getBytes(StandardCharsets.UTF_8);
return setBody(bodyBytes);
}
/**
* Set the request content.
* The Content-Length header will be set based on the given content's length
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(byte[] content) {
headers.put("Content-Length", String.valueOf(content.length));
return setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(content))));
}
/**
* Set request content.
*
* Caller must set the Content-Length header to indicate the length of the content,
* or use Transfer-Encoding: chunked.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(Flux<ByteBuffer> content) {
this.body = content;
return this;
}
/**
* Creates a copy of the request.
*
* The main purpose of this is so that this HttpRequest can be changed and the resulting
* HttpRequest can be a backup. This means that the cloned HttpHeaders and body must
* not be able to change from side effects of this HttpRequest.
*
* @return a new HTTP request instance with cloned instances of all mutable properties.
*/
public HttpRequest copy() {
final HttpHeaders bufferedHeaders = new HttpHeaders(headers);
return new HttpRequest(httpMethod, url, bufferedHeaders, body);
}
} | class HttpRequest {
private final ClientLogger logger = new ClientLogger(HttpRequest.class);
private HttpMethod httpMethod;
private URL url;
private HttpHeaders headers;
private Flux<ByteBuffer> body;
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
*/
public HttpRequest(HttpMethod httpMethod, URL url) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = new HttpHeaders();
}
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
* @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL.
*/
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
* @param headers the HTTP headers to use with this request
* @param body the request content
*/
public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = headers;
this.body = body;
}
/**
* Get the request method.
*
* @return the request method
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Set the request method.
*
* @param httpMethod the request method
* @return this HttpRequest
*/
public HttpRequest setHttpMethod(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
return this;
}
/**
* Get the target address.
*
* @return the target address
*/
public URL getUrl() {
return url;
}
/**
* Set the target address to send the request to.
*
* @param url target address as {@link URL}
* @return this HttpRequest
*/
public HttpRequest setUrl(URL url) {
this.url = url;
return this;
}
/**
* Set the target address to send the request to.
*
* @param url target address as a String
* @return this HttpRequest
* @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL.
*/
public HttpRequest setUrl(String url) {
try {
this.url = new URL(url);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex));
}
return this;
}
/**
* Get the request headers.
*
* @return headers to be sent
*/
public HttpHeaders getHeaders() {
return headers;
}
/**
* Set the request headers.
*
* @param headers the set of headers
* @return this HttpRequest
*/
public HttpRequest setHeaders(HttpHeaders headers) {
this.headers = headers;
return this;
}
/**
* Set a request header, replacing any existing value.
* A null for {@code value} will remove the header if one with matching name exists.
*
* @param name the header name
* @param value the header value
* @return this HttpRequest
*/
public HttpRequest setHeader(String name, String value) {
headers.put(name, value);
return this;
}
/**
* Get the request content.
*
* @return the content to be send
*/
public Flux<ByteBuffer> getBody() {
return body;
}
/**
* Set the request content.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(String content) {
final byte[] bodyBytes = content.getBytes(StandardCharsets.UTF_8);
return setBody(bodyBytes);
}
/**
* Set the request content.
* The Content-Length header will be set based on the given content's length
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(byte[] content) {
headers.put("Content-Length", String.valueOf(content.length));
return setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(content))));
}
/**
* Set request content.
*
* Caller must set the Content-Length header to indicate the length of the content,
* or use Transfer-Encoding: chunked.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(Flux<ByteBuffer> content) {
this.body = content;
return this;
}
/**
* Creates a copy of the request.
*
* The main purpose of this is so that this HttpRequest can be changed and the resulting
* HttpRequest can be a backup. This means that the cloned HttpHeaders and body must
* not be able to change from side effects of this HttpRequest.
*
* @return a new HTTP request instance with cloned instances of all mutable properties.
*/
public HttpRequest copy() {
final HttpHeaders bufferedHeaders = new HttpHeaders(headers);
return new HttpRequest(httpMethod, url, bufferedHeaders, body);
}
} |
Same here. Add `e` as an argument to the `IllegalArgumentException` constructor. | public HttpRequest setUrl(String url) {
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL."));
}
return this;
} | throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.")); | public HttpRequest setUrl(String url) {
try {
this.url = new URL(url);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex));
}
return this;
} | class HttpRequest implements Serializable {
private static final long serialVersionUID = 6338479743058758810L;
private final ClientLogger logger = new ClientLogger(HttpRequest.class);
private HttpMethod httpMethod;
private URL url;
private HttpHeaders headers;
private Flux<ByteBuffer> body;
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
*/
public HttpRequest(HttpMethod httpMethod, URL url) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = new HttpHeaders();
}
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
*/
public HttpRequest(HttpMethod httpMethod, String url) {
this.httpMethod = httpMethod;
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL"));
}
this.headers = new HttpHeaders();
}
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
* @param headers the HTTP headers to use with this request
* @param body the request content
*/
public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = headers;
this.body = body;
}
/**
* Get the request method.
*
* @return the request method
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Set the request method.
*
* @param httpMethod the request method
* @return this HttpRequest
*/
public HttpRequest setHttpMethod(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
return this;
}
/**
* Get the target address.
*
* @return the target address
*/
public URL getUrl() {
return url;
}
/**
* Get the target address as a String.
*
* @return the target address
*/
public String getUrlString() {
return url.toString();
}
/**
* Set the target address to send the request to.
*
* @param url target address as {@link URL}
* @return this HttpRequest
*/
public HttpRequest setUrl(URL url) {
this.url = url;
return this;
}
/**
* Set the target address to send the request to.
*
* @param url target address as a String
* @return this HttpRequest
*/
/**
* Get the request headers.
*
* @return headers to be sent
*/
public HttpHeaders getHeaders() {
return headers;
}
/**
* Set the request headers.
*
* @param headers the set of headers
* @return this HttpRequest
*/
public HttpRequest setHeaders(HttpHeaders headers) {
this.headers = headers;
return this;
}
/**
* Set a request header, replacing any existing value.
* A null for {@code value} will remove the header if one with matching name exists.
*
* @param name the header name
* @param value the header value
* @return this HttpRequest
*/
public HttpRequest setHeader(String name, String value) {
headers.put(name, value);
return this;
}
/**
* Get the request content.
*
* @return the content to be send
*/
public Flux<ByteBuffer> getBody() {
return body;
}
/**
* Set the request content.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(String content) {
final byte[] bodyBytes = content.getBytes(StandardCharsets.UTF_8);
return setBody(bodyBytes);
}
/**
* Set the request content.
* The Content-Length header will be set based on the given content's length
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(byte[] content) {
headers.put("Content-Length", String.valueOf(content.length));
return setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(content))));
}
/**
* Set request content.
*
* Caller must set the Content-Length header to indicate the length of the content,
* or use Transfer-Encoding: chunked.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(Flux<ByteBuffer> content) {
this.body = content;
return this;
}
/**
* Creates a copy of the request.
*
* The main purpose of this is so that this HttpRequest can be changed and the resulting
* HttpRequest can be a backup. This means that the cloned HttpHeaders and body must
* not be able to change from side effects of this HttpRequest.
*
* @return a new HTTP request instance with cloned instances of all mutable properties.
*/
public HttpRequest copy() {
final HttpHeaders bufferedHeaders = new HttpHeaders(headers);
return new HttpRequest(httpMethod, url, bufferedHeaders, body);
}
} | class HttpRequest {
private final ClientLogger logger = new ClientLogger(HttpRequest.class);
private HttpMethod httpMethod;
private URL url;
private HttpHeaders headers;
private Flux<ByteBuffer> body;
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
*/
public HttpRequest(HttpMethod httpMethod, URL url) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = new HttpHeaders();
}
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
* @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL.
*/
public HttpRequest(HttpMethod httpMethod, String url) {
this.httpMethod = httpMethod;
try {
this.url = new URL(url);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL", ex));
}
this.headers = new HttpHeaders();
}
/**
* Create a new HttpRequest instance.
*
* @param httpMethod the HTTP request method
* @param url the target address to send the request to
* @param headers the HTTP headers to use with this request
* @param body the request content
*/
public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, Flux<ByteBuffer> body) {
this.httpMethod = httpMethod;
this.url = url;
this.headers = headers;
this.body = body;
}
/**
* Get the request method.
*
* @return the request method
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Set the request method.
*
* @param httpMethod the request method
* @return this HttpRequest
*/
public HttpRequest setHttpMethod(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
return this;
}
/**
* Get the target address.
*
* @return the target address
*/
public URL getUrl() {
return url;
}
/**
* Set the target address to send the request to.
*
* @param url target address as {@link URL}
* @return this HttpRequest
*/
public HttpRequest setUrl(URL url) {
this.url = url;
return this;
}
/**
* Set the target address to send the request to.
*
* @param url target address as a String
* @return this HttpRequest
* @throws IllegalArgumentException if {@code url} is null or it cannot be parsed into a valid URL.
*/
/**
* Get the request headers.
*
* @return headers to be sent
*/
public HttpHeaders getHeaders() {
return headers;
}
/**
* Set the request headers.
*
* @param headers the set of headers
* @return this HttpRequest
*/
public HttpRequest setHeaders(HttpHeaders headers) {
this.headers = headers;
return this;
}
/**
* Set a request header, replacing any existing value.
* A null for {@code value} will remove the header if one with matching name exists.
*
* @param name the header name
* @param value the header value
* @return this HttpRequest
*/
public HttpRequest setHeader(String name, String value) {
headers.put(name, value);
return this;
}
/**
* Get the request content.
*
* @return the content to be send
*/
public Flux<ByteBuffer> getBody() {
return body;
}
/**
* Set the request content.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(String content) {
final byte[] bodyBytes = content.getBytes(StandardCharsets.UTF_8);
return setBody(bodyBytes);
}
/**
* Set the request content.
* The Content-Length header will be set based on the given content's length
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(byte[] content) {
headers.put("Content-Length", String.valueOf(content.length));
return setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(content))));
}
/**
* Set request content.
*
* Caller must set the Content-Length header to indicate the length of the content,
* or use Transfer-Encoding: chunked.
*
* @param content the request content
* @return this HttpRequest
*/
public HttpRequest setBody(Flux<ByteBuffer> content) {
this.body = content;
return this;
}
/**
* Creates a copy of the request.
*
* The main purpose of this is so that this HttpRequest can be changed and the resulting
* HttpRequest can be a backup. This means that the cloned HttpHeaders and body must
* not be able to change from side effects of this HttpRequest.
*
* @return a new HTTP request instance with cloned instances of all mutable properties.
*/
public HttpRequest copy() {
final HttpHeaders bufferedHeaders = new HttpHeaders(headers);
return new HttpRequest(httpMethod, url, bufferedHeaders, body);
}
} |
Same here and in few other places. Change to `continuationToken` | public String getContinuationToken() {
return this.nextLink;
} | return this.nextLink; | public String getContinuationToken() {
return this.continuationToken;
} | class DeletedCertificatePage implements Page<DeletedCertificate> {
/**
* The link to the next page.
*/
@JsonProperty("nextLink")
private String nextLink;
/**
* The list of items.
*/
@JsonProperty("value")
private List<DeletedCertificate> items;
/**
* Gets the link to the next page. Or {@code null} if there are no more resources to fetch.
*
* @return The link to the next page.
*/
@Override
/**
* Gets the list of {@link DeletedCertificate deletedSecrets} on this page.
*
* @return The list of items in {@link List}.
*/
@Override
public List<DeletedCertificate> getItems() {
return items;
}
} | class DeletedCertificatePage implements Page<DeletedCertificate> {
/**
* The link to the next page.
*/
@JsonProperty("nextLink")
private String continuationToken;
/**
* The list of items.
*/
@JsonProperty("value")
private List<DeletedCertificate> items;
/**
* Gets the link to the next page. Or {@code null} if there are no more resources to fetch.
*
* @return The link to the next page.
*/
@Override
/**
* Gets the list of {@link DeletedCertificate deletedSecrets} on this page.
*
* @return The list of items in {@link List}.
*/
@Override
public List<DeletedCertificate> getItems() {
return items;
}
} |
Should be `hostname` rather than `hostName`. | public void addDataToContext() {
final String hostNameValue = "host-name-value";
final String entityPathValue = "entity-path-value";
final String userParentSpan = "user-parent-span";
final String openCensusSpanKey = "opencensus-span";
final String hostName = "hostName-key";
final String entityPath = "entity-path-key";
Context parentSpanContext = new Context(openCensusSpanKey, userParentSpan);
Context updatedContext = parentSpanContext.addData(hostName, hostNameValue)
.addData(entityPath, entityPathValue);
System.out.printf("HOSTNAME value: %s%n", updatedContext.getData(hostName).get());
System.out.printf("ENTITY_PATH value: %s%n", updatedContext.getData(entityPath).get());
} | Context updatedContext = parentSpanContext.addData(hostName, hostNameValue) | public void addDataToContext() {
final String hostNameValue = "host-name-value";
final String entityPathValue = "entity-path-value";
final String userParentSpan = "user-parent-span";
Context parentSpanContext = new Context(PARENT_SPAN_KEY, userParentSpan);
Context updatedContext = parentSpanContext.addData(HOST_NAME_KEY, hostNameValue)
.addData(ENTITY_PATH_KEY, entityPathValue);
System.out.printf("Hostname value: %s%n", updatedContext.getData(HOST_NAME_KEY).get());
System.out.printf("Entity Path value: %s%n", updatedContext.getData(ENTITY_PATH_KEY).get());
} | class ContextJavaDocCodeSnippets {
/**
* Code snippet for {@link Context
*/
public void constructContextObject() {
Context emptyContext = Context.NONE;
final String userParentSpan = "user-parent-span";
final String openCensusSpanKey = "opencensus-span";
Context keyValueContext = new Context(openCensusSpanKey, userParentSpan);
}
/**
* Code snippet for creating Context object using key-value pair map
*/
public void contextOfObject() {
final String key1 = "Key1";
final String value1 = "first-value";
Map<Object, Object> keyValueMap = new HashMap<>();
keyValueMap.put(key1, value1);
Context keyValueContext = Context.of(keyValueMap);
System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get());
}
/**
* Code snippet for {@link Context
*/
/**
* Code snippet for {@link Context
*/
public void getDataContext() {
final String key1 = "Key1";
final String value1 = "first-value";
Context context = new Context(key1, value1);
Optional<Object> optionalObject = context.getData(key1);
if (optionalObject.isPresent()) {
System.out.printf("Key1 value: %s%n", optionalObject.get());
} else {
System.out.println("Key1 does not exist or have data.");
}
}
} | class ContextJavaDocCodeSnippets {
/**
* Code snippet for {@link Context
*/
public void constructContextObject() {
Context emptyContext = Context.NONE;
final String userParentSpan = "user-parent-span";
Context keyValueContext = new Context(PARENT_SPAN_KEY, userParentSpan);
}
/**
* Code snippet for creating Context object using key-value pair map
*/
public void contextOfObject() {
final String key1 = "Key1";
final String value1 = "first-value";
Map<Object, Object> keyValueMap = new HashMap<>();
keyValueMap.put(key1, value1);
Context keyValueContext = Context.of(keyValueMap);
System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get());
}
/**
* Code snippet for {@link Context
*/
/**
* Code snippet for {@link Context
*/
public void getDataContext() {
final String key1 = "Key1";
final String value1 = "first-value";
Context context = new Context(key1, value1);
Optional<Object> optionalObject = context.getData(key1);
if (optionalObject.isPresent()) {
System.out.printf("Key1 value: %s%n", optionalObject.get());
} else {
System.out.println("Key1 does not exist or have data.");
}
}
} |
`hostnameKey` | public void startTracingSpan() {
String openCensusSpanKey = "opencensus-span";
Context traceContext = new Context(openCensusSpanKey, "<user-current-span>");
Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext);
System.out.printf("Span returned in the context object: %s%n",
updatedContext.getData(openCensusSpanKey).get());
String hostNameKey = "hostname";
String entityPathKey = "entity-path";
Context sendContext = new Context(openCensusSpanKey, "<user-current-span>")
.addData(entityPathKey, "entity-path").addData(hostNameKey, "hostname");
Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND);
System.out.printf("Span returned in the context object: %s%n",
updatedSendContext.getData(openCensusSpanKey).get());
String diagnosticIdKey = "diagnostic-id";
Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext,
ProcessKind.RECEIVE);
System.out.printf("Diagnostic Id: %s%n", updatedReceiveContext.getData(diagnosticIdKey).get().toString());
String spanImplContext = "span-context";
Context processContext = new Context(openCensusSpanKey, "<user-current-span>")
.addData(spanImplContext, "<user-current-span-context>");
Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext,
ProcessKind.PROCESS);
System.out.printf("Scope: %s%n", updatedProcessContext.getData("scope").get());
} | .addData(entityPathKey, "entity-path").addData(hostNameKey, "hostname"); | public void startTracingSpan() {
Context traceContext = new Context(PARENT_SPAN_KEY, "<user-current-span>");
Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext);
System.out.printf("Span returned in the context object: %s%n",
updatedContext.getData(PARENT_SPAN_KEY).get());
Context sendContext = new Context(PARENT_SPAN_KEY, "<user-current-span>")
.addData(ENTITY_PATH_KEY, "entity-path").addData(HOST_NAME_KEY, "hostname");
Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND);
System.out.printf("Span returned in the context object: %s%n",
updatedSendContext.getData(PARENT_SPAN_KEY).get());
String diagnosticIdKey = "diagnostic-id";
Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext,
ProcessKind.RECEIVE);
System.out.printf("Diagnostic Id: %s%n", updatedReceiveContext.getData(diagnosticIdKey).get().toString());
String spanImplContext = "span-context";
Context processContext = new Context(PARENT_SPAN_KEY, "<user-current-span>")
.addData(spanImplContext, "<user-current-span-context>");
Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext,
ProcessKind.PROCESS);
System.out.printf("Scope: %s%n", updatedProcessContext.getData("scope").get());
} | class TracerJavaDocCodeSnippets {
final Tracer tracer = new TracerImplementation();
/**
* Code snippet for {@link Tracer
*/
/**
* Code snippet for {@link Tracer
*/
public void endTracingSpan() {
String openCensusSpanKey = "opencensus-span";
Context traceContext = new Context(openCensusSpanKey, "<user-current-span>");
tracer.end(200, null, traceContext);
tracer.end("success", null, traceContext);
}
/**
* Code snippet for {@link Tracer
*/
public void setSpanName() {
String openCensusSpanKey = "opencensus-span-name";
Context context = tracer.setSpanName("test-span-method", Context.NONE);
System.out.printf("Span name: %s%n", context.getData(openCensusSpanKey).get().toString());
}
/**
* Code snippet for {@link Tracer
*/
public void addLink() {
String openCensusSpanKey = "opencensus-span";
Context parentContext = new Context(openCensusSpanKey, "<user-current-span>");
Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE);
tracer.addLink(spanContext);
}
/**
* Code snippet for {@link Tracer
*/
public void extractContext() {
String spanImplContext = "span-context";
Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE);
System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(spanImplContext).get());
}
private static final class TracerImplementation implements Tracer {
@Override
public Context start(String methodName, Context context) {
return null;
}
@Override
public Context start(String methodName, Context context, ProcessKind processKind) {
return null;
}
@Override
public void end(int responseCode, Throwable error, Context context) {
}
@Override
public void end(String errorCondition, Throwable error, Context context) {
}
@Override
public void setAttribute(String key, String value, Context context) {
}
@Override
public Context setSpanName(String spanName, Context context) {
return null;
}
@Override
public void addLink(Context context) {
}
@Override
public Context extractContext(String diagnosticId, Context context) {
return null;
}
}
} | class TracerJavaDocCodeSnippets {
final Tracer tracer = new TracerImplementation();
/**
* Code snippet for {@link Tracer
*/
/**
* Code snippet for {@link Tracer
*/
public void endTracingSpan() {
String openCensusSpanKey = "opencensus-span";
Context traceContext = new Context(PARENT_SPAN_KEY, "<user-current-span>");
tracer.end(200, null, traceContext);
tracer.end("success", null, traceContext);
}
/**
* Code snippet for {@link Tracer
*/
public void setSpanName() {
String openCensusSpanKey = "opencensus-span-name";
Context context = tracer.setSpanName("test-span-method", Context.NONE);
System.out.printf("Span name: %s%n", context.getData(PARENT_SPAN_KEY).get().toString());
}
/**
* Code snippet for {@link Tracer
*/
public void addLink() {
Context parentContext = new Context(PARENT_SPAN_KEY, "<user-current-span>");
Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE);
tracer.addLink(spanContext);
}
/**
* Code snippet for {@link Tracer
*/
public void extractContext() {
String spanImplContext = "span-context";
Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE);
System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(spanImplContext).get());
}
private static final class TracerImplementation implements Tracer {
@Override
public Context start(String methodName, Context context) {
return null;
}
@Override
public Context start(String methodName, Context context, ProcessKind processKind) {
return null;
}
@Override
public void end(int responseCode, Throwable error, Context context) {
}
@Override
public void end(String errorCondition, Throwable error, Context context) {
}
@Override
public void setAttribute(String key, String value, Context context) {
}
@Override
public Context setSpanName(String spanName, Context context) {
return null;
}
@Override
public void addLink(Context context) {
}
@Override
public Context extractContext(String diagnosticId, Context context) {
return null;
}
}
} |
Instead of redefining all these strings. There is a constants class you can put these into. Or at least at the top of the file. is "entity-Path" what you intend? | private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) {
return sendLinkMono.flatMap(link -> {
final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE);
return link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final BatchOptions batchOptions = new BatchOptions()
.setPartitionKey(partitionKey)
.setMaximumSizeInBytes(batchSize);
final AtomicReference<Boolean> isFirst = new AtomicReference<>(true);
return events.map(eventData -> {
Context parentContext = eventData.getContext();
if (isFirst.getAndSet(false)) {
Context entityContext = parentContext.addData("entity-Path", link.getEntityPath());
sendSpanContext.set(tracerProvider.startSpan(
entityContext.addData("hostname", link.getHostname()), ProcessKind.SEND));
}
return setSpanContext(eventData, parentContext);
}).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext));
})
.flatMap(list -> sendInternal(Flux.fromIterable(list)))
.doOnEach(signal -> {
tracerProvider.endSpan(sendSpanContext.get(), signal);
});
});
} | Context entityContext = parentContext.addData("entity-Path", link.getEntityPath()); | private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) {
return sendLinkMono.flatMap(link -> {
final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE);
return link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final BatchOptions batchOptions = new BatchOptions()
.setPartitionKey(partitionKey)
.setMaximumSizeInBytes(batchSize);
final AtomicReference<Boolean> isFirst = new AtomicReference<>(true);
return events.map(eventData -> {
Context parentContext = eventData.getContext();
if (isFirst.getAndSet(false)) {
Context entityContext = parentContext.addData(ENTITY_PATH_KEY, link.getEntityPath());
sendSpanContext.set(tracerProvider.startSpan(
entityContext.addData(HOST_NAME_KEY, link.getHostname()), ProcessKind.SEND));
}
return setSpanContext(eventData, parentContext);
}).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext));
})
.flatMap(list -> sendInternal(Flux.fromIterable(list)))
.doOnEach(signal -> {
tracerProvider.endSpan(sendSpanContext.get(), signal);
});
});
} | class EventHubAsyncProducer implements Closeable {
private static final int MAX_PARTITION_KEY_LENGTH = 128;
private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions();
private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions();
private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final EventHubProducerOptions senderOptions;
private final Mono<AmqpSendLink> sendLinkMono;
private final boolean isPartitionSender;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
/**
* Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link
* EventHubProducerOptions
* otherwise, allows the service to load balance the messages amongst available partitions.
*/
EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options,
TracerProvider tracerProvider, MessageSerializer messageSerializer) {
this.sendLinkMono = amqpSendLinkMono.cache();
this.senderOptions = options;
this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId());
this.tracerProvider = tracerProvider;
this.messageSerializer = messageSerializer;
}
/**
* Creates an {@link EventDataBatch} that can fit as many events as the transport allows.
* @return A new {@link EventDataBatch} that can fit as many events as the transport allows.
*/
public Mono<EventDataBatch> createBatch() {
return createBatch(DEFAULT_BATCH_OPTIONS);
}
/**
* Creates an {@link EventDataBatch} that can fit as many events as the transport allows.
* @param options A set of options used to configure the {@link EventDataBatch}.
* @return A new {@link EventDataBatch} that can fit as many events as the transport allows.
*/
public Mono<EventDataBatch> createBatch(BatchOptions options) {
Objects.requireNonNull(options, "'options' cannot be null.");
final BatchOptions clone = options.clone();
verifyPartitionKey(clone.getPartitionKey());
return sendLinkMono.flatMap(link -> link.getLinkSize()
.flatMap(size -> {
final int maximumLinkSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
if (clone.getMaximumSizeInBytes() > maximumLinkSize) {
return Mono.error(new IllegalArgumentException(String.format(Locale.US,
"BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).",
clone.getMaximumSizeInBytes(), maximumLinkSize)));
}
final int batchSize = clone.getMaximumSizeInBytes() > 0
? clone.getMaximumSizeInBytes()
: maximumLinkSize;
return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext));
}));
}
/**
* Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size
* allowed, an exception will be triggered and the send will fail.
* <p>
* For more information regarding the maximum event size allowed, see
* <a href="https:
* Limits</a>.
* </p>
*
* @param event Event to send to the service.
*
* @return A {@link Mono} that completes when the event is pushed to the service.
*/
public Mono<Void> send(EventData event) {
Objects.requireNonNull(event, "'event' cannot be null.");
return send(Flux.just(event));
}
/**
* Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds
* the maximum size allowed, an exception will be triggered and the send will fail.
*
* <p>
* For more information regarding the maximum event size allowed, see
* <a href="https:
* Limits</a>.
* </p>
* @param event Event to send to the service.
* @param options The set of options to consider when sending this event.
*
* @return A {@link Mono} that completes when the event is pushed to the service.
*/
public Mono<Void> send(EventData event, SendOptions options) {
Objects.requireNonNull(event, "'event' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return send(Flux.just(event), options);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
*
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Iterable<EventData> events) {
Objects.requireNonNull(events, "'events' cannot be null.");
return send(Flux.fromIterable(events));
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @param options The set of options to consider when sending this batch.
*
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Iterable<EventData> events, SendOptions options) {
Objects.requireNonNull(events, "'options' cannot be null.");
return send(Flux.fromIterable(events), options);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Flux<EventData> events) {
Objects.requireNonNull(events, "'events' cannot be null.");
return send(events, DEFAULT_SEND_OPTIONS);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @param options The set of options to consider when sending this batch.
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Flux<EventData> events, SendOptions options) {
Objects.requireNonNull(events, "'events' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return sendInternal(events, options);
}
/**
* Sends the batch to the associated Event Hub.
*
* @param batch The batch to send to the service.
* @return A {@link Mono} that completes when the batch is pushed to the service.
* @throws NullPointerException if {@code batch} is {@code null}.
* @see EventHubAsyncProducer
* @see EventHubAsyncProducer
*/
public Mono<Void> send(EventDataBatch batch) {
Objects.requireNonNull(batch, "'batch' cannot be null.");
if (batch.getEvents().isEmpty()) {
logger.info("Cannot send an EventBatch that is empty.");
return Mono.empty();
}
if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) {
logger.info("Sending batch with size[{}].", batch.getSize());
} else {
logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey());
}
final String partitionKey = batch.getPartitionKey();
final List<Message> messages = batch.getEvents().stream().map(event -> {
final Message message = messageSerializer.serialize(event);
if (!ImplUtils.isNullOrEmpty(partitionKey)) {
final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null
? new MessageAnnotations(new HashMap<>())
: message.getMessageAnnotations();
messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey);
message.setMessageAnnotations(messageAnnotations);
}
return message;
}).collect(Collectors.toList());
return sendLinkMono.flatMap(link -> messages.size() == 1
? link.send(messages.get(0))
: link.send(messages));
}
private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) {
final String partitionKey = options.getPartitionKey();
verifyPartitionKey(partitionKey);
if (tracerProvider.isEnabled()) {
return sendInternalTracingEnabled(events, partitionKey);
} else {
return sendInternalTracingDisabled(events, partitionKey);
}
}
private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) {
return sendLinkMono.flatMap(link -> {
return link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final BatchOptions batchOptions = new BatchOptions()
.setPartitionKey(partitionKey)
.setMaximumSizeInBytes(batchSize);
return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext));
})
.flatMap(list -> sendInternal(Flux.fromIterable(list)));
});
}
private EventData setSpanContext(EventData event, Context parentContext) {
Optional<Object> eventContextData = event.getContext().getData("span-context");
if (eventContextData.isPresent()) {
Object spanContextObject = eventContextData.get();
if (spanContextObject instanceof Context) {
tracerProvider.addSpanLinks((Context) eventContextData.get());
} else {
logger.warning(String.format(Locale.US,
"Event Data context type is not of type Context, but type: %s. Not adding span links.",
spanContextObject != null ? spanContextObject.getClass() : "null"));
}
return event;
} else {
Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE);
if (eventSpanContext != null) {
Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData("diagnostic-id");
if (eventDiagnosticIdOptional.isPresent()) {
event.addProperty("diagnostic-id", eventDiagnosticIdOptional.get().toString());
tracerProvider.endSpan(eventSpanContext, Signal.complete());
event.addContext("span-context", eventSpanContext);
}
}
}
return event;
}
private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) {
return eventBatches
.flatMap(this::send)
.then()
.doOnError(error -> {
logger.error("Error sending batch.", error);
});
}
private void verifyPartitionKey(String partitionKey) {
if (ImplUtils.isNullOrEmpty(partitionKey)) {
return;
}
if (isPartitionSender) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with"
+ "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to "
+ "partition '%s'.",
senderOptions.getPartitionId())));
} else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey,
MAX_PARTITION_KEY_LENGTH)));
}
}
/**
* Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service.
* @throws IOException if the underlying transport could not be closed and its resources could not be
* disposed.
*/
@Override
public void close() throws IOException {
if (!isDisposed.getAndSet(true)) {
final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout());
if (block != null) {
block.close();
}
}
}
/**
* Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then
* it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code
* maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link
* ErrorCondition
*/
private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>,
List<EventDataBatch>> {
private final String partitionKey;
private final int maxMessageSize;
private final Integer maxNumberOfBatches;
private final ErrorContextProvider contextProvider;
private volatile EventDataBatch currentBatch;
EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) {
this.maxNumberOfBatches = maxNumberOfBatches;
this.maxMessageSize = options.getMaximumSizeInBytes() > 0
? options.getMaximumSizeInBytes()
: MAX_MESSAGE_LENGTH_BYTES;
this.partitionKey = options.getPartitionKey();
this.contextProvider = contextProvider;
currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider);
}
@Override
public Supplier<List<EventDataBatch>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<EventDataBatch>, EventData> accumulator() {
return (list, event) -> {
EventDataBatch batch = currentBatch;
if (batch.tryAdd(event)) {
return;
}
if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) {
final String message = String.format(Locale.US,
"EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches);
throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message,
contextProvider.getErrorContext());
}
currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider);
currentBatch.tryAdd(event);
list.add(batch);
};
}
@Override
public BinaryOperator<List<EventDataBatch>> combiner() {
return (existing, another) -> {
existing.addAll(another);
return existing;
};
}
@Override
public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() {
return list -> {
EventDataBatch batch = currentBatch;
currentBatch = null;
if (batch != null) {
list.add(batch);
}
return list;
};
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
} | class EventHubAsyncProducer implements Closeable {
private static final int MAX_PARTITION_KEY_LENGTH = 128;
private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions();
private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions();
private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final EventHubProducerOptions senderOptions;
private final Mono<AmqpSendLink> sendLinkMono;
private final boolean isPartitionSender;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
/**
* Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link
* EventHubProducerOptions
* otherwise, allows the service to load balance the messages amongst available partitions.
*/
EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options,
TracerProvider tracerProvider, MessageSerializer messageSerializer) {
this.sendLinkMono = amqpSendLinkMono.cache();
this.senderOptions = options;
this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId());
this.tracerProvider = tracerProvider;
this.messageSerializer = messageSerializer;
}
/**
* Creates an {@link EventDataBatch} that can fit as many events as the transport allows.
* @return A new {@link EventDataBatch} that can fit as many events as the transport allows.
*/
public Mono<EventDataBatch> createBatch() {
return createBatch(DEFAULT_BATCH_OPTIONS);
}
/**
* Creates an {@link EventDataBatch} that can fit as many events as the transport allows.
* @param options A set of options used to configure the {@link EventDataBatch}.
* @return A new {@link EventDataBatch} that can fit as many events as the transport allows.
*/
public Mono<EventDataBatch> createBatch(BatchOptions options) {
Objects.requireNonNull(options, "'options' cannot be null.");
final BatchOptions clone = options.clone();
verifyPartitionKey(clone.getPartitionKey());
return sendLinkMono.flatMap(link -> link.getLinkSize()
.flatMap(size -> {
final int maximumLinkSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
if (clone.getMaximumSizeInBytes() > maximumLinkSize) {
return Mono.error(new IllegalArgumentException(String.format(Locale.US,
"BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).",
clone.getMaximumSizeInBytes(), maximumLinkSize)));
}
final int batchSize = clone.getMaximumSizeInBytes() > 0
? clone.getMaximumSizeInBytes()
: maximumLinkSize;
return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext));
}));
}
/**
* Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size
* allowed, an exception will be triggered and the send will fail.
* <p>
* For more information regarding the maximum event size allowed, see
* <a href="https:
* Limits</a>.
* </p>
*
* @param event Event to send to the service.
*
* @return A {@link Mono} that completes when the event is pushed to the service.
*/
public Mono<Void> send(EventData event) {
Objects.requireNonNull(event, "'event' cannot be null.");
return send(Flux.just(event));
}
/**
* Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds
* the maximum size allowed, an exception will be triggered and the send will fail.
*
* <p>
* For more information regarding the maximum event size allowed, see
* <a href="https:
* Limits</a>.
* </p>
* @param event Event to send to the service.
* @param options The set of options to consider when sending this event.
*
* @return A {@link Mono} that completes when the event is pushed to the service.
*/
public Mono<Void> send(EventData event, SendOptions options) {
Objects.requireNonNull(event, "'event' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return send(Flux.just(event), options);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
*
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Iterable<EventData> events) {
Objects.requireNonNull(events, "'events' cannot be null.");
return send(Flux.fromIterable(events));
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @param options The set of options to consider when sending this batch.
*
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Iterable<EventData> events, SendOptions options) {
Objects.requireNonNull(events, "'options' cannot be null.");
return send(Flux.fromIterable(events), options);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Flux<EventData> events) {
Objects.requireNonNull(events, "'events' cannot be null.");
return send(events, DEFAULT_SEND_OPTIONS);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @param options The set of options to consider when sending this batch.
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Flux<EventData> events, SendOptions options) {
Objects.requireNonNull(events, "'events' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return sendInternal(events, options);
}
/**
* Sends the batch to the associated Event Hub.
*
* @param batch The batch to send to the service.
* @return A {@link Mono} that completes when the batch is pushed to the service.
* @throws NullPointerException if {@code batch} is {@code null}.
* @see EventHubAsyncProducer
* @see EventHubAsyncProducer
*/
public Mono<Void> send(EventDataBatch batch) {
Objects.requireNonNull(batch, "'batch' cannot be null.");
if (batch.getEvents().isEmpty()) {
logger.info("Cannot send an EventBatch that is empty.");
return Mono.empty();
}
if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) {
logger.info("Sending batch with size[{}].", batch.getSize());
} else {
logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey());
}
final String partitionKey = batch.getPartitionKey();
final List<Message> messages = batch.getEvents().stream().map(event -> {
final Message message = messageSerializer.serialize(event);
if (!ImplUtils.isNullOrEmpty(partitionKey)) {
final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null
? new MessageAnnotations(new HashMap<>())
: message.getMessageAnnotations();
messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey);
message.setMessageAnnotations(messageAnnotations);
}
return message;
}).collect(Collectors.toList());
return sendLinkMono.flatMap(link -> messages.size() == 1
? link.send(messages.get(0))
: link.send(messages));
}
private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) {
final String partitionKey = options.getPartitionKey();
verifyPartitionKey(partitionKey);
if (tracerProvider.isEnabled()) {
return sendInternalTracingEnabled(events, partitionKey);
} else {
return sendInternalTracingDisabled(events, partitionKey);
}
}
private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) {
return sendLinkMono.flatMap(link -> {
return link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final BatchOptions batchOptions = new BatchOptions()
.setPartitionKey(partitionKey)
.setMaximumSizeInBytes(batchSize);
return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext));
})
.flatMap(list -> sendInternal(Flux.fromIterable(list)));
});
}
private EventData setSpanContext(EventData event, Context parentContext) {
Optional<Object> eventContextData = event.getContext().getData(SPAN_CONTEXT_KEY);
if (eventContextData.isPresent()) {
Object spanContextObject = eventContextData.get();
if (spanContextObject instanceof Context) {
tracerProvider.addSpanLinks((Context) eventContextData.get());
} else {
logger.warning(String.format(Locale.US,
"Event Data context type is not of type Context, but type: %s. Not adding span links.",
spanContextObject != null ? spanContextObject.getClass() : "null"));
}
return event;
} else {
Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE);
if (eventSpanContext != null) {
Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY);
if (eventDiagnosticIdOptional.isPresent()) {
event.addProperty(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get().toString());
tracerProvider.endSpan(eventSpanContext, Signal.complete());
event.addContext(SPAN_CONTEXT_KEY, eventSpanContext);
}
}
}
return event;
}
private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) {
return eventBatches
.flatMap(this::send)
.then()
.doOnError(error -> {
logger.error("Error sending batch.", error);
});
}
private void verifyPartitionKey(String partitionKey) {
if (ImplUtils.isNullOrEmpty(partitionKey)) {
return;
}
if (isPartitionSender) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with"
+ "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to "
+ "partition '%s'.",
senderOptions.getPartitionId())));
} else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey,
MAX_PARTITION_KEY_LENGTH)));
}
}
/**
* Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service.
* @throws IOException if the underlying transport could not be closed and its resources could not be
* disposed.
*/
@Override
public void close() throws IOException {
if (!isDisposed.getAndSet(true)) {
final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout());
if (block != null) {
block.close();
}
}
}
/**
* Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then
* it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code
* maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link
* ErrorCondition
*/
private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>,
List<EventDataBatch>> {
private final String partitionKey;
private final int maxMessageSize;
private final Integer maxNumberOfBatches;
private final ErrorContextProvider contextProvider;
private volatile EventDataBatch currentBatch;
EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) {
this.maxNumberOfBatches = maxNumberOfBatches;
this.maxMessageSize = options.getMaximumSizeInBytes() > 0
? options.getMaximumSizeInBytes()
: MAX_MESSAGE_LENGTH_BYTES;
this.partitionKey = options.getPartitionKey();
this.contextProvider = contextProvider;
currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider);
}
@Override
public Supplier<List<EventDataBatch>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<EventDataBatch>, EventData> accumulator() {
return (list, event) -> {
EventDataBatch batch = currentBatch;
if (batch.tryAdd(event)) {
return;
}
if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) {
final String message = String.format(Locale.US,
"EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches);
throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message,
contextProvider.getErrorContext());
}
currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider);
currentBatch.tryAdd(event);
list.add(batch);
};
}
@Override
public BinaryOperator<List<EventDataBatch>> combiner() {
return (existing, another) -> {
existing.addAll(another);
return existing;
};
}
@Override
public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() {
return list -> {
EventDataBatch batch = currentBatch;
currentBatch = null;
if (batch != null) {
list.add(batch);
}
return list;
};
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
} |
Use a shared constants class in event hubs so we don't have to redefine these shared strings. There is a ClientConstants class. | public void startPartitionPump(PartitionOwnership claimedOwnership) {
if (partitionPumps.containsKey(claimedOwnership.getPartitionId())) {
logger.info("Consumer is already running for this partition {}", claimedOwnership.getPartitionId());
return;
}
PartitionContext partitionContext = new PartitionContext(claimedOwnership.getPartitionId(),
claimedOwnership.getEventHubName(), claimedOwnership.getConsumerGroupName(),
claimedOwnership.getOwnerId(), claimedOwnership.getETag(), partitionManager);
PartitionProcessor partitionProcessor = this.partitionProcessorFactory.get();
partitionProcessor.initialize(partitionContext);
EventPosition startFromEventPosition;
if (claimedOwnership.getOffset() != null) {
startFromEventPosition = EventPosition.fromOffset(claimedOwnership.getOffset());
} else if (claimedOwnership.getSequenceNumber() != null) {
startFromEventPosition = EventPosition.fromSequenceNumber(claimedOwnership.getSequenceNumber());
} else {
startFromEventPosition = initialEventPosition;
}
EventHubConsumerOptions eventHubConsumerOptions = new EventHubConsumerOptions().setOwnerLevel(0L);
EventHubAsyncConsumer eventHubConsumer = eventHubAsyncClient
.createConsumer(claimedOwnership.getConsumerGroupName(), claimedOwnership.getPartitionId(),
startFromEventPosition,
eventHubConsumerOptions);
partitionPumps.put(claimedOwnership.getPartitionId(), eventHubConsumer);
eventHubConsumer.receive().subscribe(eventData -> {
try {
Context processSpanContext = startProcessTracingSpan(eventData);
if (processSpanContext.getData("span-context").isPresent()) {
eventData.addContext("span-context", processSpanContext);
}
partitionProcessor.processEvent(partitionContext, eventData).doOnEach(signal ->
endProcessTracingSpan(processSpanContext, signal)).subscribe(unused -> {
}, /* event processing returned error */ ex -> handleProcessingError(claimedOwnership,
eventHubConsumer, partitionProcessor, ex, partitionContext));
} catch (Exception ex) {
/* event processing threw an exception */
handleProcessingError(claimedOwnership, eventHubConsumer, partitionProcessor, ex, partitionContext);
}
}, /* EventHubConsumer receive() returned an error */
ex -> handleReceiveError(claimedOwnership, eventHubConsumer, partitionProcessor, ex, partitionContext),
() -> partitionProcessor.close(partitionContext, CloseReason.EVENT_PROCESSOR_SHUTDOWN));
} | if (processSpanContext.getData("span-context").isPresent()) { | public void startPartitionPump(PartitionOwnership claimedOwnership) {
if (partitionPumps.containsKey(claimedOwnership.getPartitionId())) {
logger.info("Consumer is already running for this partition {}", claimedOwnership.getPartitionId());
return;
}
PartitionContext partitionContext = new PartitionContext(claimedOwnership.getPartitionId(),
claimedOwnership.getEventHubName(), claimedOwnership.getConsumerGroupName(),
claimedOwnership.getOwnerId(), claimedOwnership.getETag(), partitionManager);
PartitionProcessor partitionProcessor = this.partitionProcessorFactory.get();
partitionProcessor.initialize(partitionContext);
EventPosition startFromEventPosition;
if (claimedOwnership.getOffset() != null) {
startFromEventPosition = EventPosition.fromOffset(claimedOwnership.getOffset());
} else if (claimedOwnership.getSequenceNumber() != null) {
startFromEventPosition = EventPosition.fromSequenceNumber(claimedOwnership.getSequenceNumber());
} else {
startFromEventPosition = initialEventPosition;
}
EventHubConsumerOptions eventHubConsumerOptions = new EventHubConsumerOptions().setOwnerLevel(0L);
EventHubAsyncConsumer eventHubConsumer = eventHubAsyncClient
.createConsumer(claimedOwnership.getConsumerGroupName(), claimedOwnership.getPartitionId(),
startFromEventPosition,
eventHubConsumerOptions);
partitionPumps.put(claimedOwnership.getPartitionId(), eventHubConsumer);
eventHubConsumer.receive().subscribe(eventData -> {
try {
Context processSpanContext = startProcessTracingSpan(eventData);
if (processSpanContext.getData(SPAN_CONTEXT_KEY).isPresent()) {
eventData.addContext(SPAN_CONTEXT_KEY, processSpanContext);
}
partitionProcessor.processEvent(partitionContext, eventData).doOnEach(signal ->
endProcessTracingSpan(processSpanContext, signal)).subscribe(unused -> {
}, /* event processing returned error */ ex -> handleProcessingError(claimedOwnership,
eventHubConsumer, partitionProcessor, ex, partitionContext));
} catch (Exception ex) {
/* event processing threw an exception */
handleProcessingError(claimedOwnership, eventHubConsumer, partitionProcessor, ex, partitionContext);
}
}, /* EventHubConsumer receive() returned an error */
ex -> handleReceiveError(claimedOwnership, eventHubConsumer, partitionProcessor, ex, partitionContext),
() -> partitionProcessor.close(partitionContext, CloseReason.EVENT_PROCESSOR_SHUTDOWN));
} | class PartitionPumpManager {
private final ClientLogger logger = new ClientLogger(PartitionPumpManager.class);
private final Map<String, EventHubAsyncConsumer> partitionPumps = new ConcurrentHashMap<>();
private final PartitionManager partitionManager;
private final Supplier<PartitionProcessor> partitionProcessorFactory;
private final EventPosition initialEventPosition;
private final EventHubAsyncClient eventHubAsyncClient;
private final TracerProvider tracerProvider;
/**
* Creates an instance of partition pump manager.
*
* @param partitionManager The partition manager that is used to store and update checkpoints.
* @param partitionProcessorFactory The partition processor factory that is used to create new instances of {@link
* PartitionProcessor} when new partition pumps are started.
* @param initialEventPosition The initial event position to use when a new partition pump is created and no
* checkpoint for the partition is available.
* @param eventHubAsyncClient The client used to receive events from the Event Hub.
*/
public PartitionPumpManager(PartitionManager partitionManager,
Supplier<PartitionProcessor> partitionProcessorFactory,
EventPosition initialEventPosition, EventHubAsyncClient eventHubAsyncClient, TracerProvider tracerProvider) {
this.partitionManager = partitionManager;
this.partitionProcessorFactory = partitionProcessorFactory;
this.initialEventPosition = initialEventPosition;
this.eventHubAsyncClient = eventHubAsyncClient;
this.tracerProvider = tracerProvider;
}
/**
* Stops all partition pumps that are actively consuming events. This method is invoked when the {@link
* EventProcessor} is requested to stop.
*/
public void stopAllPartitionPumps() {
this.partitionPumps.forEach((partitionId, eventHubConsumer) -> {
try {
eventHubConsumer.close();
} catch (Exception ex) {
logger.warning("Failed to close consumer for partition {}", partitionId, ex);
} finally {
partitionPumps.remove(partitionId);
}
});
}
/**
* Starts a new partition pump for the newly claimed partition. If the partition already has an active partition
* pump, this will not create a new consumer.
*
* @param claimedOwnership The details of partition ownership for which new partition pump is requested to start.
*/
private void handleProcessingError(PartitionOwnership claimedOwnership, EventHubAsyncConsumer eventHubConsumer,
PartitionProcessor partitionProcessor, Throwable error, PartitionContext partitionContext) {
try {
partitionProcessor.processError(partitionContext, error);
} catch (Exception ex) {
logger.warning("Failed while processing error {}", claimedOwnership.getPartitionId(), ex);
}
}
private void handleReceiveError(PartitionOwnership claimedOwnership, EventHubAsyncConsumer eventHubConsumer,
PartitionProcessor partitionProcessor, Throwable error, PartitionContext partitionContext) {
try {
partitionProcessor.processError(partitionContext, error);
CloseReason closeReason = CloseReason.EVENT_HUB_EXCEPTION;
if (error instanceof AmqpException) {
closeReason = CloseReason.LOST_PARTITION_OWNERSHIP;
}
partitionProcessor.close(partitionContext, closeReason);
} catch (Exception ex) {
logger.warning("Failed while processing error on receive {}", claimedOwnership.getPartitionId(), ex);
} finally {
try {
eventHubConsumer.close();
} catch (IOException ex) {
logger.warning("Failed to close EventHubConsumer for partition {}", claimedOwnership.getPartitionId(),
ex);
} finally {
partitionPumps.remove(claimedOwnership.getPartitionId());
}
}
}
/*
* Starts a new process tracing span and attached context the EventData object for users.
*/
private Context startProcessTracingSpan(EventData eventData) {
Object diagnosticId = eventData.getProperties().get("diagnostic-id");
if (diagnosticId == null || !tracerProvider.isEnabled()) {
return Context.NONE;
}
Context spanContext = tracerProvider.extractContext(diagnosticId.toString(), Context.NONE);
return tracerProvider.startSpan(spanContext, ProcessKind.PROCESS);
}
/*
* Ends the process tracing span and the scope of that span.
*/
private void endProcessTracingSpan(Context processSpanContext, Signal<Void> signal) {
Optional<Object> spanScope = processSpanContext.getData("scope");
if (!spanScope.isPresent() || !tracerProvider.isEnabled()) {
return;
}
if (spanScope.get() instanceof Closeable) {
Closeable close = (Closeable) processSpanContext.getData("scope").get();
try {
close.close();
tracerProvider.endSpan(processSpanContext, signal);
} catch (IOException ioException) {
logger.error("EventProcessor.run() endTracingSpan().close() failed with an error %s", ioException);
}
} else {
logger.warning(String.format(Locale.US,
"Process span scope type is not of type Closeable, but type: %s. Not closing the scope and span",
spanScope.get() != null ? spanScope.getClass() : "null"));
}
}
} | class PartitionPumpManager {
private final ClientLogger logger = new ClientLogger(PartitionPumpManager.class);
private final Map<String, EventHubAsyncConsumer> partitionPumps = new ConcurrentHashMap<>();
private final PartitionManager partitionManager;
private final Supplier<PartitionProcessor> partitionProcessorFactory;
private final EventPosition initialEventPosition;
private final EventHubAsyncClient eventHubAsyncClient;
private final TracerProvider tracerProvider;
/**
* Creates an instance of partition pump manager.
*
* @param partitionManager The partition manager that is used to store and update checkpoints.
* @param partitionProcessorFactory The partition processor factory that is used to create new instances of {@link
* PartitionProcessor} when new partition pumps are started.
* @param initialEventPosition The initial event position to use when a new partition pump is created and no
* checkpoint for the partition is available.
* @param eventHubAsyncClient The client used to receive events from the Event Hub.
*/
public PartitionPumpManager(PartitionManager partitionManager,
Supplier<PartitionProcessor> partitionProcessorFactory,
EventPosition initialEventPosition, EventHubAsyncClient eventHubAsyncClient, TracerProvider tracerProvider) {
this.partitionManager = partitionManager;
this.partitionProcessorFactory = partitionProcessorFactory;
this.initialEventPosition = initialEventPosition;
this.eventHubAsyncClient = eventHubAsyncClient;
this.tracerProvider = tracerProvider;
}
/**
* Stops all partition pumps that are actively consuming events. This method is invoked when the {@link
* EventProcessor} is requested to stop.
*/
public void stopAllPartitionPumps() {
this.partitionPumps.forEach((partitionId, eventHubConsumer) -> {
try {
eventHubConsumer.close();
} catch (Exception ex) {
logger.warning("Failed to close consumer for partition {}", partitionId, ex);
} finally {
partitionPumps.remove(partitionId);
}
});
}
/**
* Starts a new partition pump for the newly claimed partition. If the partition already has an active partition
* pump, this will not create a new consumer.
*
* @param claimedOwnership The details of partition ownership for which new partition pump is requested to start.
*/
private void handleProcessingError(PartitionOwnership claimedOwnership, EventHubAsyncConsumer eventHubConsumer,
PartitionProcessor partitionProcessor, Throwable error, PartitionContext partitionContext) {
try {
partitionProcessor.processError(partitionContext, error);
} catch (Exception ex) {
logger.warning("Failed while processing error {}", claimedOwnership.getPartitionId(), ex);
}
}
private void handleReceiveError(PartitionOwnership claimedOwnership, EventHubAsyncConsumer eventHubConsumer,
PartitionProcessor partitionProcessor, Throwable error, PartitionContext partitionContext) {
try {
partitionProcessor.processError(partitionContext, error);
CloseReason closeReason = CloseReason.EVENT_HUB_EXCEPTION;
if (error instanceof AmqpException) {
closeReason = CloseReason.LOST_PARTITION_OWNERSHIP;
}
partitionProcessor.close(partitionContext, closeReason);
} catch (Exception ex) {
logger.warning("Failed while processing error on receive {}", claimedOwnership.getPartitionId(), ex);
} finally {
try {
eventHubConsumer.close();
} catch (IOException ex) {
logger.warning("Failed to close EventHubConsumer for partition {}", claimedOwnership.getPartitionId(),
ex);
} finally {
partitionPumps.remove(claimedOwnership.getPartitionId());
}
}
}
/*
* Starts a new process tracing span and attached context the EventData object for users.
*/
private Context startProcessTracingSpan(EventData eventData) {
Object diagnosticId = eventData.getProperties().get(DIAGNOSTIC_ID_KEY);
if (diagnosticId == null || !tracerProvider.isEnabled()) {
return Context.NONE;
}
Context spanContext = tracerProvider.extractContext(diagnosticId.toString(), Context.NONE);
return tracerProvider.startSpan(spanContext, ProcessKind.PROCESS);
}
/*
* Ends the process tracing span and the scope of that span.
*/
private void endProcessTracingSpan(Context processSpanContext, Signal<Void> signal) {
Optional<Object> spanScope = processSpanContext.getData(SCOPE_KEY);
if (!spanScope.isPresent() || !tracerProvider.isEnabled()) {
return;
}
if (spanScope.get() instanceof Closeable) {
Closeable close = (Closeable) processSpanContext.getData(SCOPE_KEY).get();
try {
close.close();
tracerProvider.endSpan(processSpanContext, signal);
} catch (IOException ioException) {
logger.error("EventProcessor.run() endTracingSpan().close() failed with an error %s", ioException);
}
} else {
logger.warning(String.format(Locale.US,
"Process span scope type is not of type Closeable, but type: %s. Not closing the scope and span",
spanScope.get() != null ? spanScope.getClass() : "null"));
}
}
} |
There is a ClientConstants class. | private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) {
return sendLinkMono.flatMap(link -> {
final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE);
return link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final BatchOptions batchOptions = new BatchOptions()
.setPartitionKey(partitionKey)
.setMaximumSizeInBytes(batchSize);
final AtomicReference<Boolean> isFirst = new AtomicReference<>(true);
return events.map(eventData -> {
Context parentContext = eventData.getContext();
if (isFirst.getAndSet(false)) {
Context entityContext = parentContext.addData("entity-Path", link.getEntityPath());
sendSpanContext.set(tracerProvider.startSpan(
entityContext.addData("hostname", link.getHostname()), ProcessKind.SEND));
}
return setSpanContext(eventData, parentContext);
}).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext));
})
.flatMap(list -> sendInternal(Flux.fromIterable(list)))
.doOnEach(signal -> {
tracerProvider.endSpan(sendSpanContext.get(), signal);
});
});
} | Context entityContext = parentContext.addData("entity-Path", link.getEntityPath()); | private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) {
return sendLinkMono.flatMap(link -> {
final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE);
return link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final BatchOptions batchOptions = new BatchOptions()
.setPartitionKey(partitionKey)
.setMaximumSizeInBytes(batchSize);
final AtomicReference<Boolean> isFirst = new AtomicReference<>(true);
return events.map(eventData -> {
Context parentContext = eventData.getContext();
if (isFirst.getAndSet(false)) {
Context entityContext = parentContext.addData(ENTITY_PATH_KEY, link.getEntityPath());
sendSpanContext.set(tracerProvider.startSpan(
entityContext.addData(HOST_NAME_KEY, link.getHostname()), ProcessKind.SEND));
}
return setSpanContext(eventData, parentContext);
}).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext));
})
.flatMap(list -> sendInternal(Flux.fromIterable(list)))
.doOnEach(signal -> {
tracerProvider.endSpan(sendSpanContext.get(), signal);
});
});
} | class EventHubAsyncProducer implements Closeable {
private static final int MAX_PARTITION_KEY_LENGTH = 128;
private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions();
private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions();
private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final EventHubProducerOptions senderOptions;
private final Mono<AmqpSendLink> sendLinkMono;
private final boolean isPartitionSender;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
/**
* Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link
* EventHubProducerOptions
* otherwise, allows the service to load balance the messages amongst available partitions.
*/
EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options,
TracerProvider tracerProvider, MessageSerializer messageSerializer) {
this.sendLinkMono = amqpSendLinkMono.cache();
this.senderOptions = options;
this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId());
this.tracerProvider = tracerProvider;
this.messageSerializer = messageSerializer;
}
/**
* Creates an {@link EventDataBatch} that can fit as many events as the transport allows.
* @return A new {@link EventDataBatch} that can fit as many events as the transport allows.
*/
public Mono<EventDataBatch> createBatch() {
return createBatch(DEFAULT_BATCH_OPTIONS);
}
/**
* Creates an {@link EventDataBatch} that can fit as many events as the transport allows.
* @param options A set of options used to configure the {@link EventDataBatch}.
* @return A new {@link EventDataBatch} that can fit as many events as the transport allows.
*/
public Mono<EventDataBatch> createBatch(BatchOptions options) {
Objects.requireNonNull(options, "'options' cannot be null.");
final BatchOptions clone = options.clone();
verifyPartitionKey(clone.getPartitionKey());
return sendLinkMono.flatMap(link -> link.getLinkSize()
.flatMap(size -> {
final int maximumLinkSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
if (clone.getMaximumSizeInBytes() > maximumLinkSize) {
return Mono.error(new IllegalArgumentException(String.format(Locale.US,
"BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).",
clone.getMaximumSizeInBytes(), maximumLinkSize)));
}
final int batchSize = clone.getMaximumSizeInBytes() > 0
? clone.getMaximumSizeInBytes()
: maximumLinkSize;
return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext));
}));
}
/**
* Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size
* allowed, an exception will be triggered and the send will fail.
* <p>
* For more information regarding the maximum event size allowed, see
* <a href="https:
* Limits</a>.
* </p>
*
* @param event Event to send to the service.
*
* @return A {@link Mono} that completes when the event is pushed to the service.
*/
public Mono<Void> send(EventData event) {
Objects.requireNonNull(event, "'event' cannot be null.");
return send(Flux.just(event));
}
/**
* Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds
* the maximum size allowed, an exception will be triggered and the send will fail.
*
* <p>
* For more information regarding the maximum event size allowed, see
* <a href="https:
* Limits</a>.
* </p>
* @param event Event to send to the service.
* @param options The set of options to consider when sending this event.
*
* @return A {@link Mono} that completes when the event is pushed to the service.
*/
public Mono<Void> send(EventData event, SendOptions options) {
Objects.requireNonNull(event, "'event' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return send(Flux.just(event), options);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
*
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Iterable<EventData> events) {
Objects.requireNonNull(events, "'events' cannot be null.");
return send(Flux.fromIterable(events));
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @param options The set of options to consider when sending this batch.
*
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Iterable<EventData> events, SendOptions options) {
Objects.requireNonNull(events, "'options' cannot be null.");
return send(Flux.fromIterable(events), options);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Flux<EventData> events) {
Objects.requireNonNull(events, "'events' cannot be null.");
return send(events, DEFAULT_SEND_OPTIONS);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @param options The set of options to consider when sending this batch.
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Flux<EventData> events, SendOptions options) {
Objects.requireNonNull(events, "'events' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return sendInternal(events, options);
}
/**
* Sends the batch to the associated Event Hub.
*
* @param batch The batch to send to the service.
* @return A {@link Mono} that completes when the batch is pushed to the service.
* @throws NullPointerException if {@code batch} is {@code null}.
* @see EventHubAsyncProducer
* @see EventHubAsyncProducer
*/
public Mono<Void> send(EventDataBatch batch) {
Objects.requireNonNull(batch, "'batch' cannot be null.");
if (batch.getEvents().isEmpty()) {
logger.info("Cannot send an EventBatch that is empty.");
return Mono.empty();
}
if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) {
logger.info("Sending batch with size[{}].", batch.getSize());
} else {
logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey());
}
final String partitionKey = batch.getPartitionKey();
final List<Message> messages = batch.getEvents().stream().map(event -> {
final Message message = messageSerializer.serialize(event);
if (!ImplUtils.isNullOrEmpty(partitionKey)) {
final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null
? new MessageAnnotations(new HashMap<>())
: message.getMessageAnnotations();
messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey);
message.setMessageAnnotations(messageAnnotations);
}
return message;
}).collect(Collectors.toList());
return sendLinkMono.flatMap(link -> messages.size() == 1
? link.send(messages.get(0))
: link.send(messages));
}
private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) {
final String partitionKey = options.getPartitionKey();
verifyPartitionKey(partitionKey);
if (tracerProvider.isEnabled()) {
return sendInternalTracingEnabled(events, partitionKey);
} else {
return sendInternalTracingDisabled(events, partitionKey);
}
}
private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) {
return sendLinkMono.flatMap(link -> {
return link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final BatchOptions batchOptions = new BatchOptions()
.setPartitionKey(partitionKey)
.setMaximumSizeInBytes(batchSize);
return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext));
})
.flatMap(list -> sendInternal(Flux.fromIterable(list)));
});
}
private EventData setSpanContext(EventData event, Context parentContext) {
Optional<Object> eventContextData = event.getContext().getData("span-context");
if (eventContextData.isPresent()) {
Object spanContextObject = eventContextData.get();
if (spanContextObject instanceof Context) {
tracerProvider.addSpanLinks((Context) eventContextData.get());
} else {
logger.warning(String.format(Locale.US,
"Event Data context type is not of type Context, but type: %s. Not adding span links.",
spanContextObject != null ? spanContextObject.getClass() : "null"));
}
return event;
} else {
Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE);
if (eventSpanContext != null) {
Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData("diagnostic-id");
if (eventDiagnosticIdOptional.isPresent()) {
event.addProperty("diagnostic-id", eventDiagnosticIdOptional.get().toString());
tracerProvider.endSpan(eventSpanContext, Signal.complete());
event.addContext("span-context", eventSpanContext);
}
}
}
return event;
}
private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) {
return eventBatches
.flatMap(this::send)
.then()
.doOnError(error -> {
logger.error("Error sending batch.", error);
});
}
private void verifyPartitionKey(String partitionKey) {
if (ImplUtils.isNullOrEmpty(partitionKey)) {
return;
}
if (isPartitionSender) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with"
+ "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to "
+ "partition '%s'.",
senderOptions.getPartitionId())));
} else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey,
MAX_PARTITION_KEY_LENGTH)));
}
}
/**
* Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service.
* @throws IOException if the underlying transport could not be closed and its resources could not be
* disposed.
*/
@Override
public void close() throws IOException {
if (!isDisposed.getAndSet(true)) {
final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout());
if (block != null) {
block.close();
}
}
}
/**
* Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then
* it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code
* maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link
* ErrorCondition
*/
private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>,
List<EventDataBatch>> {
private final String partitionKey;
private final int maxMessageSize;
private final Integer maxNumberOfBatches;
private final ErrorContextProvider contextProvider;
private volatile EventDataBatch currentBatch;
EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) {
this.maxNumberOfBatches = maxNumberOfBatches;
this.maxMessageSize = options.getMaximumSizeInBytes() > 0
? options.getMaximumSizeInBytes()
: MAX_MESSAGE_LENGTH_BYTES;
this.partitionKey = options.getPartitionKey();
this.contextProvider = contextProvider;
currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider);
}
@Override
public Supplier<List<EventDataBatch>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<EventDataBatch>, EventData> accumulator() {
return (list, event) -> {
EventDataBatch batch = currentBatch;
if (batch.tryAdd(event)) {
return;
}
if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) {
final String message = String.format(Locale.US,
"EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches);
throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message,
contextProvider.getErrorContext());
}
currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider);
currentBatch.tryAdd(event);
list.add(batch);
};
}
@Override
public BinaryOperator<List<EventDataBatch>> combiner() {
return (existing, another) -> {
existing.addAll(another);
return existing;
};
}
@Override
public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() {
return list -> {
EventDataBatch batch = currentBatch;
currentBatch = null;
if (batch != null) {
list.add(batch);
}
return list;
};
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
} | class EventHubAsyncProducer implements Closeable {
private static final int MAX_PARTITION_KEY_LENGTH = 128;
private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions();
private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions();
private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final EventHubProducerOptions senderOptions;
private final Mono<AmqpSendLink> sendLinkMono;
private final boolean isPartitionSender;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
/**
* Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link
* EventHubProducerOptions
* otherwise, allows the service to load balance the messages amongst available partitions.
*/
EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options,
TracerProvider tracerProvider, MessageSerializer messageSerializer) {
this.sendLinkMono = amqpSendLinkMono.cache();
this.senderOptions = options;
this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId());
this.tracerProvider = tracerProvider;
this.messageSerializer = messageSerializer;
}
/**
* Creates an {@link EventDataBatch} that can fit as many events as the transport allows.
* @return A new {@link EventDataBatch} that can fit as many events as the transport allows.
*/
public Mono<EventDataBatch> createBatch() {
return createBatch(DEFAULT_BATCH_OPTIONS);
}
/**
* Creates an {@link EventDataBatch} that can fit as many events as the transport allows.
* @param options A set of options used to configure the {@link EventDataBatch}.
* @return A new {@link EventDataBatch} that can fit as many events as the transport allows.
*/
public Mono<EventDataBatch> createBatch(BatchOptions options) {
Objects.requireNonNull(options, "'options' cannot be null.");
final BatchOptions clone = options.clone();
verifyPartitionKey(clone.getPartitionKey());
return sendLinkMono.flatMap(link -> link.getLinkSize()
.flatMap(size -> {
final int maximumLinkSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
if (clone.getMaximumSizeInBytes() > maximumLinkSize) {
return Mono.error(new IllegalArgumentException(String.format(Locale.US,
"BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).",
clone.getMaximumSizeInBytes(), maximumLinkSize)));
}
final int batchSize = clone.getMaximumSizeInBytes() > 0
? clone.getMaximumSizeInBytes()
: maximumLinkSize;
return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext));
}));
}
/**
* Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size
* allowed, an exception will be triggered and the send will fail.
* <p>
* For more information regarding the maximum event size allowed, see
* <a href="https:
* Limits</a>.
* </p>
*
* @param event Event to send to the service.
*
* @return A {@link Mono} that completes when the event is pushed to the service.
*/
public Mono<Void> send(EventData event) {
Objects.requireNonNull(event, "'event' cannot be null.");
return send(Flux.just(event));
}
/**
* Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds
* the maximum size allowed, an exception will be triggered and the send will fail.
*
* <p>
* For more information regarding the maximum event size allowed, see
* <a href="https:
* Limits</a>.
* </p>
* @param event Event to send to the service.
* @param options The set of options to consider when sending this event.
*
* @return A {@link Mono} that completes when the event is pushed to the service.
*/
public Mono<Void> send(EventData event, SendOptions options) {
Objects.requireNonNull(event, "'event' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return send(Flux.just(event), options);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
*
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Iterable<EventData> events) {
Objects.requireNonNull(events, "'events' cannot be null.");
return send(Flux.fromIterable(events));
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @param options The set of options to consider when sending this batch.
*
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Iterable<EventData> events, SendOptions options) {
Objects.requireNonNull(events, "'options' cannot be null.");
return send(Flux.fromIterable(events), options);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Flux<EventData> events) {
Objects.requireNonNull(events, "'events' cannot be null.");
return send(events, DEFAULT_SEND_OPTIONS);
}
/**
* Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the
* maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message
* size is the max amount allowed on the link.
* @param events Events to send to the service.
* @param options The set of options to consider when sending this batch.
* @return A {@link Mono} that completes when all events are pushed to the service.
*/
public Mono<Void> send(Flux<EventData> events, SendOptions options) {
Objects.requireNonNull(events, "'events' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return sendInternal(events, options);
}
/**
* Sends the batch to the associated Event Hub.
*
* @param batch The batch to send to the service.
* @return A {@link Mono} that completes when the batch is pushed to the service.
* @throws NullPointerException if {@code batch} is {@code null}.
* @see EventHubAsyncProducer
* @see EventHubAsyncProducer
*/
public Mono<Void> send(EventDataBatch batch) {
Objects.requireNonNull(batch, "'batch' cannot be null.");
if (batch.getEvents().isEmpty()) {
logger.info("Cannot send an EventBatch that is empty.");
return Mono.empty();
}
if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) {
logger.info("Sending batch with size[{}].", batch.getSize());
} else {
logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey());
}
final String partitionKey = batch.getPartitionKey();
final List<Message> messages = batch.getEvents().stream().map(event -> {
final Message message = messageSerializer.serialize(event);
if (!ImplUtils.isNullOrEmpty(partitionKey)) {
final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null
? new MessageAnnotations(new HashMap<>())
: message.getMessageAnnotations();
messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey);
message.setMessageAnnotations(messageAnnotations);
}
return message;
}).collect(Collectors.toList());
return sendLinkMono.flatMap(link -> messages.size() == 1
? link.send(messages.get(0))
: link.send(messages));
}
private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) {
final String partitionKey = options.getPartitionKey();
verifyPartitionKey(partitionKey);
if (tracerProvider.isEnabled()) {
return sendInternalTracingEnabled(events, partitionKey);
} else {
return sendInternalTracingDisabled(events, partitionKey);
}
}
private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) {
return sendLinkMono.flatMap(link -> {
return link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final BatchOptions batchOptions = new BatchOptions()
.setPartitionKey(partitionKey)
.setMaximumSizeInBytes(batchSize);
return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext));
})
.flatMap(list -> sendInternal(Flux.fromIterable(list)));
});
}
private EventData setSpanContext(EventData event, Context parentContext) {
Optional<Object> eventContextData = event.getContext().getData(SPAN_CONTEXT_KEY);
if (eventContextData.isPresent()) {
Object spanContextObject = eventContextData.get();
if (spanContextObject instanceof Context) {
tracerProvider.addSpanLinks((Context) eventContextData.get());
} else {
logger.warning(String.format(Locale.US,
"Event Data context type is not of type Context, but type: %s. Not adding span links.",
spanContextObject != null ? spanContextObject.getClass() : "null"));
}
return event;
} else {
Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE);
if (eventSpanContext != null) {
Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY);
if (eventDiagnosticIdOptional.isPresent()) {
event.addProperty(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get().toString());
tracerProvider.endSpan(eventSpanContext, Signal.complete());
event.addContext(SPAN_CONTEXT_KEY, eventSpanContext);
}
}
}
return event;
}
private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) {
return eventBatches
.flatMap(this::send)
.then()
.doOnError(error -> {
logger.error("Error sending batch.", error);
});
}
private void verifyPartitionKey(String partitionKey) {
if (ImplUtils.isNullOrEmpty(partitionKey)) {
return;
}
if (isPartitionSender) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with"
+ "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to "
+ "partition '%s'.",
senderOptions.getPartitionId())));
} else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey,
MAX_PARTITION_KEY_LENGTH)));
}
}
/**
* Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service.
* @throws IOException if the underlying transport could not be closed and its resources could not be
* disposed.
*/
@Override
public void close() throws IOException {
if (!isDisposed.getAndSet(true)) {
final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout());
if (block != null) {
block.close();
}
}
}
/**
* Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then
* it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code
* maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link
* ErrorCondition
*/
private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>,
List<EventDataBatch>> {
private final String partitionKey;
private final int maxMessageSize;
private final Integer maxNumberOfBatches;
private final ErrorContextProvider contextProvider;
private volatile EventDataBatch currentBatch;
EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) {
this.maxNumberOfBatches = maxNumberOfBatches;
this.maxMessageSize = options.getMaximumSizeInBytes() > 0
? options.getMaximumSizeInBytes()
: MAX_MESSAGE_LENGTH_BYTES;
this.partitionKey = options.getPartitionKey();
this.contextProvider = contextProvider;
currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider);
}
@Override
public Supplier<List<EventDataBatch>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<EventDataBatch>, EventData> accumulator() {
return (list, event) -> {
EventDataBatch batch = currentBatch;
if (batch.tryAdd(event)) {
return;
}
if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) {
final String message = String.format(Locale.US,
"EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches);
throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message,
contextProvider.getErrorContext());
}
currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider);
currentBatch.tryAdd(event);
list.add(batch);
};
}
@Override
public BinaryOperator<List<EventDataBatch>> combiner() {
return (existing, another) -> {
existing.addAll(another);
return existing;
};
}
@Override
public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() {
return list -> {
EventDataBatch batch = currentBatch;
currentBatch = null;
if (batch != null) {
list.add(batch);
}
return list;
};
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
} |
Where is the the RuntimeException being thrown from? I'm surprised that the `withContext(…)` or underlying RestProxy isn't bubbling this to downstream. | public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
} | try { | public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | class ConfigurationAsyncClient {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class);
private static final String ETAG_ANY = "*";
private static final String RANGE_QUERY = "items=%s";
private final String serviceEndpoint;
private final ConfigurationService service;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceEndpoint The URL string for the App Configuration service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
ConfigurationAsyncClient(String serviceEndpoint, HttpPipeline pipeline) {
this.service = RestProxy.create(ConfigurationService.class, pipeline);
this.serviceEndpoint = serviceEndpoint;
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add, or optionally, null if a setting with
* label is desired.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(String key, String label, String value) {
return withContext(
context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
}
/**
* Adds a configuration value in the service if that key and label does not exist.The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param setting The setting to add based on its key and optional label combination.
* @return The {@link ConfigurationSetting} that was created, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null,
getETagValue(ETAG_ANY), context)
.doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue()))
.onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper)
.doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, or optionally, null if a setting with
* label is desired.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setSetting(String key, String label, String value) {
try {
return withContext(
context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value),
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* If {@link ConfigurationSetting
* setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value
* (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's etag does not match, or the setting exists and is
* locked.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> setSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting,
ifMatchETag, null, context)
.doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label) {
try {
return getSetting(key, label, null);
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code asOfDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) {
try {
return withContext(
context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime,
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse
*
* @param setting The setting to retrieve.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime asOfDateTime,
boolean ifChanged) {
try {
return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime,
boolean onlyIfChanged, Context context) {
validateSetting(setting);
final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null;
return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete, or optionally, null if a setting with
* label is desired.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteSetting(String key, String label) {
try {
return withContext(
context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current etag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> deleteSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag,
null, context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error));
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to lock.
* @param label The label of configuration setting to lock, or optionally, null if a setting with label is desired.
* @return The {@link ConfigurationSetting} that was locked, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label) {
try {
return withContext(context -> setReadOnly(
new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The setting to lock based on its key and optional label combination.
* @return A REST response containing the locked ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> setReadOnly(setting, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error));
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly
*
* @param key The key of configuration setting to unlock.
* @param label The label of configuration setting to unlock, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} that was unlocked, or an empty Mono is also returned if a key collision
* occurs or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> clearReadOnly(String key, String label) {
try {
return withContext(context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse
*
* @param setting The setting to unlock based on its key and optional label combination.
* @return A REST response containing the unlocked ConfigurationSetting, or {@code null} if didn't exist. {@code
* null} is also returned if the {@link ConfigurationSetting
* throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> clearReadOnly(setting, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(),
null, null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting))
.doOnSuccess(
response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue()))
.doOnError(
error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error));
}
/**
* Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings}
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux
* contains all of the current settings in the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) {
try {
return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)),
continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex))));
}
}
PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector, Context context) {
return new PagedFlux<>(() -> listFirstPageSettings(selector, context),
continuationToken -> listNextPageSettings(context, continuationToken));
}
private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) {
try {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
return service.listKeyValues(serviceEndpoint, continuationToken, context)
.doOnSubscribe(
ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken))
.doOnError(
error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken,
error));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector selector, Context context) {
try {
if (selector == null) {
return service.listKeyValues(serviceEndpoint, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings"))
.doOnSuccess(response -> logger.info("Listed all ConfigurationSettings"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error));
}
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
return service.listKeyValues(serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), context)
.doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", selector))
.doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", selector, error));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* after a period of time. The service maintains change history for up to 7 days.
*
* If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code options}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions}
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) {
try {
return new PagedFlux<>(() ->
withContext(context -> listSettingRevisionsFirstPage(selector, context)),
continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex))));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result;
if (selector != null) {
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null;
result =
service.listKeyValueRevisions(
serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context)
.doOnRequest(
ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector))
.doOnError(
error -> logger
.warning("Failed to list ConfigurationSetting revisions - {}", selector, error));
} else {
result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions"))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error));
}
return result;
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result = service
.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result;
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) {
return new PagedFlux<>(() ->
listSettingRevisionsFirstPage(selector, context),
continuationToken -> listSettingRevisionsNextPage(continuationToken, context));
}
private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) {
Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context));
}
private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings(
PagedResponse<ConfigurationSetting> page, Context context) {
return ImplUtils.extractAndFetch(page, context, this::listSettings);
}
/*
* Azure Configuration service requires that the etag value is surrounded in quotation marks.
*
* @param etag The etag to get the value for. If null is pass in, an empty string is returned.
* @return The etag surrounded by quotations. (ex. "etag")
*/
private static String getETagValue(String etag) {
return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\"";
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
private static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since
* add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return
* this status when the configuration doesn't exist.
*
* @param throwable Error response from the service.
*
* @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException,
* otherwise the throwable is returned unmodified.
*/
private static Throwable addSettingExceptionMapper(Throwable throwable) {
if (!(throwable instanceof ResourceNotFoundException)) {
return throwable;
}
ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable;
return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse());
}
} | class ConfigurationAsyncClient {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class);
private static final String ETAG_ANY = "*";
private static final String RANGE_QUERY = "items=%s";
private final String serviceEndpoint;
private final ConfigurationService service;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceEndpoint The URL string for the App Configuration service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
ConfigurationAsyncClient(String serviceEndpoint, HttpPipeline pipeline) {
this.service = RestProxy.create(ConfigurationService.class, pipeline);
this.serviceEndpoint = serviceEndpoint;
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add, or optionally, null if a setting with
* label is desired.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(String key, String label, String value) {
try {
return withContext(
context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist.The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param setting The setting to add based on its key and optional label combination.
* @return The {@link ConfigurationSetting} that was created, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null,
getETagValue(ETAG_ANY), context)
.doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue()))
.onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper)
.doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, or optionally, null if a setting with
* label is desired.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setSetting(String key, String label, String value) {
try {
return withContext(
context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value),
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* If {@link ConfigurationSetting
* setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value
* (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's etag does not match, or the setting exists and is
* locked.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> setSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting,
ifMatchETag, null, context)
.doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label) {
try {
return getSetting(key, label, null);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code asOfDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) {
try {
return withContext(
context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime,
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse
*
* @param setting The setting to retrieve.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime asOfDateTime,
boolean ifChanged) {
try {
return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime,
boolean onlyIfChanged, Context context) {
validateSetting(setting);
final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null;
return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete, or optionally, null if a setting with
* label is desired.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteSetting(String key, String label) {
try {
return withContext(
context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current etag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> deleteSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag,
null, context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error));
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to lock.
* @param label The label of configuration setting to lock, or optionally, null if a setting with label is desired.
* @return The {@link ConfigurationSetting} that was locked, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label) {
try {
return withContext(context -> setReadOnly(
new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The setting to lock based on its key and optional label combination.
* @return A REST response containing the locked ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> setReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error));
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly
*
* @param key The key of configuration setting to unlock.
* @param label The label of configuration setting to unlock, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} that was unlocked, or an empty Mono is also returned if a key collision
* occurs or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> clearReadOnly(String key, String label) {
try {
return withContext(
context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse
*
* @param setting The setting to unlock based on its key and optional label combination.
* @return A REST response containing the unlocked ConfigurationSetting, or {@code null} if didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> clearReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(),
null, null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting))
.doOnSuccess(
response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue()))
.doOnError(
error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error));
}
/**
* Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings}
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux
* contains all of the current settings in the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) {
try {
return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)),
continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector, Context context) {
return new PagedFlux<>(() -> listFirstPageSettings(selector, context),
continuationToken -> listNextPageSettings(context, continuationToken));
}
private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) {
try {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
return service.listKeyValues(serviceEndpoint, continuationToken, context)
.doOnSubscribe(
ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken))
.doOnError(
error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector selector, Context context) {
try {
if (selector == null) {
return service.listKeyValues(serviceEndpoint, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings"))
.doOnSuccess(response -> logger.info("Listed all ConfigurationSettings"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error));
}
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
return service.listKeyValues(serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), context)
.doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", selector))
.doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", selector, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* after a period of time. The service maintains change history for up to 7 days.
*
* If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code options}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions}
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) {
try {
return new PagedFlux<>(() ->
withContext(context -> listSettingRevisionsFirstPage(selector, context)),
continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result;
if (selector != null) {
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null;
result =
service.listKeyValueRevisions(
serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context)
.doOnRequest(
ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector))
.doOnError(
error -> logger
.warning("Failed to list ConfigurationSetting revisions - {}", selector, error));
} else {
result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions"))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error));
}
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result = service
.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) {
return new PagedFlux<>(() ->
listSettingRevisionsFirstPage(selector, context),
continuationToken -> listSettingRevisionsNextPage(continuationToken, context));
}
private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) {
Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context));
}
private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings(
PagedResponse<ConfigurationSetting> page, Context context) {
return ImplUtils.extractAndFetch(page, context, this::listSettings);
}
/*
* Azure Configuration service requires that the etag value is surrounded in quotation marks.
*
* @param etag The etag to get the value for. If null is pass in, an empty string is returned.
* @return The etag surrounded by quotations. (ex. "etag")
*/
private static String getETagValue(String etag) {
return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\"";
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
private static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since
* add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return
* this status when the configuration doesn't exist.
*
* @param throwable Error response from the service.
*
* @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException,
* otherwise the throwable is returned unmodified.
*/
private static Throwable addSettingExceptionMapper(Throwable throwable) {
if (!(throwable instanceof ResourceNotFoundException)) {
return throwable;
}
ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable;
return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse());
}
} |
The exception is thrown in one of the methods in this class `validateSetting(setting)`. Besides, the purpose of this change is to catch all runtime exceptions before the user code - sdk api handshake and return them in the error channel. | public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
} | try { | public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | class ConfigurationAsyncClient {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class);
private static final String ETAG_ANY = "*";
private static final String RANGE_QUERY = "items=%s";
private final String serviceEndpoint;
private final ConfigurationService service;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceEndpoint The URL string for the App Configuration service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
ConfigurationAsyncClient(String serviceEndpoint, HttpPipeline pipeline) {
this.service = RestProxy.create(ConfigurationService.class, pipeline);
this.serviceEndpoint = serviceEndpoint;
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add, or optionally, null if a setting with
* label is desired.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(String key, String label, String value) {
return withContext(
context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
}
/**
* Adds a configuration value in the service if that key and label does not exist.The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param setting The setting to add based on its key and optional label combination.
* @return The {@link ConfigurationSetting} that was created, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null,
getETagValue(ETAG_ANY), context)
.doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue()))
.onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper)
.doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, or optionally, null if a setting with
* label is desired.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setSetting(String key, String label, String value) {
try {
return withContext(
context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value),
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* If {@link ConfigurationSetting
* setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value
* (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's etag does not match, or the setting exists and is
* locked.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> setSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting,
ifMatchETag, null, context)
.doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label) {
try {
return getSetting(key, label, null);
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code asOfDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) {
try {
return withContext(
context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime,
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse
*
* @param setting The setting to retrieve.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime asOfDateTime,
boolean ifChanged) {
try {
return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime,
boolean onlyIfChanged, Context context) {
validateSetting(setting);
final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null;
return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete, or optionally, null if a setting with
* label is desired.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteSetting(String key, String label) {
try {
return withContext(
context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current etag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> deleteSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag,
null, context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error));
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to lock.
* @param label The label of configuration setting to lock, or optionally, null if a setting with label is desired.
* @return The {@link ConfigurationSetting} that was locked, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label) {
try {
return withContext(context -> setReadOnly(
new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The setting to lock based on its key and optional label combination.
* @return A REST response containing the locked ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> setReadOnly(setting, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error));
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly
*
* @param key The key of configuration setting to unlock.
* @param label The label of configuration setting to unlock, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} that was unlocked, or an empty Mono is also returned if a key collision
* occurs or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> clearReadOnly(String key, String label) {
try {
return withContext(context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse
*
* @param setting The setting to unlock based on its key and optional label combination.
* @return A REST response containing the unlocked ConfigurationSetting, or {@code null} if didn't exist. {@code
* null} is also returned if the {@link ConfigurationSetting
* throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> clearReadOnly(setting, context));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(),
null, null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting))
.doOnSuccess(
response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue()))
.doOnError(
error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error));
}
/**
* Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings}
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux
* contains all of the current settings in the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) {
try {
return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)),
continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex))));
}
}
PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector, Context context) {
return new PagedFlux<>(() -> listFirstPageSettings(selector, context),
continuationToken -> listNextPageSettings(context, continuationToken));
}
private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) {
try {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
return service.listKeyValues(serviceEndpoint, continuationToken, context)
.doOnSubscribe(
ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken))
.doOnError(
error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken,
error));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector selector, Context context) {
try {
if (selector == null) {
return service.listKeyValues(serviceEndpoint, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings"))
.doOnSuccess(response -> logger.info("Listed all ConfigurationSettings"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error));
}
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
return service.listKeyValues(serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), context)
.doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", selector))
.doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", selector, error));
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* after a period of time. The service maintains change history for up to 7 days.
*
* If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code options}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions}
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) {
try {
return new PagedFlux<>(() ->
withContext(context -> listSettingRevisionsFirstPage(selector, context)),
continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex))));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result;
if (selector != null) {
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null;
result =
service.listKeyValueRevisions(
serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context)
.doOnRequest(
ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector))
.doOnError(
error -> logger
.warning("Failed to list ConfigurationSetting revisions - {}", selector, error));
} else {
result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions"))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error));
}
return result;
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result = service
.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result;
} catch (RuntimeException ex) {
return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
}
}
PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) {
return new PagedFlux<>(() ->
listSettingRevisionsFirstPage(selector, context),
continuationToken -> listSettingRevisionsNextPage(continuationToken, context));
}
private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) {
Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context));
}
private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings(
PagedResponse<ConfigurationSetting> page, Context context) {
return ImplUtils.extractAndFetch(page, context, this::listSettings);
}
/*
* Azure Configuration service requires that the etag value is surrounded in quotation marks.
*
* @param etag The etag to get the value for. If null is pass in, an empty string is returned.
* @return The etag surrounded by quotations. (ex. "etag")
*/
private static String getETagValue(String etag) {
return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\"";
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
private static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since
* add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return
* this status when the configuration doesn't exist.
*
* @param throwable Error response from the service.
*
* @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException,
* otherwise the throwable is returned unmodified.
*/
private static Throwable addSettingExceptionMapper(Throwable throwable) {
if (!(throwable instanceof ResourceNotFoundException)) {
return throwable;
}
ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable;
return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse());
}
} | class ConfigurationAsyncClient {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class);
private static final String ETAG_ANY = "*";
private static final String RANGE_QUERY = "items=%s";
private final String serviceEndpoint;
private final ConfigurationService service;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceEndpoint The URL string for the App Configuration service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
ConfigurationAsyncClient(String serviceEndpoint, HttpPipeline pipeline) {
this.service = RestProxy.create(ConfigurationService.class, pipeline);
this.serviceEndpoint = serviceEndpoint;
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add, or optionally, null if a setting with
* label is desired.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(String key, String label, String value) {
try {
return withContext(
context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist.The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param setting The setting to add based on its key and optional label combination.
* @return The {@link ConfigurationSetting} that was created, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null,
getETagValue(ETAG_ANY), context)
.doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue()))
.onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper)
.doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, or optionally, null if a setting with
* label is desired.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setSetting(String key, String label, String value) {
try {
return withContext(
context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value),
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* If {@link ConfigurationSetting
* setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value
* (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's etag does not match, or the setting exists and is
* locked.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> setSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting,
ifMatchETag, null, context)
.doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label) {
try {
return getSetting(key, label, null);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code asOfDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) {
try {
return withContext(
context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime,
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse
*
* @param setting The setting to retrieve.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime asOfDateTime,
boolean ifChanged) {
try {
return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime,
boolean onlyIfChanged, Context context) {
validateSetting(setting);
final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null;
return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete, or optionally, null if a setting with
* label is desired.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteSetting(String key, String label) {
try {
return withContext(
context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current etag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> deleteSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag,
null, context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error));
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to lock.
* @param label The label of configuration setting to lock, or optionally, null if a setting with label is desired.
* @return The {@link ConfigurationSetting} that was locked, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label) {
try {
return withContext(context -> setReadOnly(
new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The setting to lock based on its key and optional label combination.
* @return A REST response containing the locked ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> setReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error));
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly
*
* @param key The key of configuration setting to unlock.
* @param label The label of configuration setting to unlock, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} that was unlocked, or an empty Mono is also returned if a key collision
* occurs or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> clearReadOnly(String key, String label) {
try {
return withContext(
context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse
*
* @param setting The setting to unlock based on its key and optional label combination.
* @return A REST response containing the unlocked ConfigurationSetting, or {@code null} if didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> clearReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(),
null, null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting))
.doOnSuccess(
response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue()))
.doOnError(
error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error));
}
/**
* Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings}
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux
* contains all of the current settings in the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) {
try {
return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)),
continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector, Context context) {
return new PagedFlux<>(() -> listFirstPageSettings(selector, context),
continuationToken -> listNextPageSettings(context, continuationToken));
}
private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) {
try {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
return service.listKeyValues(serviceEndpoint, continuationToken, context)
.doOnSubscribe(
ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken))
.doOnError(
error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector selector, Context context) {
try {
if (selector == null) {
return service.listKeyValues(serviceEndpoint, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings"))
.doOnSuccess(response -> logger.info("Listed all ConfigurationSettings"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error));
}
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
return service.listKeyValues(serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), context)
.doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", selector))
.doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", selector, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* after a period of time. The service maintains change history for up to 7 days.
*
* If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code options}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions}
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) {
try {
return new PagedFlux<>(() ->
withContext(context -> listSettingRevisionsFirstPage(selector, context)),
continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result;
if (selector != null) {
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null;
result =
service.listKeyValueRevisions(
serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context)
.doOnRequest(
ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector))
.doOnError(
error -> logger
.warning("Failed to list ConfigurationSetting revisions - {}", selector, error));
} else {
result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions"))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error));
}
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result = service
.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) {
return new PagedFlux<>(() ->
listSettingRevisionsFirstPage(selector, context),
continuationToken -> listSettingRevisionsNextPage(continuationToken, context));
}
private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) {
Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context));
}
private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings(
PagedResponse<ConfigurationSetting> page, Context context) {
return ImplUtils.extractAndFetch(page, context, this::listSettings);
}
/*
* Azure Configuration service requires that the etag value is surrounded in quotation marks.
*
* @param etag The etag to get the value for. If null is pass in, an empty string is returned.
* @return The etag surrounded by quotations. (ex. "etag")
*/
private static String getETagValue(String etag) {
return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\"";
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
private static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since
* add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return
* this status when the configuration doesn't exist.
*
* @param throwable Error response from the service.
*
* @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException,
* otherwise the throwable is returned unmodified.
*/
private static Throwable addSettingExceptionMapper(Throwable throwable) {
if (!(throwable instanceof ResourceNotFoundException)) {
return throwable;
}
ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable;
return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse());
}
} |
What about a `monoError` here too? | public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) {
try {
return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)),
continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex))));
}
} | return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)))); | public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) {
try {
return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)),
continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
} | class ConfigurationAsyncClient {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class);
private static final String ETAG_ANY = "*";
private static final String RANGE_QUERY = "items=%s";
private final String serviceEndpoint;
private final ConfigurationService service;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceEndpoint The URL string for the App Configuration service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
ConfigurationAsyncClient(String serviceEndpoint, HttpPipeline pipeline) {
this.service = RestProxy.create(ConfigurationService.class, pipeline);
this.serviceEndpoint = serviceEndpoint;
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add, or optionally, null if a setting with
* label is desired.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(String key, String label, String value) {
try {
return withContext(
context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist.The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param setting The setting to add based on its key and optional label combination.
* @return The {@link ConfigurationSetting} that was created, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null,
getETagValue(ETAG_ANY), context)
.doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue()))
.onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper)
.doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, or optionally, null if a setting with
* label is desired.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setSetting(String key, String label, String value) {
try {
return withContext(
context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value),
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* If {@link ConfigurationSetting
* setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value
* (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's etag does not match, or the setting exists and is
* locked.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> setSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting,
ifMatchETag, null, context)
.doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label) {
try {
return getSetting(key, label, null);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code asOfDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) {
try {
return withContext(
context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime,
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse
*
* @param setting The setting to retrieve.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime asOfDateTime,
boolean ifChanged) {
try {
return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime,
boolean onlyIfChanged, Context context) {
validateSetting(setting);
final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null;
return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete, or optionally, null if a setting with
* label is desired.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteSetting(String key, String label) {
try {
return withContext(
context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current etag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> deleteSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag,
null, context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error));
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to lock.
* @param label The label of configuration setting to lock, or optionally, null if a setting with label is desired.
* @return The {@link ConfigurationSetting} that was locked, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label) {
try {
return withContext(context -> setReadOnly(
new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The setting to lock based on its key and optional label combination.
* @return A REST response containing the locked ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> setReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error));
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly
*
* @param key The key of configuration setting to unlock.
* @param label The label of configuration setting to unlock, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} that was unlocked, or an empty Mono is also returned if a key collision
* occurs or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> clearReadOnly(String key, String label) {
try {
return withContext(
context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse
*
* @param setting The setting to unlock based on its key and optional label combination.
* @return A REST response containing the unlocked ConfigurationSetting, or {@code null} if didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> clearReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(),
null, null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting))
.doOnSuccess(
response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue()))
.doOnError(
error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error));
}
/**
* Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings}
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux
* contains all of the current settings in the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector, Context context) {
return new PagedFlux<>(() -> listFirstPageSettings(selector, context),
continuationToken -> listNextPageSettings(context, continuationToken));
}
private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) {
try {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
return service.listKeyValues(serviceEndpoint, continuationToken, context)
.doOnSubscribe(
ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken))
.doOnError(
error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector selector, Context context) {
try {
if (selector == null) {
return service.listKeyValues(serviceEndpoint, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings"))
.doOnSuccess(response -> logger.info("Listed all ConfigurationSettings"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error));
}
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
return service.listKeyValues(serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), context)
.doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", selector))
.doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", selector, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* after a period of time. The service maintains change history for up to 7 days.
*
* If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code options}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions}
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) {
try {
return new PagedFlux<>(() ->
withContext(context -> listSettingRevisionsFirstPage(selector, context)),
continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex))));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result;
if (selector != null) {
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null;
result =
service.listKeyValueRevisions(
serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context)
.doOnRequest(
ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector))
.doOnError(
error -> logger
.warning("Failed to list ConfigurationSetting revisions - {}", selector, error));
} else {
result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions"))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error));
}
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result = service
.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) {
return new PagedFlux<>(() ->
listSettingRevisionsFirstPage(selector, context),
continuationToken -> listSettingRevisionsNextPage(continuationToken, context));
}
private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) {
Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context));
}
private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings(
PagedResponse<ConfigurationSetting> page, Context context) {
return ImplUtils.extractAndFetch(page, context, this::listSettings);
}
/*
* Azure Configuration service requires that the etag value is surrounded in quotation marks.
*
* @param etag The etag to get the value for. If null is pass in, an empty string is returned.
* @return The etag surrounded by quotations. (ex. "etag")
*/
private static String getETagValue(String etag) {
return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\"";
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
private static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since
* add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return
* this status when the configuration doesn't exist.
*
* @param throwable Error response from the service.
*
* @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException,
* otherwise the throwable is returned unmodified.
*/
private static Throwable addSettingExceptionMapper(Throwable throwable) {
if (!(throwable instanceof ResourceNotFoundException)) {
return throwable;
}
ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable;
return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse());
}
} | class ConfigurationAsyncClient {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class);
private static final String ETAG_ANY = "*";
private static final String RANGE_QUERY = "items=%s";
private final String serviceEndpoint;
private final ConfigurationService service;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceEndpoint The URL string for the App Configuration service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
ConfigurationAsyncClient(String serviceEndpoint, HttpPipeline pipeline) {
this.service = RestProxy.create(ConfigurationService.class, pipeline);
this.serviceEndpoint = serviceEndpoint;
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add, or optionally, null if a setting with
* label is desired.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(String key, String label, String value) {
try {
return withContext(
context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist.The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param setting The setting to add based on its key and optional label combination.
* @return The {@link ConfigurationSetting} that was created, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null,
getETagValue(ETAG_ANY), context)
.doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue()))
.onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper)
.doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, or optionally, null if a setting with
* label is desired.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setSetting(String key, String label, String value) {
try {
return withContext(
context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value),
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* If {@link ConfigurationSetting
* setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value
* (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's etag does not match, or the setting exists and is
* locked.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> setSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting,
ifMatchETag, null, context)
.doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label) {
try {
return getSetting(key, label, null);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code asOfDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) {
try {
return withContext(
context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime,
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse
*
* @param setting The setting to retrieve.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime asOfDateTime,
boolean ifChanged) {
try {
return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime,
boolean onlyIfChanged, Context context) {
validateSetting(setting);
final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null;
return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete, or optionally, null if a setting with
* label is desired.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteSetting(String key, String label) {
try {
return withContext(
context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current etag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> deleteSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag,
null, context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error));
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to lock.
* @param label The label of configuration setting to lock, or optionally, null if a setting with label is desired.
* @return The {@link ConfigurationSetting} that was locked, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label) {
try {
return withContext(context -> setReadOnly(
new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The setting to lock based on its key and optional label combination.
* @return A REST response containing the locked ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> setReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error));
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly
*
* @param key The key of configuration setting to unlock.
* @param label The label of configuration setting to unlock, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} that was unlocked, or an empty Mono is also returned if a key collision
* occurs or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> clearReadOnly(String key, String label) {
try {
return withContext(
context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse
*
* @param setting The setting to unlock based on its key and optional label combination.
* @return A REST response containing the unlocked ConfigurationSetting, or {@code null} if didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> clearReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(),
null, null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting))
.doOnSuccess(
response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue()))
.doOnError(
error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error));
}
/**
* Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings}
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux
* contains all of the current settings in the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector, Context context) {
return new PagedFlux<>(() -> listFirstPageSettings(selector, context),
continuationToken -> listNextPageSettings(context, continuationToken));
}
private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) {
try {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
return service.listKeyValues(serviceEndpoint, continuationToken, context)
.doOnSubscribe(
ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken))
.doOnError(
error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector selector, Context context) {
try {
if (selector == null) {
return service.listKeyValues(serviceEndpoint, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings"))
.doOnSuccess(response -> logger.info("Listed all ConfigurationSettings"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error));
}
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
return service.listKeyValues(serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), context)
.doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", selector))
.doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", selector, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* after a period of time. The service maintains change history for up to 7 days.
*
* If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code options}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions}
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) {
try {
return new PagedFlux<>(() ->
withContext(context -> listSettingRevisionsFirstPage(selector, context)),
continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result;
if (selector != null) {
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null;
result =
service.listKeyValueRevisions(
serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context)
.doOnRequest(
ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector))
.doOnError(
error -> logger
.warning("Failed to list ConfigurationSetting revisions - {}", selector, error));
} else {
result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions"))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error));
}
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result = service
.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) {
return new PagedFlux<>(() ->
listSettingRevisionsFirstPage(selector, context),
continuationToken -> listSettingRevisionsNextPage(continuationToken, context));
}
private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) {
Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context));
}
private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings(
PagedResponse<ConfigurationSetting> page, Context context) {
return ImplUtils.extractAndFetch(page, context, this::listSettings);
}
/*
* Azure Configuration service requires that the etag value is surrounded in quotation marks.
*
* @param etag The etag to get the value for. If null is pass in, an empty string is returned.
* @return The etag surrounded by quotations. (ex. "etag")
*/
private static String getETagValue(String etag) {
return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\"";
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
private static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since
* add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return
* this status when the configuration doesn't exist.
*
* @param throwable Error response from the service.
*
* @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException,
* otherwise the throwable is returned unmodified.
*/
private static Throwable addSettingExceptionMapper(Throwable throwable) {
if (!(throwable instanceof ResourceNotFoundException)) {
return throwable;
}
ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable;
return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse());
}
} |
Updated these to `monoError` as well. | public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) {
try {
return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)),
continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex))));
}
} | return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)))); | public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) {
try {
return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)),
continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
} | class ConfigurationAsyncClient {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class);
private static final String ETAG_ANY = "*";
private static final String RANGE_QUERY = "items=%s";
private final String serviceEndpoint;
private final ConfigurationService service;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceEndpoint The URL string for the App Configuration service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
ConfigurationAsyncClient(String serviceEndpoint, HttpPipeline pipeline) {
this.service = RestProxy.create(ConfigurationService.class, pipeline);
this.serviceEndpoint = serviceEndpoint;
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add, or optionally, null if a setting with
* label is desired.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(String key, String label, String value) {
try {
return withContext(
context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist.The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param setting The setting to add based on its key and optional label combination.
* @return The {@link ConfigurationSetting} that was created, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null,
getETagValue(ETAG_ANY), context)
.doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue()))
.onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper)
.doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, or optionally, null if a setting with
* label is desired.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setSetting(String key, String label, String value) {
try {
return withContext(
context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value),
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* If {@link ConfigurationSetting
* setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value
* (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's etag does not match, or the setting exists and is
* locked.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> setSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting,
ifMatchETag, null, context)
.doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label) {
try {
return getSetting(key, label, null);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code asOfDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) {
try {
return withContext(
context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime,
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse
*
* @param setting The setting to retrieve.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime asOfDateTime,
boolean ifChanged) {
try {
return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime,
boolean onlyIfChanged, Context context) {
validateSetting(setting);
final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null;
return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete, or optionally, null if a setting with
* label is desired.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteSetting(String key, String label) {
try {
return withContext(
context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current etag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> deleteSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag,
null, context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error));
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to lock.
* @param label The label of configuration setting to lock, or optionally, null if a setting with label is desired.
* @return The {@link ConfigurationSetting} that was locked, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label) {
try {
return withContext(context -> setReadOnly(
new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The setting to lock based on its key and optional label combination.
* @return A REST response containing the locked ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> setReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error));
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly
*
* @param key The key of configuration setting to unlock.
* @param label The label of configuration setting to unlock, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} that was unlocked, or an empty Mono is also returned if a key collision
* occurs or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> clearReadOnly(String key, String label) {
try {
return withContext(
context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse
*
* @param setting The setting to unlock based on its key and optional label combination.
* @return A REST response containing the unlocked ConfigurationSetting, or {@code null} if didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> clearReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(),
null, null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting))
.doOnSuccess(
response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue()))
.doOnError(
error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error));
}
/**
* Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings}
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux
* contains all of the current settings in the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector, Context context) {
return new PagedFlux<>(() -> listFirstPageSettings(selector, context),
continuationToken -> listNextPageSettings(context, continuationToken));
}
private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) {
try {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
return service.listKeyValues(serviceEndpoint, continuationToken, context)
.doOnSubscribe(
ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken))
.doOnError(
error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector selector, Context context) {
try {
if (selector == null) {
return service.listKeyValues(serviceEndpoint, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings"))
.doOnSuccess(response -> logger.info("Listed all ConfigurationSettings"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error));
}
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
return service.listKeyValues(serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), context)
.doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", selector))
.doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", selector, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* after a period of time. The service maintains change history for up to 7 days.
*
* If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code options}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions}
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) {
try {
return new PagedFlux<>(() ->
withContext(context -> listSettingRevisionsFirstPage(selector, context)),
continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex))));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result;
if (selector != null) {
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null;
result =
service.listKeyValueRevisions(
serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context)
.doOnRequest(
ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector))
.doOnError(
error -> logger
.warning("Failed to list ConfigurationSetting revisions - {}", selector, error));
} else {
result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions"))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error));
}
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result = service
.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) {
return new PagedFlux<>(() ->
listSettingRevisionsFirstPage(selector, context),
continuationToken -> listSettingRevisionsNextPage(continuationToken, context));
}
private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) {
Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context));
}
private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings(
PagedResponse<ConfigurationSetting> page, Context context) {
return ImplUtils.extractAndFetch(page, context, this::listSettings);
}
/*
* Azure Configuration service requires that the etag value is surrounded in quotation marks.
*
* @param etag The etag to get the value for. If null is pass in, an empty string is returned.
* @return The etag surrounded by quotations. (ex. "etag")
*/
private static String getETagValue(String etag) {
return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\"";
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
private static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since
* add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return
* this status when the configuration doesn't exist.
*
* @param throwable Error response from the service.
*
* @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException,
* otherwise the throwable is returned unmodified.
*/
private static Throwable addSettingExceptionMapper(Throwable throwable) {
if (!(throwable instanceof ResourceNotFoundException)) {
return throwable;
}
ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable;
return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse());
}
} | class ConfigurationAsyncClient {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class);
private static final String ETAG_ANY = "*";
private static final String RANGE_QUERY = "items=%s";
private final String serviceEndpoint;
private final ConfigurationService service;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceEndpoint The URL string for the App Configuration service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
ConfigurationAsyncClient(String serviceEndpoint, HttpPipeline pipeline) {
this.service = RestProxy.create(ConfigurationService.class, pipeline);
this.serviceEndpoint = serviceEndpoint;
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add, or optionally, null if a setting with
* label is desired.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(String key, String label, String value) {
try {
return withContext(
context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist.The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting
*
* @param setting The setting to add based on its key and optional label combination.
* @return The {@link ConfigurationSetting} that was created, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> addSetting(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null,
getETagValue(ETAG_ANY), context)
.doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue()))
.onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper)
.doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, or optionally, null if a setting with
* label is desired.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setSetting(String key, String label, String value) {
try {
return withContext(
context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value),
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* If {@link ConfigurationSetting
* setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value
* (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's etag does not match, or the setting exists and is
* locked.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> setSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting,
ifMatchETag, null, context)
.doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label) {
try {
return getSetting(key, label, null);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code asOfDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve, or optionally, null if a setting with
* label is desired.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) {
try {
return withContext(
context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime,
false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse
*
* @param setting The setting to retrieve.
* @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with
* {@code asOfDateTime} is desired.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime asOfDateTime,
boolean ifChanged) {
try {
return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime,
boolean onlyIfChanged, Context context) {
validateSetting(setting);
final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null;
return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete, or optionally, null if a setting with
* label is desired.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteSetting(String key, String label) {
try {
return withContext(
context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is locked.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current etag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
return withContext(context -> deleteSetting(setting, ifUnchanged, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged,
Context context) {
validateSetting(setting);
final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null;
return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag,
null, context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error));
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to lock.
* @param label The label of configuration setting to lock, or optionally, null if a setting with label is desired.
* @return The {@link ConfigurationSetting} that was locked, or an empty Mono if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label) {
try {
return withContext(context -> setReadOnly(
new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The setting to lock based on its key and optional label combination.
* @return A REST response containing the locked ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> setReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null,
null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting))
.doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue()))
.doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error));
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@code key}, and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly
*
* @param key The key of configuration setting to unlock.
* @param label The label of configuration setting to unlock, or optionally, null if a setting with
* label is desired.
* @return The {@link ConfigurationSetting} that was unlocked, or an empty Mono is also returned if a key collision
* occurs or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> clearReadOnly(String key, String label) {
try {
return withContext(
context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context))
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Unlock the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* <p><strong>Code Samples</strong></p>
*
* <p>Unlock the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse
*
* @param setting The setting to unlock based on its key and optional label combination.
* @return A REST response containing the unlocked ConfigurationSetting, or {@code null} if didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) {
try {
return withContext(context -> clearReadOnly(setting, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) {
validateSetting(setting);
return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(),
null, null, context)
.doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting))
.doOnSuccess(
response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue()))
.doOnError(
error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error));
}
/**
* Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings}
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux
* contains all of the current settings in the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector, Context context) {
return new PagedFlux<>(() -> listFirstPageSettings(selector, context),
continuationToken -> listNextPageSettings(context, continuationToken));
}
private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) {
try {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
return service.listKeyValues(serviceEndpoint, continuationToken, context)
.doOnSubscribe(
ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken))
.doOnError(
error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector selector, Context context) {
try {
if (selector == null) {
return service.listKeyValues(serviceEndpoint, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings"))
.doOnSuccess(response -> logger.info("Listed all ConfigurationSettings"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error));
}
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
return service.listKeyValues(serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), context)
.doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", selector))
.doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", selector, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* after a period of time. The service maintains change history for up to 7 days.
*
* If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code options}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions}
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) {
try {
return new PagedFlux<>(() ->
withContext(context -> listSettingRevisionsFirstPage(selector, context)),
continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result;
if (selector != null) {
String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper);
String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key);
String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label);
String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null;
result =
service.listKeyValueRevisions(
serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context)
.doOnRequest(
ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector))
.doOnError(
error -> logger
.warning("Failed to list ConfigurationSetting revisions - {}", selector, error));
} else {
result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context)
.doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions"))
.doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions"))
.doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error));
}
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) {
try {
Mono<PagedResponse<ConfigurationSetting>> result = service
.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result;
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) {
return new PagedFlux<>(() ->
listSettingRevisionsFirstPage(selector, context),
continuationToken -> listSettingRevisionsNextPage(continuationToken, context));
}
private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) {
Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error));
return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context));
}
private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings(
PagedResponse<ConfigurationSetting> page, Context context) {
return ImplUtils.extractAndFetch(page, context, this::listSettings);
}
/*
* Azure Configuration service requires that the etag value is surrounded in quotation marks.
*
* @param etag The etag to get the value for. If null is pass in, an empty string is returned.
* @return The etag surrounded by quotations. (ex. "etag")
*/
private static String getETagValue(String etag) {
return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\"";
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
private static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since
* add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return
* this status when the configuration doesn't exist.
*
* @param throwable Error response from the service.
*
* @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException,
* otherwise the throwable is returned unmodified.
*/
private static Throwable addSettingExceptionMapper(Throwable throwable) {
if (!(throwable instanceof ResourceNotFoundException)) {
return throwable;
}
ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable;
return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse());
}
} |
jfyi we could also do: ``` headerMapper = simpleMapper .copy() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); ``` https://static.javadoc.io/com.fasterxml.jackson.core/jackson-databind/2.9.8/com/fasterxml/jackson/databind/ObjectMapper.html#copy-- | public JacksonAdapter() {
simpleMapper = initializeObjectMapper(new ObjectMapper());
xmlMapper = initializeObjectMapper(new XmlMapper());
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
xmlMapper.setDefaultUseWrapper(false);
ObjectMapper flatteningMapper = initializeObjectMapper(new ObjectMapper())
.registerModule(FlatteningSerializer.getModule(simpleMapper()))
.registerModule(FlatteningDeserializer.getModule(simpleMapper()));
mapper = initializeObjectMapper(new ObjectMapper())
.registerModule(AdditionalPropertiesSerializer.getModule(flatteningMapper))
.registerModule(AdditionalPropertiesDeserializer.getModule(flatteningMapper))
.registerModule(FlatteningSerializer.getModule(simpleMapper()))
.registerModule(FlatteningDeserializer.getModule(simpleMapper()));
headerMapper = initializeHeaderMapper(new ObjectMapper());
} | headerMapper = initializeHeaderMapper(new ObjectMapper()); | public JacksonAdapter() {
simpleMapper = initializeObjectMapper(new ObjectMapper());
xmlMapper = initializeObjectMapper(new XmlMapper());
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
xmlMapper.setDefaultUseWrapper(false);
ObjectMapper flatteningMapper = initializeObjectMapper(new ObjectMapper())
.registerModule(FlatteningSerializer.getModule(simpleMapper()))
.registerModule(FlatteningDeserializer.getModule(simpleMapper()));
mapper = initializeObjectMapper(new ObjectMapper())
.registerModule(AdditionalPropertiesSerializer.getModule(flatteningMapper))
.registerModule(AdditionalPropertiesDeserializer.getModule(flatteningMapper))
.registerModule(FlatteningSerializer.getModule(simpleMapper()))
.registerModule(FlatteningDeserializer.getModule(simpleMapper()));
headerMapper = simpleMapper
.copy()
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
} | class JacksonAdapter implements SerializerAdapter {
private final ClientLogger logger = new ClientLogger(JacksonAdapter.class);
/**
* An instance of {@link ObjectMapper} to serialize/deserialize objects.
*/
private final ObjectMapper mapper;
/**
* An instance of {@link ObjectMapper} that does not do flattening.
*/
private final ObjectMapper simpleMapper;
private final XmlMapper xmlMapper;
private final ObjectMapper headerMapper;
/*
* The lazily-created serializer for this ServiceClient.
*/
private static SerializerAdapter serializerAdapter;
/*
* BOM header from some response bodies. To be removed in deserialization.
*/
private static final String BOM = "\uFEFF";
/**
* Creates a new JacksonAdapter instance with default mapper settings.
*/
/**
* Gets a static instance of {@link ObjectMapper} that doesn't handle flattening.
*
* @return an instance of {@link ObjectMapper}.
*/
protected ObjectMapper simpleMapper() {
return simpleMapper;
}
/**
* maintain singleton instance of the default serializer adapter.
*
* @return the default serializer
*/
public static synchronized SerializerAdapter createDefaultSerializerAdapter() {
if (serializerAdapter == null) {
serializerAdapter = new JacksonAdapter();
}
return serializerAdapter;
}
/**
* @return the original serializer type
*/
public ObjectMapper serializer() {
return mapper;
}
@Override
public String serialize(Object object, SerializerEncoding encoding) throws IOException {
if (object == null) {
return null;
}
StringWriter writer = new StringWriter();
if (encoding == SerializerEncoding.XML) {
xmlMapper.writeValue(writer, object);
} else {
serializer().writeValue(writer, object);
}
return writer.toString();
}
@Override
public String serializeRaw(Object object) {
if (object == null) {
return null;
}
try {
return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", "");
} catch (IOException ex) {
return null;
}
}
@Override
public String serializeList(List<?> list, CollectionFormat format) {
if (list == null) {
return null;
}
List<String> serialized = new ArrayList<>();
for (Object element : list) {
String raw = serializeRaw(element);
serialized.add(raw != null ? raw : "");
}
return String.join(format.getDelimiter(), serialized);
}
@Override
@SuppressWarnings("unchecked")
public <T> T deserialize(String value, final Type type, SerializerEncoding encoding) throws IOException {
if (value == null || value.isEmpty() || value.equals(BOM)) {
return null;
}
if (value.startsWith(BOM)) {
value = value.replaceFirst(BOM, "");
}
final JavaType javaType = createJavaType(type);
try {
if (encoding == SerializerEncoding.XML) {
return (T) xmlMapper.readValue(value, javaType);
} else {
return (T) serializer().readValue(value, javaType);
}
} catch (JsonParseException jpe) {
throw logger.logExceptionAsError(new MalformedValueException(jpe.getMessage(), jpe));
}
}
@Override
public <T> T deserialize(HttpHeaders headers, Type deserializedHeadersType) throws IOException {
if (deserializedHeadersType == null) {
return null;
}
final String headersJsonString = headerMapper.writeValueAsString(headers);
T deserializedHeaders =
headerMapper.readValue(headersJsonString, createJavaType(deserializedHeadersType));
final Class<?> deserializedHeadersClass = TypeUtil.getRawClass(deserializedHeadersType);
final Field[] declaredFields = deserializedHeadersClass.getDeclaredFields();
for (final Field declaredField : declaredFields) {
if (declaredField.isAnnotationPresent(HeaderCollection.class)) {
final Type declaredFieldType = declaredField.getGenericType();
if (TypeUtil.isTypeOrSubTypeOf(declaredField.getType(), Map.class)) {
final Type[] mapTypeArguments = TypeUtil.getTypeArguments(declaredFieldType);
if (mapTypeArguments.length == 2
&& mapTypeArguments[0] == String.class
&& mapTypeArguments[1] == String.class) {
final HeaderCollection headerCollectionAnnotation =
declaredField.getAnnotation(HeaderCollection.class);
final String headerCollectionPrefix =
headerCollectionAnnotation.value().toLowerCase(Locale.ROOT);
final int headerCollectionPrefixLength = headerCollectionPrefix.length();
if (headerCollectionPrefixLength > 0) {
final Map<String, String> headerCollection = new HashMap<>();
for (final HttpHeader header : headers) {
final String headerName = header.getName();
if (headerName.toLowerCase(Locale.ROOT).startsWith(headerCollectionPrefix)) {
headerCollection.put(headerName.substring(headerCollectionPrefixLength),
header.getValue());
}
}
final boolean declaredFieldAccessibleBackup = declaredField.isAccessible();
try {
if (!declaredFieldAccessibleBackup) {
declaredField.setAccessible(true);
}
declaredField.set(deserializedHeaders, headerCollection);
} catch (IllegalAccessException ignored) {
} finally {
if (!declaredFieldAccessibleBackup) {
declaredField.setAccessible(declaredFieldAccessibleBackup);
}
}
}
}
}
}
}
return deserializedHeaders;
}
/**
* Initializes an instance of JacksonMapperAdapter with default configurations
* applied to the object mapper.
*
* @param mapper the object mapper to use.
*/
private static <T extends ObjectMapper> T initializeObjectMapper(T mapper) {
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.registerModule(new JavaTimeModule())
.registerModule(ByteArraySerializer.getModule())
.registerModule(Base64UrlSerializer.getModule())
.registerModule(DateTimeSerializer.getModule())
.registerModule(DateTimeRfc1123Serializer.getModule())
.registerModule(DurationSerializer.getModule())
.registerModule(HttpHeadersSerializer.getModule());
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
return mapper;
}
private static <T extends ObjectMapper> T initializeHeaderMapper(T mapper) {
initializeObjectMapper(mapper);
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
return mapper;
}
private JavaType createJavaType(Type type) {
JavaType result;
if (type == null) {
result = null;
} else if (type instanceof JavaType) {
result = (JavaType) type;
} else if (type instanceof ParameterizedType) {
final ParameterizedType parameterizedType = (ParameterizedType) type;
final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
JavaType[] javaTypeArguments = new JavaType[actualTypeArguments.length];
for (int i = 0; i != actualTypeArguments.length; i++) {
javaTypeArguments[i] = createJavaType(actualTypeArguments[i]);
}
result = mapper
.getTypeFactory().constructParametricType((Class<?>) parameterizedType.getRawType(), javaTypeArguments);
} else {
result = mapper
.getTypeFactory().constructType(type);
}
return result;
}
} | class JacksonAdapter implements SerializerAdapter {
private final ClientLogger logger = new ClientLogger(JacksonAdapter.class);
/**
* An instance of {@link ObjectMapper} to serialize/deserialize objects.
*/
private final ObjectMapper mapper;
/**
* An instance of {@link ObjectMapper} that does not do flattening.
*/
private final ObjectMapper simpleMapper;
private final XmlMapper xmlMapper;
private final ObjectMapper headerMapper;
/*
* The lazily-created serializer for this ServiceClient.
*/
private static SerializerAdapter serializerAdapter;
/*
* BOM header from some response bodies. To be removed in deserialization.
*/
private static final String BOM = "\uFEFF";
/**
* Creates a new JacksonAdapter instance with default mapper settings.
*/
/**
* Gets a static instance of {@link ObjectMapper} that doesn't handle flattening.
*
* @return an instance of {@link ObjectMapper}.
*/
protected ObjectMapper simpleMapper() {
return simpleMapper;
}
/**
* maintain singleton instance of the default serializer adapter.
*
* @return the default serializer
*/
public static synchronized SerializerAdapter createDefaultSerializerAdapter() {
if (serializerAdapter == null) {
serializerAdapter = new JacksonAdapter();
}
return serializerAdapter;
}
/**
* @return the original serializer type
*/
public ObjectMapper serializer() {
return mapper;
}
@Override
public String serialize(Object object, SerializerEncoding encoding) throws IOException {
if (object == null) {
return null;
}
StringWriter writer = new StringWriter();
if (encoding == SerializerEncoding.XML) {
xmlMapper.writeValue(writer, object);
} else {
serializer().writeValue(writer, object);
}
return writer.toString();
}
@Override
public String serializeRaw(Object object) {
if (object == null) {
return null;
}
try {
return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", "");
} catch (IOException ex) {
return null;
}
}
@Override
public String serializeList(List<?> list, CollectionFormat format) {
if (list == null) {
return null;
}
List<String> serialized = new ArrayList<>();
for (Object element : list) {
String raw = serializeRaw(element);
serialized.add(raw != null ? raw : "");
}
return String.join(format.getDelimiter(), serialized);
}
@Override
@SuppressWarnings("unchecked")
public <T> T deserialize(String value, final Type type, SerializerEncoding encoding) throws IOException {
if (value == null || value.isEmpty() || value.equals(BOM)) {
return null;
}
if (value.startsWith(BOM)) {
value = value.replaceFirst(BOM, "");
}
final JavaType javaType = createJavaType(type);
try {
if (encoding == SerializerEncoding.XML) {
return (T) xmlMapper.readValue(value, javaType);
} else {
return (T) serializer().readValue(value, javaType);
}
} catch (JsonParseException jpe) {
throw logger.logExceptionAsError(new MalformedValueException(jpe.getMessage(), jpe));
}
}
@Override
public <T> T deserialize(HttpHeaders headers, Type deserializedHeadersType) throws IOException {
if (deserializedHeadersType == null) {
return null;
}
final String headersJsonString = headerMapper.writeValueAsString(headers);
T deserializedHeaders =
headerMapper.readValue(headersJsonString, createJavaType(deserializedHeadersType));
final Class<?> deserializedHeadersClass = TypeUtil.getRawClass(deserializedHeadersType);
final Field[] declaredFields = deserializedHeadersClass.getDeclaredFields();
for (final Field declaredField : declaredFields) {
if (declaredField.isAnnotationPresent(HeaderCollection.class)) {
final Type declaredFieldType = declaredField.getGenericType();
if (TypeUtil.isTypeOrSubTypeOf(declaredField.getType(), Map.class)) {
final Type[] mapTypeArguments = TypeUtil.getTypeArguments(declaredFieldType);
if (mapTypeArguments.length == 2
&& mapTypeArguments[0] == String.class
&& mapTypeArguments[1] == String.class) {
final HeaderCollection headerCollectionAnnotation =
declaredField.getAnnotation(HeaderCollection.class);
final String headerCollectionPrefix =
headerCollectionAnnotation.value().toLowerCase(Locale.ROOT);
final int headerCollectionPrefixLength = headerCollectionPrefix.length();
if (headerCollectionPrefixLength > 0) {
final Map<String, String> headerCollection = new HashMap<>();
for (final HttpHeader header : headers) {
final String headerName = header.getName();
if (headerName.toLowerCase(Locale.ROOT).startsWith(headerCollectionPrefix)) {
headerCollection.put(headerName.substring(headerCollectionPrefixLength),
header.getValue());
}
}
final boolean declaredFieldAccessibleBackup = declaredField.isAccessible();
try {
if (!declaredFieldAccessibleBackup) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
declaredField.setAccessible(true);
return null;
});
}
declaredField.set(deserializedHeaders, headerCollection);
} catch (IllegalAccessException ignored) {
} finally {
if (!declaredFieldAccessibleBackup) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
declaredField.setAccessible(declaredFieldAccessibleBackup);
return null;
});
}
}
}
}
}
}
}
return deserializedHeaders;
}
/**
* Initializes an instance of JacksonMapperAdapter with default configurations
* applied to the object mapper.
*
* @param mapper the object mapper to use.
*/
private static <T extends ObjectMapper> T initializeObjectMapper(T mapper) {
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.registerModule(new JavaTimeModule())
.registerModule(ByteArraySerializer.getModule())
.registerModule(Base64UrlSerializer.getModule())
.registerModule(DateTimeSerializer.getModule())
.registerModule(DateTimeRfc1123Serializer.getModule())
.registerModule(DurationSerializer.getModule())
.registerModule(HttpHeadersSerializer.getModule());
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
return mapper;
}
private JavaType createJavaType(Type type) {
JavaType result;
if (type == null) {
result = null;
} else if (type instanceof JavaType) {
result = (JavaType) type;
} else if (type instanceof ParameterizedType) {
final ParameterizedType parameterizedType = (ParameterizedType) type;
final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
JavaType[] javaTypeArguments = new JavaType[actualTypeArguments.length];
for (int i = 0; i != actualTypeArguments.length; i++) {
javaTypeArguments[i] = createJavaType(actualTypeArguments[i]);
}
result = mapper
.getTypeFactory().constructParametricType((Class<?>) parameterizedType.getRawType(), javaTypeArguments);
} else {
result = mapper
.getTypeFactory().constructType(type);
}
return result;
}
} |
Just to confirm all exceptions including null pointer will flow through Mono.error ? | public Mono<Response<Key>> getKeyWithResponse(KeyProperties keyProperties) {
try {
Objects.requireNonNull(keyProperties, "The Key Properties parameter cannot be null.");
return withContext(context -> getKeyWithResponse(keyProperties.getName(), keyProperties.getVersion() == null ? ""
: keyProperties.getVersion(), context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | Objects.requireNonNull(keyProperties, "The Key Properties parameter cannot be null."); | return withContext(context -> getKeyWithResponse(keyProperties.getName(), keyProperties.getVersion() == null ? ""
: keyProperties.getVersion(), context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
} | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param endpoint URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
KeyAsyncClient(URL endpoint, HttpPipeline pipeline) {
Objects.requireNonNull(endpoint,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.endpoint = endpoint.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param keyCreateOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createKeyWithResponse(KeyCreateOptions keyCreateOptions) {
try {
return withContext(context -> createKeyWithResponse(keyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType);
return service.createKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Creating key - {}", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyCreateOptions} is required. The {@link KeyCreateOptions
* KeyCreateOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link KeyCreateOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param keyCreateOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createKey(KeyCreateOptions keyCreateOptions) {
try {
return createKeyWithResponse(keyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createKeyWithResponse(KeyCreateOptions keyCreateOptions, Context context) {
Objects.requireNonNull(keyCreateOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(keyCreateOptions.getKeyType())
.setKeyOps(keyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(keyCreateOptions));
return service.createKey(endpoint, keyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", keyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", keyCreateOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link RsaKeyCreateOptions} is required. The {@link RsaKeyCreateOptions
* optionally specified. The {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
*
* <p>The {@link RsaKeyCreateOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param rsaKeyCreateOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createRsaKey(RsaKeyCreateOptions rsaKeyCreateOptions) {
try {
return createRsaKeyWithResponse(rsaKeyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link RsaKeyCreateOptions} is required. The {@link RsaKeyCreateOptions
* optionally specified. The {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
* RsaKeyCreateOptions
*
* <p>The {@link RsaKeyCreateOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param rsaKeyCreateOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createRsaKeyWithResponse(RsaKeyCreateOptions rsaKeyCreateOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(rsaKeyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createRsaKeyWithResponse(RsaKeyCreateOptions rsaKeyCreateOptions, Context context) {
Objects.requireNonNull(rsaKeyCreateOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(rsaKeyCreateOptions.getKeyType())
.setKeySize(rsaKeyCreateOptions.getKeySize())
.setKeyOps(rsaKeyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(rsaKeyCreateOptions));
return service.createKey(endpoint, rsaKeyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", rsaKeyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", rsaKeyCreateOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link EcKeyCreateOptions} parameter is required. The {@link EcKeyCreateOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link EcKeyCreateOptions
* values are optional. The {@link EcKeyCreateOptions
* if not specified.</p>
*
* <p>The {@link EcKeyCreateOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param ecKeyCreateOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createEcKey(EcKeyCreateOptions ecKeyCreateOptions) {
try {
return createEcKeyWithResponse(ecKeyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link EcKeyCreateOptions} parameter is required. The {@link EcKeyCreateOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link EcKeyCreateOptions
* values are optional. The {@link EcKeyCreateOptions
* not specified.</p>
*
* <p>The {@link EcKeyCreateOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param ecKeyCreateOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createEcKeyWithResponse(EcKeyCreateOptions ecKeyCreateOptions) {
try {
return withContext(context -> createEcKeyWithResponse(ecKeyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createEcKeyWithResponse(EcKeyCreateOptions ecKeyCreateOptions, Context context) {
Objects.requireNonNull(ecKeyCreateOptions, "The Ec key options options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(ecKeyCreateOptions.getKeyType())
.setCurve(ecKeyCreateOptions.getCurve())
.setKeyOps(ecKeyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(ecKeyCreateOptions));
return service.createKey(endpoint, ecKeyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", ecKeyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", ecKeyCreateOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link KeyImportOptions
* KeyImportOptions
* {@link KeyImportOptions
* no values are set for the fields. The {@link KeyImportOptions
* {@link KeyImportOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param keyImportOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link Key imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> importKey(KeyImportOptions keyImportOptions) {
try {
return importKeyWithResponse(keyImportOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link KeyImportOptions
* KeyImportOptions
* {@link KeyImportOptions
* no values are set for the fields. The {@link KeyImportOptions
* field is set to true and the {@link KeyImportOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param keyImportOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> importKeyWithResponse(KeyImportOptions keyImportOptions) {
try {
return withContext(context -> importKeyWithResponse(keyImportOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> importKeyWithResponse(KeyImportOptions keyImportOptions, Context context) {
Objects.requireNonNull(keyImportOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(keyImportOptions.getKeyMaterial())
.setHsm(keyImportOptions.isHsm())
.setKeyAttributes(new KeyRequestAttributes(keyImportOptions));
return service.importKey(endpoint, keyImportOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", keyImportOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", keyImportOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get public part of the key which represents {@link KeyProperties keyProperties} from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p>The list operations {@link KeyAsyncClient
* return the {@link Flux} containing {@link KeyProperties key properties} as output excluding the key material of the key.
* This operation can then be used to get the full key with its key material from {@code keyProperties}.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param keyProperties The {@link KeyProperties key properties} holding attributes of the key being requested.
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param endpoint URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
KeyAsyncClient(URL endpoint, HttpPipeline pipeline) {
Objects.requireNonNull(endpoint,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.endpoint = endpoint.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param keyCreateOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createKeyWithResponse(KeyCreateOptions keyCreateOptions) {
try {
return withContext(context -> createKeyWithResponse(keyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType);
return service.createKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Creating key - {}", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyCreateOptions} is required. The {@link KeyCreateOptions
* KeyCreateOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link KeyCreateOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param keyCreateOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createKey(KeyCreateOptions keyCreateOptions) {
try {
return createKeyWithResponse(keyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createKeyWithResponse(KeyCreateOptions keyCreateOptions, Context context) {
Objects.requireNonNull(keyCreateOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(keyCreateOptions.getKeyType())
.setKeyOps(keyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(keyCreateOptions));
return service.createKey(endpoint, keyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", keyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", keyCreateOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link RsaKeyCreateOptions} is required. The {@link RsaKeyCreateOptions
* optionally specified. The {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
*
* <p>The {@link RsaKeyCreateOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param rsaKeyCreateOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createRsaKey(RsaKeyCreateOptions rsaKeyCreateOptions) {
try {
return createRsaKeyWithResponse(rsaKeyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link RsaKeyCreateOptions} is required. The {@link RsaKeyCreateOptions
* optionally specified. The {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
* RsaKeyCreateOptions
*
* <p>The {@link RsaKeyCreateOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param rsaKeyCreateOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createRsaKeyWithResponse(RsaKeyCreateOptions rsaKeyCreateOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(rsaKeyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createRsaKeyWithResponse(RsaKeyCreateOptions rsaKeyCreateOptions, Context context) {
Objects.requireNonNull(rsaKeyCreateOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(rsaKeyCreateOptions.getKeyType())
.setKeySize(rsaKeyCreateOptions.getKeySize())
.setKeyOps(rsaKeyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(rsaKeyCreateOptions));
return service.createKey(endpoint, rsaKeyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", rsaKeyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", rsaKeyCreateOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link EcKeyCreateOptions} parameter is required. The {@link EcKeyCreateOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link EcKeyCreateOptions
* values are optional. The {@link EcKeyCreateOptions
* if not specified.</p>
*
* <p>The {@link EcKeyCreateOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param ecKeyCreateOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createEcKey(EcKeyCreateOptions ecKeyCreateOptions) {
try {
return createEcKeyWithResponse(ecKeyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link EcKeyCreateOptions} parameter is required. The {@link EcKeyCreateOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link EcKeyCreateOptions
* values are optional. The {@link EcKeyCreateOptions
* not specified.</p>
*
* <p>The {@link EcKeyCreateOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param ecKeyCreateOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createEcKeyWithResponse(EcKeyCreateOptions ecKeyCreateOptions) {
try {
return withContext(context -> createEcKeyWithResponse(ecKeyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createEcKeyWithResponse(EcKeyCreateOptions ecKeyCreateOptions, Context context) {
Objects.requireNonNull(ecKeyCreateOptions, "The Ec key options options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(ecKeyCreateOptions.getKeyType())
.setCurve(ecKeyCreateOptions.getCurve())
.setKeyOps(ecKeyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(ecKeyCreateOptions));
return service.createKey(endpoint, ecKeyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", ecKeyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", ecKeyCreateOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link KeyImportOptions
* KeyImportOptions
* {@link KeyImportOptions
* no values are set for the fields. The {@link KeyImportOptions
* {@link KeyImportOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param keyImportOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link Key imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> importKey(KeyImportOptions keyImportOptions) {
try {
return importKeyWithResponse(keyImportOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link KeyImportOptions
* KeyImportOptions
* {@link KeyImportOptions
* no values are set for the fields. The {@link KeyImportOptions
* field is set to true and the {@link KeyImportOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param keyImportOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> importKeyWithResponse(KeyImportOptions keyImportOptions) {
try {
return withContext(context -> importKeyWithResponse(keyImportOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> importKeyWithResponse(KeyImportOptions keyImportOptions, Context context) {
Objects.requireNonNull(keyImportOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(keyImportOptions.getKeyMaterial())
.setHsm(keyImportOptions.isHsm())
.setKeyAttributes(new KeyRequestAttributes(keyImportOptions));
return service.importKey(endpoint, keyImportOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", keyImportOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", keyImportOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get public part of the key which represents {@link KeyProperties keyProperties} from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p>The list operations {@link KeyAsyncClient
* return the {@link Flux} containing {@link KeyProperties key properties} as output excluding the key material of the key.
* This operation can then be used to get the full key with its key material from {@code keyProperties}.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param keyProperties The {@link KeyProperties key properties} holding attributes of the key being requested.
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties |
Yes | public Mono<Response<Key>> getKeyWithResponse(KeyProperties keyProperties) {
try {
Objects.requireNonNull(keyProperties, "The Key Properties parameter cannot be null.");
return withContext(context -> getKeyWithResponse(keyProperties.getName(), keyProperties.getVersion() == null ? ""
: keyProperties.getVersion(), context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | Objects.requireNonNull(keyProperties, "The Key Properties parameter cannot be null."); | return withContext(context -> getKeyWithResponse(keyProperties.getName(), keyProperties.getVersion() == null ? ""
: keyProperties.getVersion(), context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
} | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param endpoint URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
KeyAsyncClient(URL endpoint, HttpPipeline pipeline) {
Objects.requireNonNull(endpoint,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.endpoint = endpoint.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param keyCreateOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createKeyWithResponse(KeyCreateOptions keyCreateOptions) {
try {
return withContext(context -> createKeyWithResponse(keyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType);
return service.createKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Creating key - {}", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyCreateOptions} is required. The {@link KeyCreateOptions
* KeyCreateOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link KeyCreateOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param keyCreateOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createKey(KeyCreateOptions keyCreateOptions) {
try {
return createKeyWithResponse(keyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createKeyWithResponse(KeyCreateOptions keyCreateOptions, Context context) {
Objects.requireNonNull(keyCreateOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(keyCreateOptions.getKeyType())
.setKeyOps(keyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(keyCreateOptions));
return service.createKey(endpoint, keyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", keyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", keyCreateOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link RsaKeyCreateOptions} is required. The {@link RsaKeyCreateOptions
* optionally specified. The {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
*
* <p>The {@link RsaKeyCreateOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param rsaKeyCreateOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createRsaKey(RsaKeyCreateOptions rsaKeyCreateOptions) {
try {
return createRsaKeyWithResponse(rsaKeyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link RsaKeyCreateOptions} is required. The {@link RsaKeyCreateOptions
* optionally specified. The {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
* RsaKeyCreateOptions
*
* <p>The {@link RsaKeyCreateOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param rsaKeyCreateOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createRsaKeyWithResponse(RsaKeyCreateOptions rsaKeyCreateOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(rsaKeyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createRsaKeyWithResponse(RsaKeyCreateOptions rsaKeyCreateOptions, Context context) {
Objects.requireNonNull(rsaKeyCreateOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(rsaKeyCreateOptions.getKeyType())
.setKeySize(rsaKeyCreateOptions.getKeySize())
.setKeyOps(rsaKeyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(rsaKeyCreateOptions));
return service.createKey(endpoint, rsaKeyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", rsaKeyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", rsaKeyCreateOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link EcKeyCreateOptions} parameter is required. The {@link EcKeyCreateOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link EcKeyCreateOptions
* values are optional. The {@link EcKeyCreateOptions
* if not specified.</p>
*
* <p>The {@link EcKeyCreateOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param ecKeyCreateOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createEcKey(EcKeyCreateOptions ecKeyCreateOptions) {
try {
return createEcKeyWithResponse(ecKeyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link EcKeyCreateOptions} parameter is required. The {@link EcKeyCreateOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link EcKeyCreateOptions
* values are optional. The {@link EcKeyCreateOptions
* not specified.</p>
*
* <p>The {@link EcKeyCreateOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param ecKeyCreateOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createEcKeyWithResponse(EcKeyCreateOptions ecKeyCreateOptions) {
try {
return withContext(context -> createEcKeyWithResponse(ecKeyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createEcKeyWithResponse(EcKeyCreateOptions ecKeyCreateOptions, Context context) {
Objects.requireNonNull(ecKeyCreateOptions, "The Ec key options options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(ecKeyCreateOptions.getKeyType())
.setCurve(ecKeyCreateOptions.getCurve())
.setKeyOps(ecKeyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(ecKeyCreateOptions));
return service.createKey(endpoint, ecKeyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", ecKeyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", ecKeyCreateOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link KeyImportOptions
* KeyImportOptions
* {@link KeyImportOptions
* no values are set for the fields. The {@link KeyImportOptions
* {@link KeyImportOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param keyImportOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link Key imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> importKey(KeyImportOptions keyImportOptions) {
try {
return importKeyWithResponse(keyImportOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link KeyImportOptions
* KeyImportOptions
* {@link KeyImportOptions
* no values are set for the fields. The {@link KeyImportOptions
* field is set to true and the {@link KeyImportOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param keyImportOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> importKeyWithResponse(KeyImportOptions keyImportOptions) {
try {
return withContext(context -> importKeyWithResponse(keyImportOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> importKeyWithResponse(KeyImportOptions keyImportOptions, Context context) {
Objects.requireNonNull(keyImportOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(keyImportOptions.getKeyMaterial())
.setHsm(keyImportOptions.isHsm())
.setKeyAttributes(new KeyRequestAttributes(keyImportOptions));
return service.importKey(endpoint, keyImportOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", keyImportOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", keyImportOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get public part of the key which represents {@link KeyProperties keyProperties} from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p>The list operations {@link KeyAsyncClient
* return the {@link Flux} containing {@link KeyProperties key properties} as output excluding the key material of the key.
* This operation can then be used to get the full key with its key material from {@code keyProperties}.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param keyProperties The {@link KeyProperties key properties} holding attributes of the key being requested.
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param endpoint URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
*/
KeyAsyncClient(URL endpoint, HttpPipeline pipeline) {
Objects.requireNonNull(endpoint,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.endpoint = endpoint.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param keyCreateOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createKeyWithResponse(KeyCreateOptions keyCreateOptions) {
try {
return withContext(context -> createKeyWithResponse(keyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = new KeyRequestParameters().setKty(keyType);
return service.createKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Creating key - {}", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyCreateOptions} is required. The {@link KeyCreateOptions
* KeyCreateOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link KeyCreateOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param keyCreateOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createKey(KeyCreateOptions keyCreateOptions) {
try {
return createKeyWithResponse(keyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createKeyWithResponse(KeyCreateOptions keyCreateOptions, Context context) {
Objects.requireNonNull(keyCreateOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(keyCreateOptions.getKeyType())
.setKeyOps(keyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(keyCreateOptions));
return service.createKey(endpoint, keyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", keyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", keyCreateOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link RsaKeyCreateOptions} is required. The {@link RsaKeyCreateOptions
* optionally specified. The {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
*
* <p>The {@link RsaKeyCreateOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param rsaKeyCreateOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createRsaKey(RsaKeyCreateOptions rsaKeyCreateOptions) {
try {
return createRsaKeyWithResponse(rsaKeyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link RsaKeyCreateOptions} is required. The {@link RsaKeyCreateOptions
* optionally specified. The {@link RsaKeyCreateOptions
* {@link RsaKeyCreateOptions
* RsaKeyCreateOptions
*
* <p>The {@link RsaKeyCreateOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param rsaKeyCreateOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createRsaKeyWithResponse(RsaKeyCreateOptions rsaKeyCreateOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(rsaKeyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createRsaKeyWithResponse(RsaKeyCreateOptions rsaKeyCreateOptions, Context context) {
Objects.requireNonNull(rsaKeyCreateOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(rsaKeyCreateOptions.getKeyType())
.setKeySize(rsaKeyCreateOptions.getKeySize())
.setKeyOps(rsaKeyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(rsaKeyCreateOptions));
return service.createKey(endpoint, rsaKeyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", rsaKeyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", rsaKeyCreateOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link EcKeyCreateOptions} parameter is required. The {@link EcKeyCreateOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link EcKeyCreateOptions
* values are optional. The {@link EcKeyCreateOptions
* if not specified.</p>
*
* <p>The {@link EcKeyCreateOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param ecKeyCreateOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link Key created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> createEcKey(EcKeyCreateOptions ecKeyCreateOptions) {
try {
return createEcKeyWithResponse(ecKeyCreateOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link EcKeyCreateOptions} parameter is required. The {@link EcKeyCreateOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link EcKeyCreateOptions
* values are optional. The {@link EcKeyCreateOptions
* not specified.</p>
*
* <p>The {@link EcKeyCreateOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param ecKeyCreateOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> createEcKeyWithResponse(EcKeyCreateOptions ecKeyCreateOptions) {
try {
return withContext(context -> createEcKeyWithResponse(ecKeyCreateOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> createEcKeyWithResponse(EcKeyCreateOptions ecKeyCreateOptions, Context context) {
Objects.requireNonNull(ecKeyCreateOptions, "The Ec key options options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(ecKeyCreateOptions.getKeyType())
.setCurve(ecKeyCreateOptions.getCurve())
.setKeyOps(ecKeyCreateOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(ecKeyCreateOptions));
return service.createKey(endpoint, ecKeyCreateOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", ecKeyCreateOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", ecKeyCreateOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link KeyImportOptions
* KeyImportOptions
* {@link KeyImportOptions
* no values are set for the fields. The {@link KeyImportOptions
* {@link KeyImportOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param keyImportOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link Key imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> importKey(KeyImportOptions keyImportOptions) {
try {
return importKeyWithResponse(keyImportOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link KeyImportOptions
* KeyImportOptions
* {@link KeyImportOptions
* no values are set for the fields. The {@link KeyImportOptions
* field is set to true and the {@link KeyImportOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param keyImportOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> importKeyWithResponse(KeyImportOptions keyImportOptions) {
try {
return withContext(context -> importKeyWithResponse(keyImportOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> importKeyWithResponse(KeyImportOptions keyImportOptions, Context context) {
Objects.requireNonNull(keyImportOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(keyImportOptions.getKeyMaterial())
.setHsm(keyImportOptions.isHsm())
.setKeyAttributes(new KeyRequestAttributes(keyImportOptions));
return service.importKey(endpoint, keyImportOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", keyImportOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", keyImportOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Key>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Key>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Key> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get public part of the key which represents {@link KeyProperties keyProperties} from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p>The list operations {@link KeyAsyncClient
* return the {@link Flux} containing {@link KeyProperties key properties} as output excluding the key material of the key.
* This operation can then be used to get the full key with its key material from {@code keyProperties}.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param keyProperties The {@link KeyProperties key properties} holding attributes of the key being requested.
* @return A {@link Mono} containing the requested {@link Key key}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties |
nit; alternatively we can use `count()` operator https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#count-- | public Mono<Integer> forceCloseAllHandles(boolean recursive) {
return fluxContext(context -> forceCloseAllHandlesWithTimeout(recursive, null, context))
.reduce(0, Integer::sum);
} | .reduce(0, Integer::sum); | public Mono<Integer> forceCloseAllHandles(boolean recursive) {
try {
return withContext(context -> forceCloseAllHandlesWithTimeout(recursive, null, context)
.reduce(0, Integer::sum));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?snapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?snapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient |
Let's continue using reduce for now as we won't need to do another mapping to downcast. | public Mono<Integer> forceCloseAllHandles(boolean recursive) {
return fluxContext(context -> forceCloseAllHandlesWithTimeout(recursive, null, context))
.reduce(0, Integer::sum);
} | .reduce(0, Integer::sum); | public Mono<Integer> forceCloseAllHandles(boolean recursive) {
try {
return withContext(context -> forceCloseAllHandlesWithTimeout(recursive, null, context)
.reduce(0, Integer::sum));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?snapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?snapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient |
Sounds good. | public Mono<Integer> forceCloseAllHandles(boolean recursive) {
return fluxContext(context -> forceCloseAllHandlesWithTimeout(recursive, null, context))
.reduce(0, Integer::sum);
} | .reduce(0, Integer::sum); | public Mono<Integer> forceCloseAllHandles(boolean recursive) {
try {
return withContext(context -> forceCloseAllHandlesWithTimeout(recursive, null, context)
.reduce(0, Integer::sum));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?snapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
private final String accountName;
/**
* Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link
* AzureFileStorageImpl
* {@code client}.
*
* @param azureFileStorageClient Client that interacts with the service interfaces
* @param shareName Name of the share
* @param directoryPath Name of the directory
* @param snapshot The snapshot of the share
*/
DirectoryAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String directoryPath,
String snapshot, String accountName) {
Objects.requireNonNull(shareName, "'shareName' cannot be null.");
Objects.requireNonNull(directoryPath);
this.shareName = shareName;
this.directoryPath = directoryPath;
this.snapshot = snapshot;
this.azureFileStorageClient = azureFileStorageClient;
this.accountName = accountName;
}
/**
* Get the url of the storage directory client.
*
* @return the URL of the storage directory client
*/
public String getDirectoryUrl() {
StringBuilder directoryUrlString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryUrlString.append("?snapshot=").append(snapshot);
}
return directoryUrlString.toString();
}
/**
* Constructs a FileAsyncClient that interacts with the specified file.
*
* <p>If the file doesn't exist in this directory {@link FileAsyncClient |
nit: `urlPath += "?" + urlQuery;` ? | private Mono<HttpResponse> setupBatchOperation(HttpRequest request) {
return Mono.fromRunnable(() -> {
int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue());
StringBuilder batchRequestBuilder = new StringBuilder();
appendWithNewline(batchRequestBuilder, "--" + batchBoundary);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING);
appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
String method = request.getHttpMethod().toString();
String urlPath = request.getUrl().getPath();
String urlQuery = request.getUrl().getQuery();
if (!ImplUtils.isNullOrEmpty(urlQuery)) {
urlPath = urlPath + "?" + urlQuery;
}
appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION));
request.getHeaders().stream()
.filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName()))
.forEach(header -> appendWithNewline(batchRequestBuilder,
String.format(HEADER_TEMPLATE, header.getName(), header.getValue())));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8)));
batchMapping.get(contentId).setRequest(request);
});
} | urlPath = urlPath + "?" + urlQuery; | private Mono<HttpResponse> setupBatchOperation(HttpRequest request) {
return Mono.fromRunnable(() -> {
int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue());
StringBuilder batchRequestBuilder = new StringBuilder();
appendWithNewline(batchRequestBuilder, "--" + batchBoundary);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING);
appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
String method = request.getHttpMethod().toString();
String urlPath = request.getUrl().getPath();
String urlQuery = request.getUrl().getQuery();
if (!ImplUtils.isNullOrEmpty(urlQuery)) {
urlPath = urlPath + "?" + urlQuery;
}
appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION));
request.getHeaders().stream()
.filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName()))
.forEach(header -> appendWithNewline(batchRequestBuilder,
String.format(HEADER_TEMPLATE, header.getName(), header.getValue())));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8)));
batchMapping.get(contentId).setRequest(request);
});
} | class BlobBatch {
private static final String X_MS_VERSION = "x-ms-version";
private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id";
private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path";
private static final String CONTENT_ID = "Content-Id";
private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s";
private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s";
private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http";
private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary";
private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d";
private static final String HTTP_VERSION = "HTTP/1.1";
private static final String OPERATION_TEMPLATE = "%s %s %s";
private static final String HEADER_TEMPLATE = "%s: %s";
private static final String PATH_TEMPLATE = "%s/%s";
/*
* Track the status codes expected for the batching operations here as the batch body does not get parsed in
* Azure Core where this information is maintained.
*/
private static final int[] EXPECTED_DELETE_STATUS_CODES = {202};
private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202};
private final ClientLogger logger = new ClientLogger(BlobBatch.class);
private final BlobAsyncClient blobAsyncClient;
private final Deque<Mono<? extends Response<?>>> batchOperationQueue;
private final List<ByteBuffer> batchRequest;
private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping;
private final AtomicInteger contentId;
private final String batchBoundary;
private final String contentType;
private BlobBatchType batchType;
BlobBatch(String accountUrl, HttpPipeline pipeline) {
this.contentId = new AtomicInteger();
this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID());
this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary);
boolean batchHeadersPolicySet = false;
HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation);
for (int i = 0; i < pipeline.getPolicyCount(); i++) {
HttpPipelinePolicy policy = pipeline.getPolicy(i);
if (policy instanceof StorageSharedKeyCredentialPolicy) {
batchHeadersPolicySet = true;
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
batchPipelineBuilder.policies(policy);
}
if (!batchHeadersPolicySet) {
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
this.blobAsyncClient = new BlobClientBuilder()
.endpoint(accountUrl)
.blobName("")
.pipeline(batchPipelineBuilder.build())
.buildAsyncClient();
this.batchOperationQueue = new ConcurrentLinkedDeque<>();
this.batchRequest = new ArrayList<>();
this.batchMapping = new ConcurrentHashMap<>();
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName,
DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName),
deleteOptions, blobAccessConditions);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl) {
return deleteBlobHelper(getUrlPath(blobUrl), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions);
}
private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
setBatchType(BlobBatchType.DELETE);
return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions),
urlPath, EXPECTED_DELETE_STATUS_CODES);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier,
leaseAccessConditions);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions);
}
private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
setBatchType(BlobBatchType.SET_TIER);
return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions),
urlPath, EXPECTED_SET_TIER_STATUS_CODES);
}
private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath,
int... expectedStatusCodes) {
int id = contentId.getAndIncrement();
batchOperationQueue.add(response
.subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath)));
BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes);
batchMapping.put(id, batchOperationResponse);
return batchOperationResponse;
}
private String getUrlPath(String url) {
return UrlBuilder.parse(url).getPath();
}
private void setBatchType(BlobBatchType batchType) {
if (this.batchType == null) {
this.batchType = batchType;
} else if (this.batchType != batchType) {
throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT,
"'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType)));
}
}
Flux<ByteBuffer> getBody() {
if (batchOperationQueue.isEmpty()) {
throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed."));
}
Disposable disposable = Flux.fromStream(batchOperationQueue.stream())
.flatMap(batchOperation -> batchOperation)
.subscribe();
/* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from
* throwing an exception if this was ran in a Reactor thread.
*/
while (!disposable.isDisposed()) {
}
this.batchRequest.add(ByteBuffer.wrap(
String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8)));
return Flux.fromIterable(batchRequest);
}
long getContentLength() {
long contentLength = 0;
for (ByteBuffer request : batchRequest) {
contentLength += request.remaining();
}
return contentLength;
}
String getContentType() {
return contentType;
}
BlobBatchOperationResponse<?> getBatchRequest(int contentId) {
return batchMapping.get(contentId);
}
int getOperationCount() {
return batchMapping.size();
}
/*
* This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp.
* Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this
* and it adds the header "Content-Id" that allows the request to be mapped to the response.
*/
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
context.getHttpRequest().getHeaders().remove(X_MS_VERSION);
Map<String, String> headers = context.getHttpRequest().getHeaders().toMap();
headers.entrySet().removeIf(header -> header.getValue() == null);
context.getHttpRequest().setHeaders(new HttpHeaders(headers));
context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString());
return next.process();
}
/*
* This performs changing the request URL to the value passed through the pipeline context. This policy is used in
* place of constructing a new client for each batch request that is being sent.
*/
private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
try {
UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl());
requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString());
context.getHttpRequest().setUrl(requestUrl.toURL());
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex)));
}
return next.process();
}
/*
* This will "send" the batch operation request when triggered, it simply acts as a way to build and write the
* batch operation into the overall request and then returns nothing as the response.
*/
private void appendWithNewline(StringBuilder stringBuilder, String value) {
stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE);
}
} | class BlobBatch {
private static final String X_MS_VERSION = "x-ms-version";
private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id";
private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path";
private static final String CONTENT_ID = "Content-Id";
private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s";
private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s";
private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http";
private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary";
private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d";
private static final String HTTP_VERSION = "HTTP/1.1";
private static final String OPERATION_TEMPLATE = "%s %s %s";
private static final String HEADER_TEMPLATE = "%s: %s";
private static final String PATH_TEMPLATE = "%s/%s";
/*
* Track the status codes expected for the batching operations here as the batch body does not get parsed in
* Azure Core where this information is maintained.
*/
private static final int[] EXPECTED_DELETE_STATUS_CODES = {202};
private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202};
private final ClientLogger logger = new ClientLogger(BlobBatch.class);
private final BlobAsyncClient blobAsyncClient;
private final Deque<Mono<? extends Response<?>>> batchOperationQueue;
private final List<ByteBuffer> batchRequest;
private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping;
private final AtomicInteger contentId;
private final String batchBoundary;
private final String contentType;
private BlobBatchType batchType;
BlobBatch(String accountUrl, HttpPipeline pipeline) {
this.contentId = new AtomicInteger();
this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID());
this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary);
boolean batchHeadersPolicySet = false;
HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation);
for (int i = 0; i < pipeline.getPolicyCount(); i++) {
HttpPipelinePolicy policy = pipeline.getPolicy(i);
if (policy instanceof StorageSharedKeyCredentialPolicy) {
batchHeadersPolicySet = true;
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
batchPipelineBuilder.policies(policy);
}
if (!batchHeadersPolicySet) {
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
this.blobAsyncClient = new BlobClientBuilder()
.endpoint(accountUrl)
.blobName("")
.pipeline(batchPipelineBuilder.build())
.buildAsyncClient();
this.batchOperationQueue = new ConcurrentLinkedDeque<>();
this.batchRequest = new ArrayList<>();
this.batchMapping = new ConcurrentHashMap<>();
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName,
DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName),
deleteOptions, blobAccessConditions);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl) {
return deleteBlobHelper(getUrlPath(blobUrl), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions);
}
private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
setBatchType(BlobBatchType.DELETE);
return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions),
urlPath, EXPECTED_DELETE_STATUS_CODES);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier,
leaseAccessConditions);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions);
}
private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
setBatchType(BlobBatchType.SET_TIER);
return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions),
urlPath, EXPECTED_SET_TIER_STATUS_CODES);
}
private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath,
int... expectedStatusCodes) {
int id = contentId.getAndIncrement();
batchOperationQueue.add(response
.subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath)));
BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes);
batchMapping.put(id, batchOperationResponse);
return batchOperationResponse;
}
private String getUrlPath(String url) {
return UrlBuilder.parse(url).getPath();
}
private void setBatchType(BlobBatchType batchType) {
if (this.batchType == null) {
this.batchType = batchType;
} else if (this.batchType != batchType) {
throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT,
"'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType)));
}
}
Flux<ByteBuffer> getBody() {
if (batchOperationQueue.isEmpty()) {
throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed."));
}
Disposable disposable = Flux.fromStream(batchOperationQueue.stream())
.flatMap(batchOperation -> batchOperation)
.subscribe();
/* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from
* throwing an exception if this was ran in a Reactor thread.
*/
while (!disposable.isDisposed()) {
}
this.batchRequest.add(ByteBuffer.wrap(
String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8)));
return Flux.fromIterable(batchRequest);
}
long getContentLength() {
long contentLength = 0;
for (ByteBuffer request : batchRequest) {
contentLength += request.remaining();
}
return contentLength;
}
String getContentType() {
return contentType;
}
BlobBatchOperationResponse<?> getBatchRequest(int contentId) {
return batchMapping.get(contentId);
}
int getOperationCount() {
return batchMapping.size();
}
/*
* This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp.
* Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this
* and it adds the header "Content-Id" that allows the request to be mapped to the response.
*/
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
context.getHttpRequest().getHeaders().remove(X_MS_VERSION);
Map<String, String> headers = context.getHttpRequest().getHeaders().toMap();
headers.entrySet().removeIf(header -> header.getValue() == null);
context.getHttpRequest().setHeaders(new HttpHeaders(headers));
context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString());
return next.process();
}
/*
* This performs changing the request URL to the value passed through the pipeline context. This policy is used in
* place of constructing a new client for each batch request that is being sent.
*/
private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
try {
UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl());
requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString());
context.getHttpRequest().setUrl(requestUrl.toURL());
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex)));
}
return next.process();
}
/*
* This will "send" the batch operation request when triggered, it simply acts as a way to build and write the
* batch operation into the overall request and then returns nothing as the response.
*/
private void appendWithNewline(StringBuilder stringBuilder, String value) {
stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE);
}
} |
I will add an issue to change this next week as it won't touch API | private Mono<HttpResponse> setupBatchOperation(HttpRequest request) {
return Mono.fromRunnable(() -> {
int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue());
StringBuilder batchRequestBuilder = new StringBuilder();
appendWithNewline(batchRequestBuilder, "--" + batchBoundary);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING);
appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
String method = request.getHttpMethod().toString();
String urlPath = request.getUrl().getPath();
String urlQuery = request.getUrl().getQuery();
if (!ImplUtils.isNullOrEmpty(urlQuery)) {
urlPath = urlPath + "?" + urlQuery;
}
appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION));
request.getHeaders().stream()
.filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName()))
.forEach(header -> appendWithNewline(batchRequestBuilder,
String.format(HEADER_TEMPLATE, header.getName(), header.getValue())));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8)));
batchMapping.get(contentId).setRequest(request);
});
} | urlPath = urlPath + "?" + urlQuery; | private Mono<HttpResponse> setupBatchOperation(HttpRequest request) {
return Mono.fromRunnable(() -> {
int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue());
StringBuilder batchRequestBuilder = new StringBuilder();
appendWithNewline(batchRequestBuilder, "--" + batchBoundary);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING);
appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
String method = request.getHttpMethod().toString();
String urlPath = request.getUrl().getPath();
String urlQuery = request.getUrl().getQuery();
if (!ImplUtils.isNullOrEmpty(urlQuery)) {
urlPath = urlPath + "?" + urlQuery;
}
appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION));
request.getHeaders().stream()
.filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName()))
.forEach(header -> appendWithNewline(batchRequestBuilder,
String.format(HEADER_TEMPLATE, header.getName(), header.getValue())));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8)));
batchMapping.get(contentId).setRequest(request);
});
} | class BlobBatch {
private static final String X_MS_VERSION = "x-ms-version";
private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id";
private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path";
private static final String CONTENT_ID = "Content-Id";
private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s";
private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s";
private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http";
private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary";
private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d";
private static final String HTTP_VERSION = "HTTP/1.1";
private static final String OPERATION_TEMPLATE = "%s %s %s";
private static final String HEADER_TEMPLATE = "%s: %s";
private static final String PATH_TEMPLATE = "%s/%s";
/*
* Track the status codes expected for the batching operations here as the batch body does not get parsed in
* Azure Core where this information is maintained.
*/
private static final int[] EXPECTED_DELETE_STATUS_CODES = {202};
private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202};
private final ClientLogger logger = new ClientLogger(BlobBatch.class);
private final BlobAsyncClient blobAsyncClient;
private final Deque<Mono<? extends Response<?>>> batchOperationQueue;
private final List<ByteBuffer> batchRequest;
private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping;
private final AtomicInteger contentId;
private final String batchBoundary;
private final String contentType;
private BlobBatchType batchType;
BlobBatch(String accountUrl, HttpPipeline pipeline) {
this.contentId = new AtomicInteger();
this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID());
this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary);
boolean batchHeadersPolicySet = false;
HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation);
for (int i = 0; i < pipeline.getPolicyCount(); i++) {
HttpPipelinePolicy policy = pipeline.getPolicy(i);
if (policy instanceof StorageSharedKeyCredentialPolicy) {
batchHeadersPolicySet = true;
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
batchPipelineBuilder.policies(policy);
}
if (!batchHeadersPolicySet) {
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
this.blobAsyncClient = new BlobClientBuilder()
.endpoint(accountUrl)
.blobName("")
.pipeline(batchPipelineBuilder.build())
.buildAsyncClient();
this.batchOperationQueue = new ConcurrentLinkedDeque<>();
this.batchRequest = new ArrayList<>();
this.batchMapping = new ConcurrentHashMap<>();
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName,
DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName),
deleteOptions, blobAccessConditions);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl) {
return deleteBlobHelper(getUrlPath(blobUrl), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions);
}
private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
setBatchType(BlobBatchType.DELETE);
return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions),
urlPath, EXPECTED_DELETE_STATUS_CODES);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier,
leaseAccessConditions);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions);
}
private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
setBatchType(BlobBatchType.SET_TIER);
return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions),
urlPath, EXPECTED_SET_TIER_STATUS_CODES);
}
private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath,
int... expectedStatusCodes) {
int id = contentId.getAndIncrement();
batchOperationQueue.add(response
.subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath)));
BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes);
batchMapping.put(id, batchOperationResponse);
return batchOperationResponse;
}
private String getUrlPath(String url) {
return UrlBuilder.parse(url).getPath();
}
private void setBatchType(BlobBatchType batchType) {
if (this.batchType == null) {
this.batchType = batchType;
} else if (this.batchType != batchType) {
throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT,
"'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType)));
}
}
Flux<ByteBuffer> getBody() {
if (batchOperationQueue.isEmpty()) {
throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed."));
}
Disposable disposable = Flux.fromStream(batchOperationQueue.stream())
.flatMap(batchOperation -> batchOperation)
.subscribe();
/* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from
* throwing an exception if this was ran in a Reactor thread.
*/
while (!disposable.isDisposed()) {
}
this.batchRequest.add(ByteBuffer.wrap(
String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8)));
return Flux.fromIterable(batchRequest);
}
long getContentLength() {
long contentLength = 0;
for (ByteBuffer request : batchRequest) {
contentLength += request.remaining();
}
return contentLength;
}
String getContentType() {
return contentType;
}
BlobBatchOperationResponse<?> getBatchRequest(int contentId) {
return batchMapping.get(contentId);
}
int getOperationCount() {
return batchMapping.size();
}
/*
* This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp.
* Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this
* and it adds the header "Content-Id" that allows the request to be mapped to the response.
*/
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
context.getHttpRequest().getHeaders().remove(X_MS_VERSION);
Map<String, String> headers = context.getHttpRequest().getHeaders().toMap();
headers.entrySet().removeIf(header -> header.getValue() == null);
context.getHttpRequest().setHeaders(new HttpHeaders(headers));
context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString());
return next.process();
}
/*
* This performs changing the request URL to the value passed through the pipeline context. This policy is used in
* place of constructing a new client for each batch request that is being sent.
*/
private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
try {
UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl());
requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString());
context.getHttpRequest().setUrl(requestUrl.toURL());
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex)));
}
return next.process();
}
/*
* This will "send" the batch operation request when triggered, it simply acts as a way to build and write the
* batch operation into the overall request and then returns nothing as the response.
*/
private void appendWithNewline(StringBuilder stringBuilder, String value) {
stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE);
}
} | class BlobBatch {
private static final String X_MS_VERSION = "x-ms-version";
private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id";
private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path";
private static final String CONTENT_ID = "Content-Id";
private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s";
private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s";
private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http";
private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary";
private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d";
private static final String HTTP_VERSION = "HTTP/1.1";
private static final String OPERATION_TEMPLATE = "%s %s %s";
private static final String HEADER_TEMPLATE = "%s: %s";
private static final String PATH_TEMPLATE = "%s/%s";
/*
* Track the status codes expected for the batching operations here as the batch body does not get parsed in
* Azure Core where this information is maintained.
*/
private static final int[] EXPECTED_DELETE_STATUS_CODES = {202};
private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202};
private final ClientLogger logger = new ClientLogger(BlobBatch.class);
private final BlobAsyncClient blobAsyncClient;
private final Deque<Mono<? extends Response<?>>> batchOperationQueue;
private final List<ByteBuffer> batchRequest;
private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping;
private final AtomicInteger contentId;
private final String batchBoundary;
private final String contentType;
private BlobBatchType batchType;
BlobBatch(String accountUrl, HttpPipeline pipeline) {
this.contentId = new AtomicInteger();
this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID());
this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary);
boolean batchHeadersPolicySet = false;
HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation);
for (int i = 0; i < pipeline.getPolicyCount(); i++) {
HttpPipelinePolicy policy = pipeline.getPolicy(i);
if (policy instanceof StorageSharedKeyCredentialPolicy) {
batchHeadersPolicySet = true;
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
batchPipelineBuilder.policies(policy);
}
if (!batchHeadersPolicySet) {
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
this.blobAsyncClient = new BlobClientBuilder()
.endpoint(accountUrl)
.blobName("")
.pipeline(batchPipelineBuilder.build())
.buildAsyncClient();
this.batchOperationQueue = new ConcurrentLinkedDeque<>();
this.batchRequest = new ArrayList<>();
this.batchMapping = new ConcurrentHashMap<>();
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName,
DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName),
deleteOptions, blobAccessConditions);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl) {
return deleteBlobHelper(getUrlPath(blobUrl), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions);
}
private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
setBatchType(BlobBatchType.DELETE);
return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions),
urlPath, EXPECTED_DELETE_STATUS_CODES);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier,
leaseAccessConditions);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions);
}
private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
setBatchType(BlobBatchType.SET_TIER);
return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions),
urlPath, EXPECTED_SET_TIER_STATUS_CODES);
}
private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath,
int... expectedStatusCodes) {
int id = contentId.getAndIncrement();
batchOperationQueue.add(response
.subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath)));
BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes);
batchMapping.put(id, batchOperationResponse);
return batchOperationResponse;
}
private String getUrlPath(String url) {
return UrlBuilder.parse(url).getPath();
}
private void setBatchType(BlobBatchType batchType) {
if (this.batchType == null) {
this.batchType = batchType;
} else if (this.batchType != batchType) {
throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT,
"'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType)));
}
}
Flux<ByteBuffer> getBody() {
if (batchOperationQueue.isEmpty()) {
throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed."));
}
Disposable disposable = Flux.fromStream(batchOperationQueue.stream())
.flatMap(batchOperation -> batchOperation)
.subscribe();
/* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from
* throwing an exception if this was ran in a Reactor thread.
*/
while (!disposable.isDisposed()) {
}
this.batchRequest.add(ByteBuffer.wrap(
String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8)));
return Flux.fromIterable(batchRequest);
}
long getContentLength() {
long contentLength = 0;
for (ByteBuffer request : batchRequest) {
contentLength += request.remaining();
}
return contentLength;
}
String getContentType() {
return contentType;
}
BlobBatchOperationResponse<?> getBatchRequest(int contentId) {
return batchMapping.get(contentId);
}
int getOperationCount() {
return batchMapping.size();
}
/*
* This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp.
* Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this
* and it adds the header "Content-Id" that allows the request to be mapped to the response.
*/
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
context.getHttpRequest().getHeaders().remove(X_MS_VERSION);
Map<String, String> headers = context.getHttpRequest().getHeaders().toMap();
headers.entrySet().removeIf(header -> header.getValue() == null);
context.getHttpRequest().setHeaders(new HttpHeaders(headers));
context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString());
return next.process();
}
/*
* This performs changing the request URL to the value passed through the pipeline context. This policy is used in
* place of constructing a new client for each batch request that is being sent.
*/
private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
try {
UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl());
requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString());
context.getHttpRequest().setUrl(requestUrl.toURL());
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex)));
}
return next.process();
}
/*
* This will "send" the batch operation request when triggered, it simply acts as a way to build and write the
* batch operation into the overall request and then returns nothing as the response.
*/
private void appendWithNewline(StringBuilder stringBuilder, String value) {
stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE);
}
} |
https://github.com/Azure/azure-sdk-for-java/issues/5942 | private Mono<HttpResponse> setupBatchOperation(HttpRequest request) {
return Mono.fromRunnable(() -> {
int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue());
StringBuilder batchRequestBuilder = new StringBuilder();
appendWithNewline(batchRequestBuilder, "--" + batchBoundary);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING);
appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
String method = request.getHttpMethod().toString();
String urlPath = request.getUrl().getPath();
String urlQuery = request.getUrl().getQuery();
if (!ImplUtils.isNullOrEmpty(urlQuery)) {
urlPath = urlPath + "?" + urlQuery;
}
appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION));
request.getHeaders().stream()
.filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName()))
.forEach(header -> appendWithNewline(batchRequestBuilder,
String.format(HEADER_TEMPLATE, header.getName(), header.getValue())));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8)));
batchMapping.get(contentId).setRequest(request);
});
} | urlPath = urlPath + "?" + urlQuery; | private Mono<HttpResponse> setupBatchOperation(HttpRequest request) {
return Mono.fromRunnable(() -> {
int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue());
StringBuilder batchRequestBuilder = new StringBuilder();
appendWithNewline(batchRequestBuilder, "--" + batchBoundary);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE);
appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING);
appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
String method = request.getHttpMethod().toString();
String urlPath = request.getUrl().getPath();
String urlQuery = request.getUrl().getQuery();
if (!ImplUtils.isNullOrEmpty(urlQuery)) {
urlPath = urlPath + "?" + urlQuery;
}
appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION));
request.getHeaders().stream()
.filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName()))
.forEach(header -> appendWithNewline(batchRequestBuilder,
String.format(HEADER_TEMPLATE, header.getName(), header.getValue())));
batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE);
batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8)));
batchMapping.get(contentId).setRequest(request);
});
} | class BlobBatch {
private static final String X_MS_VERSION = "x-ms-version";
private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id";
private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path";
private static final String CONTENT_ID = "Content-Id";
private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s";
private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s";
private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http";
private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary";
private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d";
private static final String HTTP_VERSION = "HTTP/1.1";
private static final String OPERATION_TEMPLATE = "%s %s %s";
private static final String HEADER_TEMPLATE = "%s: %s";
private static final String PATH_TEMPLATE = "%s/%s";
/*
* Track the status codes expected for the batching operations here as the batch body does not get parsed in
* Azure Core where this information is maintained.
*/
private static final int[] EXPECTED_DELETE_STATUS_CODES = {202};
private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202};
private final ClientLogger logger = new ClientLogger(BlobBatch.class);
private final BlobAsyncClient blobAsyncClient;
private final Deque<Mono<? extends Response<?>>> batchOperationQueue;
private final List<ByteBuffer> batchRequest;
private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping;
private final AtomicInteger contentId;
private final String batchBoundary;
private final String contentType;
private BlobBatchType batchType;
BlobBatch(String accountUrl, HttpPipeline pipeline) {
this.contentId = new AtomicInteger();
this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID());
this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary);
boolean batchHeadersPolicySet = false;
HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation);
for (int i = 0; i < pipeline.getPolicyCount(); i++) {
HttpPipelinePolicy policy = pipeline.getPolicy(i);
if (policy instanceof StorageSharedKeyCredentialPolicy) {
batchHeadersPolicySet = true;
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
batchPipelineBuilder.policies(policy);
}
if (!batchHeadersPolicySet) {
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
this.blobAsyncClient = new BlobClientBuilder()
.endpoint(accountUrl)
.blobName("")
.pipeline(batchPipelineBuilder.build())
.buildAsyncClient();
this.batchOperationQueue = new ConcurrentLinkedDeque<>();
this.batchRequest = new ArrayList<>();
this.batchMapping = new ConcurrentHashMap<>();
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName,
DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName),
deleteOptions, blobAccessConditions);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl) {
return deleteBlobHelper(getUrlPath(blobUrl), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions);
}
private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
setBatchType(BlobBatchType.DELETE);
return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions),
urlPath, EXPECTED_DELETE_STATUS_CODES);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier,
leaseAccessConditions);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions);
}
private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
setBatchType(BlobBatchType.SET_TIER);
return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions),
urlPath, EXPECTED_SET_TIER_STATUS_CODES);
}
private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath,
int... expectedStatusCodes) {
int id = contentId.getAndIncrement();
batchOperationQueue.add(response
.subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath)));
BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes);
batchMapping.put(id, batchOperationResponse);
return batchOperationResponse;
}
private String getUrlPath(String url) {
return UrlBuilder.parse(url).getPath();
}
private void setBatchType(BlobBatchType batchType) {
if (this.batchType == null) {
this.batchType = batchType;
} else if (this.batchType != batchType) {
throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT,
"'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType)));
}
}
Flux<ByteBuffer> getBody() {
if (batchOperationQueue.isEmpty()) {
throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed."));
}
Disposable disposable = Flux.fromStream(batchOperationQueue.stream())
.flatMap(batchOperation -> batchOperation)
.subscribe();
/* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from
* throwing an exception if this was ran in a Reactor thread.
*/
while (!disposable.isDisposed()) {
}
this.batchRequest.add(ByteBuffer.wrap(
String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8)));
return Flux.fromIterable(batchRequest);
}
long getContentLength() {
long contentLength = 0;
for (ByteBuffer request : batchRequest) {
contentLength += request.remaining();
}
return contentLength;
}
String getContentType() {
return contentType;
}
BlobBatchOperationResponse<?> getBatchRequest(int contentId) {
return batchMapping.get(contentId);
}
int getOperationCount() {
return batchMapping.size();
}
/*
* This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp.
* Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this
* and it adds the header "Content-Id" that allows the request to be mapped to the response.
*/
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
context.getHttpRequest().getHeaders().remove(X_MS_VERSION);
Map<String, String> headers = context.getHttpRequest().getHeaders().toMap();
headers.entrySet().removeIf(header -> header.getValue() == null);
context.getHttpRequest().setHeaders(new HttpHeaders(headers));
context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString());
return next.process();
}
/*
* This performs changing the request URL to the value passed through the pipeline context. This policy is used in
* place of constructing a new client for each batch request that is being sent.
*/
private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
try {
UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl());
requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString());
context.getHttpRequest().setUrl(requestUrl.toURL());
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex)));
}
return next.process();
}
/*
* This will "send" the batch operation request when triggered, it simply acts as a way to build and write the
* batch operation into the overall request and then returns nothing as the response.
*/
private void appendWithNewline(StringBuilder stringBuilder, String value) {
stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE);
}
} | class BlobBatch {
private static final String X_MS_VERSION = "x-ms-version";
private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id";
private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path";
private static final String CONTENT_ID = "Content-Id";
private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s";
private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s";
private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http";
private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary";
private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d";
private static final String HTTP_VERSION = "HTTP/1.1";
private static final String OPERATION_TEMPLATE = "%s %s %s";
private static final String HEADER_TEMPLATE = "%s: %s";
private static final String PATH_TEMPLATE = "%s/%s";
/*
* Track the status codes expected for the batching operations here as the batch body does not get parsed in
* Azure Core where this information is maintained.
*/
private static final int[] EXPECTED_DELETE_STATUS_CODES = {202};
private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202};
private final ClientLogger logger = new ClientLogger(BlobBatch.class);
private final BlobAsyncClient blobAsyncClient;
private final Deque<Mono<? extends Response<?>>> batchOperationQueue;
private final List<ByteBuffer> batchRequest;
private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping;
private final AtomicInteger contentId;
private final String batchBoundary;
private final String contentType;
private BlobBatchType batchType;
BlobBatch(String accountUrl, HttpPipeline pipeline) {
this.contentId = new AtomicInteger();
this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID());
this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary);
boolean batchHeadersPolicySet = false;
HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation);
for (int i = 0; i < pipeline.getPolicyCount(); i++) {
HttpPipelinePolicy policy = pipeline.getPolicy(i);
if (policy instanceof StorageSharedKeyCredentialPolicy) {
batchHeadersPolicySet = true;
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
batchPipelineBuilder.policies(policy);
}
if (!batchHeadersPolicySet) {
batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl);
}
this.blobAsyncClient = new BlobClientBuilder()
.endpoint(accountUrl)
.blobName("")
.pipeline(batchPipelineBuilder.build())
.buildAsyncClient();
this.batchOperationQueue = new ConcurrentLinkedDeque<>();
this.batchRequest = new ArrayList<>();
this.batchMapping = new ConcurrentHashMap<>();
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String containerName, String blobName,
DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(String.format(PATH_TEMPLATE, containerName, blobName),
deleteOptions, blobAccessConditions);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl) {
return deleteBlobHelper(getUrlPath(blobUrl), null, null);
}
/**
* Adds a delete blob operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob
*
* @param blobUrl URL of the blob.
* @param deleteOptions Delete options for the blob and its snapshots.
* @param blobAccessConditions Additional access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions);
}
private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions,
BlobAccessConditions blobAccessConditions) {
setBatchType(BlobBatchType.DELETE);
return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions),
urlPath, EXPECTED_DELETE_STATUS_CODES);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param containerName The container of the blob.
* @param blobName The name of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(String.format(PATH_TEMPLATE, containerName, blobName), accessTier,
leaseAccessConditions);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null);
}
/**
* Adds a set tier operation to the batch.
*
* <p><strong>Code sample</strong></p>
*
* {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier
*
* @param blobUrl URL of the blob.
* @param accessTier The tier to set on the blob.
* @param leaseAccessConditions Lease access conditions that must be met to allow this operation.
* @return a {@link Response} that will be used to associate this operation to the response when the batch is
* submitted.
* @throws UnsupportedOperationException If this batch has already added an operation of another type.
*/
public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions);
}
private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier,
LeaseAccessConditions leaseAccessConditions) {
setBatchType(BlobBatchType.SET_TIER);
return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions),
urlPath, EXPECTED_SET_TIER_STATUS_CODES);
}
private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath,
int... expectedStatusCodes) {
int id = contentId.getAndIncrement();
batchOperationQueue.add(response
.subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath)));
BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes);
batchMapping.put(id, batchOperationResponse);
return batchOperationResponse;
}
private String getUrlPath(String url) {
return UrlBuilder.parse(url).getPath();
}
private void setBatchType(BlobBatchType batchType) {
if (this.batchType == null) {
this.batchType = batchType;
} else if (this.batchType != batchType) {
throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT,
"'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType)));
}
}
Flux<ByteBuffer> getBody() {
if (batchOperationQueue.isEmpty()) {
throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed."));
}
Disposable disposable = Flux.fromStream(batchOperationQueue.stream())
.flatMap(batchOperation -> batchOperation)
.subscribe();
/* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from
* throwing an exception if this was ran in a Reactor thread.
*/
while (!disposable.isDisposed()) {
}
this.batchRequest.add(ByteBuffer.wrap(
String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8)));
return Flux.fromIterable(batchRequest);
}
long getContentLength() {
long contentLength = 0;
for (ByteBuffer request : batchRequest) {
contentLength += request.remaining();
}
return contentLength;
}
String getContentType() {
return contentType;
}
BlobBatchOperationResponse<?> getBatchRequest(int contentId) {
return batchMapping.get(contentId);
}
int getOperationCount() {
return batchMapping.size();
}
/*
* This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp.
* Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this
* and it adds the header "Content-Id" that allows the request to be mapped to the response.
*/
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
context.getHttpRequest().getHeaders().remove(X_MS_VERSION);
Map<String, String> headers = context.getHttpRequest().getHeaders().toMap();
headers.entrySet().removeIf(header -> header.getValue() == null);
context.getHttpRequest().setHeaders(new HttpHeaders(headers));
context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString());
return next.process();
}
/*
* This performs changing the request URL to the value passed through the pipeline context. This policy is used in
* place of constructing a new client for each batch request that is being sent.
*/
private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
try {
UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl());
requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString());
context.getHttpRequest().setUrl(requestUrl.toURL());
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex)));
}
return next.process();
}
/*
* This will "send" the batch operation request when triggered, it simply acts as a way to build and write the
* batch operation into the overall request and then returns nothing as the response.
*/
private void appendWithNewline(StringBuilder stringBuilder, String value) {
stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE);
}
} |
If they pass in null, just have that clear out the whitelist. | public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames;
return this;
} | this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames; | public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : allowedHeaderNames;
return this;
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>(Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
));
allowedQueryParamNames = new HashSet<>();
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* If a set of allowedHeaderNames is provided it will override the default set of header names to be whitelisted.
* Additionally, use {@link HttpLogOptions
* to add more headers names to the existing set of default allowed header names.
* <p>
* If a set of allowedHeaderNames is not provided, the default header names will be used to be whitelisted.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
private static final List<String> DEFAULT_HEADERS_WHITELIST = Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
);
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>();
allowedQueryParamNames = new HashSet<>(DEFAULT_HEADERS_WHITELIST);
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* This method sets the provided header names to be the whitelisted header names which will be logged for all http
* requests and responses, overwriting any previously configured headers, including the default set.
* Additionally, user can use {@link HttpLogOptions
* or {@link HttpLogOptions
* allowed header names.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} |
Should there be a convenience API to remove headers too? Because in most cases, users just want to redact one or two headers from the default set that may contain sensitive info. | public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames;
return this;
} | this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames; | public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : allowedHeaderNames;
return this;
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>(Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
));
allowedQueryParamNames = new HashSet<>();
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* If a set of allowedHeaderNames is provided it will override the default set of header names to be whitelisted.
* Additionally, use {@link HttpLogOptions
* to add more headers names to the existing set of default allowed header names.
* <p>
* If a set of allowedHeaderNames is not provided, the default header names will be used to be whitelisted.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
private static final List<String> DEFAULT_HEADERS_WHITELIST = Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
);
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>();
allowedQueryParamNames = new HashSet<>(DEFAULT_HEADERS_WHITELIST);
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* This method sets the provided header names to be the whitelisted header names which will be logged for all http
* requests and responses, overwriting any previously configured headers, including the default set.
* Additionally, user can use {@link HttpLogOptions
* or {@link HttpLogOptions
* allowed header names.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} |
On line 75 and 114: Should we return an immutable copy of the HashSet instead of returning the reference to the HashSet this class uses? If we return the reference, then user can add/delete to the original set outside of this class. | public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames;
return this;
} | this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames; | public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : allowedHeaderNames;
return this;
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>(Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
));
allowedQueryParamNames = new HashSet<>();
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* If a set of allowedHeaderNames is provided it will override the default set of header names to be whitelisted.
* Additionally, use {@link HttpLogOptions
* to add more headers names to the existing set of default allowed header names.
* <p>
* If a set of allowedHeaderNames is not provided, the default header names will be used to be whitelisted.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
private static final List<String> DEFAULT_HEADERS_WHITELIST = Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
);
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>();
allowedQueryParamNames = new HashSet<>(DEFAULT_HEADERS_WHITELIST);
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* This method sets the provided header names to be the whitelisted header names which will be logged for all http
* requests and responses, overwriting any previously configured headers, including the default set.
* Additionally, user can use {@link HttpLogOptions
* or {@link HttpLogOptions
* allowed header names.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} |
Extract the `Arrays.asList()` into a static field and reuse. Don't have to create a list and a hashset each time an instance of HttpLogOptions is created. | public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>(Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
));
allowedQueryParamNames = new HashSet<>();
} | allowedHeaderNames = new HashSet<>(Arrays.asList( | public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>();
allowedQueryParamNames = new HashSet<>(DEFAULT_HEADERS_WHITELIST);
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* If a set of allowedHeaderNames is provided it will override the default set of header names to be whitelisted.
* Additionally, use {@link HttpLogOptions
* to add more headers names to the existing set of default allowed header names.
* <p>
* If a set of allowedHeaderNames is not provided, the default header names will be used to be whitelisted.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames;
return this;
}
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
private static final List<String> DEFAULT_HEADERS_WHITELIST = Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
);
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* This method sets the provided header names to be the whitelisted header names which will be logged for all http
* requests and responses, overwriting any previously configured headers, including the default set.
* Additionally, user can use {@link HttpLogOptions
* or {@link HttpLogOptions
* allowed header names.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : allowedHeaderNames;
return this;
}
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} |
This can be done via `getAllowedHeaderNames().remove(..)`, so we don't need a convenience API. | public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames;
return this;
} | this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames; | public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : allowedHeaderNames;
return this;
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>(Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
));
allowedQueryParamNames = new HashSet<>();
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* If a set of allowedHeaderNames is provided it will override the default set of header names to be whitelisted.
* Additionally, use {@link HttpLogOptions
* to add more headers names to the existing set of default allowed header names.
* <p>
* If a set of allowedHeaderNames is not provided, the default header names will be used to be whitelisted.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
private static final List<String> DEFAULT_HEADERS_WHITELIST = Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
);
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>();
allowedQueryParamNames = new HashSet<>(DEFAULT_HEADERS_WHITELIST);
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* This method sets the provided header names to be the whitelisted header names which will be logged for all http
* requests and responses, overwriting any previously configured headers, including the default set.
* Additionally, user can use {@link HttpLogOptions
* or {@link HttpLogOptions
* allowed header names.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} |
I partially agree. The Arrays.asList(...) call can be a private static final field, but there should be a new set per instance, so that it can be modified via the API. | public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>(Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
));
allowedQueryParamNames = new HashSet<>();
} | allowedHeaderNames = new HashSet<>(Arrays.asList( | public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>();
allowedQueryParamNames = new HashSet<>(DEFAULT_HEADERS_WHITELIST);
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* If a set of allowedHeaderNames is provided it will override the default set of header names to be whitelisted.
* Additionally, use {@link HttpLogOptions
* to add more headers names to the existing set of default allowed header names.
* <p>
* If a set of allowedHeaderNames is not provided, the default header names will be used to be whitelisted.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames;
return this;
}
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
private static final List<String> DEFAULT_HEADERS_WHITELIST = Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
);
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* This method sets the provided header names to be the whitelisted header names which will be logged for all http
* requests and responses, overwriting any previously configured headers, including the default set.
* Additionally, user can use {@link HttpLogOptions
* or {@link HttpLogOptions
* allowed header names.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : allowedHeaderNames;
return this;
}
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} |
updated | public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>(Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
));
allowedQueryParamNames = new HashSet<>();
} | allowedHeaderNames = new HashSet<>(Arrays.asList( | public HttpLogOptions() {
logLevel = HttpLogDetailLevel.NONE;
allowedHeaderNames = new HashSet<>();
allowedQueryParamNames = new HashSet<>(DEFAULT_HEADERS_WHITELIST);
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* If a set of allowedHeaderNames is provided it will override the default set of header names to be whitelisted.
* Additionally, use {@link HttpLogOptions
* to add more headers names to the existing set of default allowed header names.
* <p>
* If a set of allowedHeaderNames is not provided, the default header names will be used to be whitelisted.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? this.allowedHeaderNames : allowedHeaderNames;
return this;
}
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private Set<String> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
private static final List<String> DEFAULT_HEADERS_WHITELIST = Arrays.asList(
"x-ms-client-request-id",
"x-ms-return-client-request-id",
"traceparent",
"Accept",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"ETag",
"Expires",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Unmodified-Since",
"Last-Modified",
"Pragma",
"Request-Id",
"Retry-After",
"Server",
"Transfer-Encoding",
"User-Agent"
);
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the whitelisted headers that should be logged.
*
* @return The list of whitelisted headers.
*/
public Set<String> getAllowedHeaderNames() {
return allowedHeaderNames;
}
/**
* Sets the given whitelisted headers that should be logged.
* <p>
* This method sets the provided header names to be the whitelisted header names which will be logged for all http
* requests and responses, overwriting any previously configured headers, including the default set.
* Additionally, user can use {@link HttpLogOptions
* or {@link HttpLogOptions
* allowed header names.
*
* @param allowedHeaderNames The list of whitelisted header names from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : allowedHeaderNames;
return this;
}
/**
* Sets the given whitelisted header to the default header set that should be logged.
*
* @param allowedHeaderName The whitelisted header name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the whitelisted query parameters.
*
* @return The list of whitelisted query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return allowedQueryParamNames;
}
/**
* Sets the given whitelisted query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of whitelisted query params from the user.
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames;
return this;
}
/**
* Sets the given whitelisted query param that should be logged.
*
* @param allowedQueryParamName The whitelisted query param name from the user.
* @return The updated HttpLogOptions object.
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
}
} |
Should this be changed based on the service version work that @samvaity has been doing (which is now in the repo)? | private void ensureState() {
if (version == null) {
version = Constants.HeaderConstants.TARGET_STORAGE_VERSION;
}
if (ImplUtils.isNullOrEmpty(blobName)) {
resource = SAS_CONTAINER_CONSTANT;
} else if (snapshotId != null) {
resource = SAS_BLOB_SNAPSHOT_CONSTANT;
} else {
resource = SAS_BLOB_CONSTANT;
}
if (permissions != null) {
switch (resource) {
case SAS_BLOB_CONSTANT:
case SAS_BLOB_SNAPSHOT_CONSTANT:
permissions = BlobSasPermission.parse(permissions).toString();
break;
case SAS_CONTAINER_CONSTANT:
permissions = BlobContainerSasPermission.parse(permissions).toString();
break;
default:
logger.info("Not re-parsing permissions. Resource type '{}' is unknown.", resource);
break;
}
}
} | version = Constants.HeaderConstants.TARGET_STORAGE_VERSION; | private void ensureState() {
if (version == null) {
version = BlobServiceVersion.getLatest().getVersion();
}
if (ImplUtils.isNullOrEmpty(blobName)) {
resource = SAS_CONTAINER_CONSTANT;
} else if (snapshotId != null) {
resource = SAS_BLOB_SNAPSHOT_CONSTANT;
} else {
resource = SAS_BLOB_CONSTANT;
}
if (permissions != null) {
switch (resource) {
case SAS_BLOB_CONSTANT:
case SAS_BLOB_SNAPSHOT_CONSTANT:
permissions = BlobSasPermission.parse(permissions).toString();
break;
case SAS_CONTAINER_CONSTANT:
permissions = BlobContainerSasPermission.parse(permissions).toString();
break;
default:
logger.info("Not re-parsing permissions. Resource type '{}' is unknown.", resource);
break;
}
}
} | class level JavaDocs for code snippets.
*
* @param delegationKey A {@link UserDelegationKey} | class level JavaDocs for code snippets.
*
* @param delegationKey A {@link UserDelegationKey} |
getKey().block().getKey() ? | private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
this.key = getKey().block().getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.info("Failed to retrieve key from key vault");
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
} | this.key = getKey().block().getKey(); | private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getKeyId())) {
unpackAndValidateId(key.getKeyId());
cryptographyServiceClient = new CryptographyServiceClient(key.getKeyId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getId())) {
unpackAndValidateId(key.getId());
cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} |
Should we log the exception here as well, since it can be either and it might help the user to actually know what happened. | private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
this.key = getKey().block().getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.info("Failed to retrieve key from key vault");
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
} | } catch (HttpResponseException | NullPointerException e) { | private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getKeyId())) {
unpackAndValidateId(key.getKeyId());
cryptographyServiceClient = new CryptographyServiceClient(key.getKeyId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getId())) {
unpackAndValidateId(key.getId());
cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} |
``` .setKeyType(createKeyOptions.getKeyType()) ``` | Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(endpoint, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
} | .setKty(createKeyOptions.getKeyType()) | new KeyRequestParameters().setKty(keyType);
return service.createKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Creating key - {} | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param endpoint URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL endpoint, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(endpoint,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.endpoint = endpoint.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Get the vault endpoint
* @return the vault endpoint
*/
public String getVaultEndpoint() {
return endpoint;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(endpoint, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions));
return service.createKey(endpoint, createRsaKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurve())
.setKeyOps(createEcKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions));
return service.createKey(endpoint, createEcKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions));
return service.importKey(endpoint, importKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get public part of the key which represents {@link KeyProperties keyProperties} from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p>The list operations {@link KeyAsyncClient
* return the {@link Flux} containing {@link KeyProperties key properties} as output excluding the key material of the key.
* This operation can then be used to get the full key with its key material from {@code keyProperties}.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param keyProperties The {@link KeyProperties key properties} holding attributes of the key being requested.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String vaultUrl;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(vaultUrl,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(vaultUrl, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions));
return service.createKey(vaultUrl, createRsaKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurveName())
.setKeyOps(createEcKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions));
return service.createKey(vaultUrl, createEcKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions));
return service.importKey(vaultUrl, importKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(vaultUrl, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) {
Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setTags(keyProperties.getTags())
.setKeyAttributes(new KeyRequestAttributes(keyProperties));
if (keyOperations.length > 0) {
parameters.setKeyOps(Arrays.asList(keyOperations));
}
return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName()))
.doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error));
}
/**
* Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed
* in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The
* delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version
* of a key. This operation removes the cryptographic material associated with the key, which means the key is not
* usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the
* {@code keys/delete} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey
*
* @param name The name of the key to be deleted.
* @return A {@link Poller} to poll on the {@link DeletedKey deleted key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Poller<DeletedKey, Void> beginDeleteKey(String name) {
return new Poller<>(Duration.ofSeconds(1), createPollOperation(name), () -> Mono.empty(), activationOperation(name), null);
}
private Supplier<Mono<DeletedKey>> activationOperation(String name) {
return () -> withContext(context -> deleteKeyWithResponse(name, context)
.flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollResponse<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) {
return prePollResponse ->
withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.flatMap(deletedKeyResponse -> {
if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.IN_PROGRESS, prePollResponse.getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue())));
}))
.onErrorReturn(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, prePollResponse.getValue()));
}
Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) {
return service.deleteKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Deleting key - {}", name))
.doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to delete key - {}", name, error));
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing the {@link DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedKey> getDeletedKey(String name) {
try {
return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) {
try {
return withContext(context -> getDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) {
return service.getDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey
*
* @param name The name of the deleted key.
* @return An empty {@link Mono}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedKey(String name) {
try {
return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a Response containing status code and HTTP headers.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) {
try {
return withContext(context -> purgeDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) {
return service.purgeDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Purging deleted key - {}", name))
.doOnSuccess(response -> logger.info("Purged deleted key - {}", name))
.doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error));
}
/**
* Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete
* enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the
* delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the recovered key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey
*
* @param name The name of the deleted key to be recovered.
* @return A {@link Poller} to poll on the {@link KeyVaultKey recovered key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Poller<KeyVaultKey, Void> beginRecoverDeletedKey(String name) {
return new Poller<>(Duration.ofSeconds(1), createRecoverPollOperation(name), () -> Mono.empty(), recoverActivationOperation(name), null);
}
private Supplier<Mono<KeyVaultKey>> recoverActivationOperation(String name) {
return () -> withContext(context -> recoverDeletedKeyWithResponse(name, context)
.flatMap(keyResponse -> Mono.just(keyResponse.getValue())));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollResponse<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) {
return prePollResponse ->
withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.flatMap(keyResponse -> {
if (keyResponse.getStatusCode() == 404) {
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.IN_PROGRESS, prePollResponse.getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue())));
}))
.onErrorReturn(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, prePollResponse.getValue()));
}
Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) {
return service.recoverDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name))
.doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error));
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the backed up key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<byte[]> backupKey(String name) {
try {
return backupKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse
*
* @param name The name of the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<byte[]>> backupKeyWithResponse(String name) {
try {
return withContext(context -> backupKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) {
return service.backupKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Backing up key - {}", name))
.doOnSuccess(response -> logger.info("Backed up key - {}", name))
.doOnError(error -> logger.warning("Failed to backup key - {}", name, error))
.flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(),
base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue())));
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) {
try {
return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) {
try {
return withContext(context -> restoreKeyBackupWithResponse(backup, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) {
KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup);
return service.restoreKey(vaultUrl, API_VERSION, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Attempting to restore key"))
.doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to restore key - {}", error));
}
/**
* List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain
* the public part of a stored key. The List operation is applicable to all key types and the individual key
* response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are
* provided in the response. The key material and individual key versions are not listed in the response. This
* operation requires the {@code keys/list} permission.
*
* <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing
* {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys}
*
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeysFirstPage(context)),
continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) {
return new PagedFlux<>(
() -> listKeysFirstPage(context),
continuationToken -> listKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) {
try {
return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing keys"))
.doOnSuccess(response -> logger.info("Listed keys"))
.doOnError(error -> logger.warning("Failed to list keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures
* that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled
* for soft-delete. This operation requires the {@code keys/list} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id
* of each deleted key when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys}
*
* @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DeletedKey> listDeletedKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listDeletedKeysFirstPage(context)),
continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DeletedKey> listDeletedKeys(Context context) {
return new PagedFlux<>(
() -> listDeletedKeysFirstPage(context),
continuationToken -> listDeletedKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* list operations.
* @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) {
try {
return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) {
try {
return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing deleted keys"))
.doOnSuccess(response -> logger.info("Listed deleted keys"))
.doOnError(error -> logger.warning("Failed to list deleted keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties}
* as only the key identifier, attributes and tags are provided in the response. The key material values are
* not provided in the response. This operation requires the {@code keys/list} permission.
*
* <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link
* Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions}
*
* @param name The name of the key.
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault.
* Flux is empty if key with {@code name} does not exist in key vault.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeyVersionsFirstPage(name, context)),
continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) {
return new PagedFlux<>(
() -> listKeyVersionsFirstPage(name, context),
continuationToken -> listKeyVersionsNextPage(continuationToken, context));
}
private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) {
try {
return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing key versions - {}", name))
.doOnSuccess(response -> logger.info("Listed key versions - {}", name))
.doOnError(error -> logger.warning(String.format("Failed to list key versions - {}", name), error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} |
``` .setKeyOperations(createKeyOptions.keyOperations()) ``` | Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(endpoint, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
} | .setKeyOps(createKeyOptions.keyOperations()) | new KeyRequestParameters().setKty(keyType);
return service.createKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Creating key - {} | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param endpoint URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL endpoint, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(endpoint,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.endpoint = endpoint.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Get the vault endpoint
* @return the vault endpoint
*/
public String getVaultEndpoint() {
return endpoint;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(endpoint, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions));
return service.createKey(endpoint, createRsaKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurve())
.setKeyOps(createEcKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions));
return service.createKey(endpoint, createEcKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions));
return service.importKey(endpoint, importKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get public part of the key which represents {@link KeyProperties keyProperties} from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p>The list operations {@link KeyAsyncClient
* return the {@link Flux} containing {@link KeyProperties key properties} as output excluding the key material of the key.
* This operation can then be used to get the full key with its key material from {@code keyProperties}.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param keyProperties The {@link KeyProperties key properties} holding attributes of the key being requested.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String vaultUrl;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(vaultUrl,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(vaultUrl, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions));
return service.createKey(vaultUrl, createRsaKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurveName())
.setKeyOps(createEcKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions));
return service.createKey(vaultUrl, createEcKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions));
return service.importKey(vaultUrl, importKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(vaultUrl, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) {
Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setTags(keyProperties.getTags())
.setKeyAttributes(new KeyRequestAttributes(keyProperties));
if (keyOperations.length > 0) {
parameters.setKeyOps(Arrays.asList(keyOperations));
}
return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName()))
.doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error));
}
/**
* Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed
* in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The
* delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version
* of a key. This operation removes the cryptographic material associated with the key, which means the key is not
* usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the
* {@code keys/delete} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey
*
* @param name The name of the key to be deleted.
* @return A {@link Poller} to poll on the {@link DeletedKey deleted key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Poller<DeletedKey, Void> beginDeleteKey(String name) {
return new Poller<>(Duration.ofSeconds(1), createPollOperation(name), () -> Mono.empty(), activationOperation(name), null);
}
private Supplier<Mono<DeletedKey>> activationOperation(String name) {
return () -> withContext(context -> deleteKeyWithResponse(name, context)
.flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollResponse<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) {
return prePollResponse ->
withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.flatMap(deletedKeyResponse -> {
if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.IN_PROGRESS, prePollResponse.getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue())));
}))
.onErrorReturn(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, prePollResponse.getValue()));
}
Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) {
return service.deleteKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Deleting key - {}", name))
.doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to delete key - {}", name, error));
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing the {@link DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedKey> getDeletedKey(String name) {
try {
return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) {
try {
return withContext(context -> getDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) {
return service.getDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey
*
* @param name The name of the deleted key.
* @return An empty {@link Mono}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedKey(String name) {
try {
return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a Response containing status code and HTTP headers.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) {
try {
return withContext(context -> purgeDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) {
return service.purgeDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Purging deleted key - {}", name))
.doOnSuccess(response -> logger.info("Purged deleted key - {}", name))
.doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error));
}
/**
* Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete
* enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the
* delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the recovered key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey
*
* @param name The name of the deleted key to be recovered.
* @return A {@link Poller} to poll on the {@link KeyVaultKey recovered key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Poller<KeyVaultKey, Void> beginRecoverDeletedKey(String name) {
return new Poller<>(Duration.ofSeconds(1), createRecoverPollOperation(name), () -> Mono.empty(), recoverActivationOperation(name), null);
}
private Supplier<Mono<KeyVaultKey>> recoverActivationOperation(String name) {
return () -> withContext(context -> recoverDeletedKeyWithResponse(name, context)
.flatMap(keyResponse -> Mono.just(keyResponse.getValue())));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollResponse<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) {
return prePollResponse ->
withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.flatMap(keyResponse -> {
if (keyResponse.getStatusCode() == 404) {
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.IN_PROGRESS, prePollResponse.getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue())));
}))
.onErrorReturn(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, prePollResponse.getValue()));
}
Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) {
return service.recoverDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name))
.doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error));
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the backed up key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<byte[]> backupKey(String name) {
try {
return backupKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse
*
* @param name The name of the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<byte[]>> backupKeyWithResponse(String name) {
try {
return withContext(context -> backupKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) {
return service.backupKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Backing up key - {}", name))
.doOnSuccess(response -> logger.info("Backed up key - {}", name))
.doOnError(error -> logger.warning("Failed to backup key - {}", name, error))
.flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(),
base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue())));
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) {
try {
return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) {
try {
return withContext(context -> restoreKeyBackupWithResponse(backup, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) {
KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup);
return service.restoreKey(vaultUrl, API_VERSION, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Attempting to restore key"))
.doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to restore key - {}", error));
}
/**
* List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain
* the public part of a stored key. The List operation is applicable to all key types and the individual key
* response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are
* provided in the response. The key material and individual key versions are not listed in the response. This
* operation requires the {@code keys/list} permission.
*
* <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing
* {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys}
*
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeysFirstPage(context)),
continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) {
return new PagedFlux<>(
() -> listKeysFirstPage(context),
continuationToken -> listKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) {
try {
return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing keys"))
.doOnSuccess(response -> logger.info("Listed keys"))
.doOnError(error -> logger.warning("Failed to list keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures
* that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled
* for soft-delete. This operation requires the {@code keys/list} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id
* of each deleted key when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys}
*
* @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DeletedKey> listDeletedKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listDeletedKeysFirstPage(context)),
continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DeletedKey> listDeletedKeys(Context context) {
return new PagedFlux<>(
() -> listDeletedKeysFirstPage(context),
continuationToken -> listDeletedKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* list operations.
* @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) {
try {
return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) {
try {
return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing deleted keys"))
.doOnSuccess(response -> logger.info("Listed deleted keys"))
.doOnError(error -> logger.warning("Failed to list deleted keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties}
* as only the key identifier, attributes and tags are provided in the response. The key material values are
* not provided in the response. This operation requires the {@code keys/list} permission.
*
* <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link
* Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions}
*
* @param name The name of the key.
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault.
* Flux is empty if key with {@code name} does not exist in key vault.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeyVersionsFirstPage(name, context)),
continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) {
return new PagedFlux<>(
() -> listKeyVersionsFirstPage(name, context),
continuationToken -> listKeyVersionsNextPage(continuationToken, context));
}
private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) {
try {
return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing key versions - {}", name))
.doOnSuccess(response -> logger.info("Listed key versions - {}", name))
.doOnError(error -> logger.warning(String.format("Failed to list key versions - {}", name), error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} |
internal class, mapping to swagger/REST API Best to keep it same as swagger/REST API | Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(endpoint, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
} | .setKty(createKeyOptions.getKeyType()) | new KeyRequestParameters().setKty(keyType);
return service.createKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Creating key - {} | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param endpoint URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL endpoint, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(endpoint,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.endpoint = endpoint.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Get the vault endpoint
* @return the vault endpoint
*/
public String getVaultEndpoint() {
return endpoint;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(endpoint, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions));
return service.createKey(endpoint, createRsaKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurve())
.setKeyOps(createEcKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions));
return service.createKey(endpoint, createEcKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions));
return service.importKey(endpoint, importKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get public part of the key which represents {@link KeyProperties keyProperties} from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p>The list operations {@link KeyAsyncClient
* return the {@link Flux} containing {@link KeyProperties key properties} as output excluding the key material of the key.
* This operation can then be used to get the full key with its key material from {@code keyProperties}.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param keyProperties The {@link KeyProperties key properties} holding attributes of the key being requested.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String vaultUrl;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(vaultUrl,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(vaultUrl, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions));
return service.createKey(vaultUrl, createRsaKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurveName())
.setKeyOps(createEcKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions));
return service.createKey(vaultUrl, createEcKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions));
return service.importKey(vaultUrl, importKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(vaultUrl, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) {
Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setTags(keyProperties.getTags())
.setKeyAttributes(new KeyRequestAttributes(keyProperties));
if (keyOperations.length > 0) {
parameters.setKeyOps(Arrays.asList(keyOperations));
}
return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName()))
.doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error));
}
/**
* Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed
* in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The
* delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version
* of a key. This operation removes the cryptographic material associated with the key, which means the key is not
* usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the
* {@code keys/delete} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey
*
* @param name The name of the key to be deleted.
* @return A {@link Poller} to poll on the {@link DeletedKey deleted key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Poller<DeletedKey, Void> beginDeleteKey(String name) {
return new Poller<>(Duration.ofSeconds(1), createPollOperation(name), () -> Mono.empty(), activationOperation(name), null);
}
private Supplier<Mono<DeletedKey>> activationOperation(String name) {
return () -> withContext(context -> deleteKeyWithResponse(name, context)
.flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollResponse<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) {
return prePollResponse ->
withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.flatMap(deletedKeyResponse -> {
if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.IN_PROGRESS, prePollResponse.getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue())));
}))
.onErrorReturn(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, prePollResponse.getValue()));
}
Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) {
return service.deleteKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Deleting key - {}", name))
.doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to delete key - {}", name, error));
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing the {@link DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedKey> getDeletedKey(String name) {
try {
return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) {
try {
return withContext(context -> getDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) {
return service.getDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey
*
* @param name The name of the deleted key.
* @return An empty {@link Mono}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedKey(String name) {
try {
return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a Response containing status code and HTTP headers.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) {
try {
return withContext(context -> purgeDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) {
return service.purgeDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Purging deleted key - {}", name))
.doOnSuccess(response -> logger.info("Purged deleted key - {}", name))
.doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error));
}
/**
* Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete
* enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the
* delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the recovered key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey
*
* @param name The name of the deleted key to be recovered.
* @return A {@link Poller} to poll on the {@link KeyVaultKey recovered key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Poller<KeyVaultKey, Void> beginRecoverDeletedKey(String name) {
return new Poller<>(Duration.ofSeconds(1), createRecoverPollOperation(name), () -> Mono.empty(), recoverActivationOperation(name), null);
}
private Supplier<Mono<KeyVaultKey>> recoverActivationOperation(String name) {
return () -> withContext(context -> recoverDeletedKeyWithResponse(name, context)
.flatMap(keyResponse -> Mono.just(keyResponse.getValue())));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollResponse<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) {
return prePollResponse ->
withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.flatMap(keyResponse -> {
if (keyResponse.getStatusCode() == 404) {
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.IN_PROGRESS, prePollResponse.getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue())));
}))
.onErrorReturn(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, prePollResponse.getValue()));
}
Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) {
return service.recoverDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name))
.doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error));
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the backed up key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<byte[]> backupKey(String name) {
try {
return backupKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse
*
* @param name The name of the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<byte[]>> backupKeyWithResponse(String name) {
try {
return withContext(context -> backupKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) {
return service.backupKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Backing up key - {}", name))
.doOnSuccess(response -> logger.info("Backed up key - {}", name))
.doOnError(error -> logger.warning("Failed to backup key - {}", name, error))
.flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(),
base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue())));
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) {
try {
return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) {
try {
return withContext(context -> restoreKeyBackupWithResponse(backup, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) {
KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup);
return service.restoreKey(vaultUrl, API_VERSION, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Attempting to restore key"))
.doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to restore key - {}", error));
}
/**
* List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain
* the public part of a stored key. The List operation is applicable to all key types and the individual key
* response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are
* provided in the response. The key material and individual key versions are not listed in the response. This
* operation requires the {@code keys/list} permission.
*
* <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing
* {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys}
*
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeysFirstPage(context)),
continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) {
return new PagedFlux<>(
() -> listKeysFirstPage(context),
continuationToken -> listKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) {
try {
return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing keys"))
.doOnSuccess(response -> logger.info("Listed keys"))
.doOnError(error -> logger.warning("Failed to list keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures
* that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled
* for soft-delete. This operation requires the {@code keys/list} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id
* of each deleted key when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys}
*
* @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DeletedKey> listDeletedKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listDeletedKeysFirstPage(context)),
continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DeletedKey> listDeletedKeys(Context context) {
return new PagedFlux<>(
() -> listDeletedKeysFirstPage(context),
continuationToken -> listDeletedKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* list operations.
* @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) {
try {
return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) {
try {
return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing deleted keys"))
.doOnSuccess(response -> logger.info("Listed deleted keys"))
.doOnError(error -> logger.warning("Failed to list deleted keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties}
* as only the key identifier, attributes and tags are provided in the response. The key material values are
* not provided in the response. This operation requires the {@code keys/list} permission.
*
* <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link
* Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions}
*
* @param name The name of the key.
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault.
* Flux is empty if key with {@code name} does not exist in key vault.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeyVersionsFirstPage(name, context)),
continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) {
return new PagedFlux<>(
() -> listKeyVersionsFirstPage(name, context),
continuationToken -> listKeyVersionsNextPage(continuationToken, context));
}
private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) {
try {
return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing key versions - {}", name))
.doOnSuccess(response -> logger.info("Listed key versions - {}", name))
.doOnError(error -> logger.warning(String.format("Failed to list key versions - {}", name), error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} |
`UnsupportedOperationException` should be wrapped with `logger.logAsError()` | Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
} | + "key with id %s", key.getKeyId()))); | Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getKeyId())) {
unpackAndValidateId(key.getKeyId());
cryptographyServiceClient = new CryptographyServiceClient(key.getKeyId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
this.key = getKey().block().getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.info("Failed to retrieve key from key vault");
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getId())) {
unpackAndValidateId(key.getId());
cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} |
done | Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
} | + "key with id %s", key.getKeyId()))); | Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getKeyId())) {
unpackAndValidateId(key.getKeyId());
cryptographyServiceClient = new CryptographyServiceClient(key.getKeyId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
this.key = getKey().block().getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.info("Failed to retrieve key from key vault");
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getId())) {
unpackAndValidateId(key.getId());
cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} |
internal class, mapping to swagger/REST API Best to keep it same as swagger/REST API | Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(endpoint, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
} | .setKeyOps(createKeyOptions.keyOperations()) | new KeyRequestParameters().setKty(keyType);
return service.createKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Creating key - {} | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String endpoint;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param endpoint URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL endpoint, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(endpoint,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.endpoint = endpoint.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Get the vault endpoint
* @return the vault endpoint
*/
public String getVaultEndpoint() {
return endpoint;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(endpoint, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions));
return service.createKey(endpoint, createRsaKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurve())
.setKeyOps(createEcKeyOptions.keyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions));
return service.createKey(endpoint, createEcKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions));
return service.importKey(endpoint, importKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Get public part of the key which represents {@link KeyProperties keyProperties} from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p>The list operations {@link KeyAsyncClient
* return the {@link Flux} containing {@link KeyProperties key properties} as output excluding the key material of the key.
* This operation can then be used to get the full key with its key material from {@code keyProperties}.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param keyProperties The {@link KeyProperties key properties} holding attributes of the key being requested.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties | class KeyAsyncClient {
static final String API_VERSION = "7.0";
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private final String vaultUrl;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(vaultUrl,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include: {@link KeyType
* EC}, {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* {@link KeyType
* and {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions));
return service.createKey(vaultUrl, createKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions));
return service.createKey(vaultUrl, createRsaKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurveName())
.setKeyOps(createEcKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions));
return service.createKey(vaultUrl, createEcKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* keyAsyncClient.importKey("keyName", jsonWebKeyToImport).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(), keyResponse.value
* ().getId()));
* </pre>
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Importing key - {}", name))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* <pre>
* KeyImportOptions keyImportOptions = new KeyImportOptions("keyName", jsonWebKeyToImport)
* .hsm(true)
* .setExpires(OffsetDateTime.now().plusDays(60));
*
* keyAsyncClient.importKey(keyImportOptions).subscribe(keyResponse ->
* System.out.printf("Key is imported with name %s and id %s \n", keyResponse.value().getName(),
* keyResponse.value().getId()));
* </pre>
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions));
return service.importKey(vaultUrl, importKeyOptions.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.info("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} and {@code version} doesn't exist in the key
* vault.
* @throws HttpRequestException if {@code name} or {@code version} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
return service.getKey(vaultUrl, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpRequestException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) {
Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null.");
KeyRequestParameters parameters = new KeyRequestParameters()
.setTags(keyProperties.getTags())
.setKeyAttributes(new KeyRequestAttributes(keyProperties));
if (keyOperations.length > 0) {
parameters.setKeyOps(Arrays.asList(keyOperations));
}
return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), API_VERSION, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName()))
.doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error));
}
/**
* Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed
* in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The
* delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version
* of a key. This operation removes the cryptographic material associated with the key, which means the key is not
* usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the
* {@code keys/delete} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey
*
* @param name The name of the key to be deleted.
* @return A {@link Poller} to poll on the {@link DeletedKey deleted key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Poller<DeletedKey, Void> beginDeleteKey(String name) {
return new Poller<>(Duration.ofSeconds(1), createPollOperation(name), () -> Mono.empty(), activationOperation(name), null);
}
private Supplier<Mono<DeletedKey>> activationOperation(String name) {
return () -> withContext(context -> deleteKeyWithResponse(name, context)
.flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue())));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollResponse<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) {
return prePollResponse ->
withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.flatMap(deletedKeyResponse -> {
if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.IN_PROGRESS, prePollResponse.getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue())));
}))
.onErrorReturn(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, prePollResponse.getValue()));
}
Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) {
return service.deleteKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Deleting key - {}", name))
.doOnSuccess(response -> logger.info("Deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to delete key - {}", name, error));
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing the {@link DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedKey> getDeletedKey(String name) {
try {
return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) {
try {
return withContext(context -> getDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) {
return service.getDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name))
.doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey
*
* @param name The name of the deleted key.
* @return An empty {@link Mono}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedKey(String name) {
try {
return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a Response containing status code and HTTP headers.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) {
try {
return withContext(context -> purgeDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) {
return service.purgeDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Purging deleted key - {}", name))
.doOnSuccess(response -> logger.info("Purged deleted key - {}", name))
.doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error));
}
/**
* Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete
* enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the
* delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the recovered key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey
*
* @param name The name of the deleted key to be recovered.
* @return A {@link Poller} to poll on the {@link KeyVaultKey recovered key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Poller<KeyVaultKey, Void> beginRecoverDeletedKey(String name) {
return new Poller<>(Duration.ofSeconds(1), createRecoverPollOperation(name), () -> Mono.empty(), recoverActivationOperation(name), null);
}
private Supplier<Mono<KeyVaultKey>> recoverActivationOperation(String name) {
return () -> withContext(context -> recoverDeletedKeyWithResponse(name, context)
.flatMap(keyResponse -> Mono.just(keyResponse.getValue())));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollResponse<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) {
return prePollResponse ->
withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.flatMap(keyResponse -> {
if (keyResponse.getStatusCode() == 404) {
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.IN_PROGRESS, prePollResponse.getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, keyResponse.getValue())));
}))
.onErrorReturn(new PollResponse<>(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED, prePollResponse.getValue()));
}
Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) {
return service.recoverDeletedKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name))
.doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error));
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the backed up key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<byte[]> backupKey(String name) {
try {
return backupKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse
*
* @param name The name of the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<byte[]>> backupKeyWithResponse(String name) {
try {
return withContext(context -> backupKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) {
return service.backupKey(vaultUrl, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Backing up key - {}", name))
.doOnSuccess(response -> logger.info("Backed up key - {}", name))
.doOnError(error -> logger.warning("Failed to backup key - {}", name, error))
.flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(),
base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue())));
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) {
try {
return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) {
try {
return withContext(context -> restoreKeyBackupWithResponse(backup, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) {
KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup);
return service.restoreKey(vaultUrl, API_VERSION, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context)
.doOnRequest(ignored -> logger.info("Attempting to restore key"))
.doOnSuccess(response -> logger.info("Restored Key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to restore key - {}", error));
}
/**
* List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain
* the public part of a stored key. The List operation is applicable to all key types and the individual key
* response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are
* provided in the response. The key material and individual key versions are not listed in the response. This
* operation requires the {@code keys/list} permission.
*
* <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing
* {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys}
*
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeysFirstPage(context)),
continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) {
return new PagedFlux<>(
() -> listKeysFirstPage(context),
continuationToken -> listKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) {
try {
return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing keys"))
.doOnSuccess(response -> logger.info("Listed keys"))
.doOnError(error -> logger.warning("Failed to list keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures
* that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled
* for soft-delete. This operation requires the {@code keys/list} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id
* of each deleted key when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys}
*
* @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DeletedKey> listDeletedKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listDeletedKeysFirstPage(context)),
continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DeletedKey> listDeletedKeys(Context context) {
return new PagedFlux<>(
() -> listDeletedKeysFirstPage(context),
continuationToken -> listDeletedKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* list operations.
* @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) {
try {
return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) {
try {
return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing deleted keys"))
.doOnSuccess(response -> logger.info("Listed deleted keys"))
.doOnError(error -> logger.warning("Failed to list deleted keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties}
* as only the key identifier, attributes and tags are provided in the response. The key material values are
* not provided in the response. This operation requires the {@code keys/list} permission.
*
* <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link
* Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions}
*
* @param name The name of the key.
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault.
* Flux is empty if key with {@code name} does not exist in key vault.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpRequestException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeyVersionsFirstPage(name, context)),
continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) {
return new PagedFlux<>(
() -> listKeyVersionsFirstPage(name, context),
continuationToken -> listKeyVersionsNextPage(continuationToken, context));
}
private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) {
try {
return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing key versions - {}", name))
.doOnSuccess(response -> logger.info("Listed key versions - {}", name))
.doOnError(error -> logger.warning(String.format("Failed to list key versions - {}", name), error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} |
added the log for exception. | private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
this.key = getKey().block().getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.info("Failed to retrieve key from key vault");
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
} | } catch (HttpResponseException | NullPointerException e) { | private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getKeyId())) {
unpackAndValidateId(key.getKeyId());
cryptographyServiceClient = new CryptographyServiceClient(key.getKeyId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getId())) {
unpackAndValidateId(key.getId());
cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} |
this is internal. first getKey is the KeyVaultKey, refactored the code to make it look readable. | private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
this.key = getKey().block().getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.info("Failed to retrieve key from key vault");
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
} | this.key = getKey().block().getKey(); | private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getKeyId())) {
unpackAndValidateId(key.getKeyId());
cryptographyServiceClient = new CryptographyServiceClient(key.getKeyId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getKeyId())));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getKeyId())));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getId())) {
unpackAndValidateId(key.getId());
cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} |
General feedback (don't worry about doing it): This code block would look nicer as a switch statement | private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
} | "The Json Web Key Type: %s is not supported.", key.getKeyType().toString()))); | private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getKeyId())) {
unpackAndValidateId(key.getKeyId());
cryptographyServiceClient = new CryptographyServiceClient(key.getKeyId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getKeyId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getKeyId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getKeyId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getKeyId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getKeyId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getKeyId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getKeyId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getKeyId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getId())) {
unpackAndValidateId(key.getId());
cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} |
Why only commented out instead of just removed? | public void deleteKey() {
} | public void deleteKey() {
deleteKeyRunner((keyToDelete) -> {
StepVerifier.create(client.createKey(keyToDelete))
.assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete();
Poller<DeletedKey, Void> poller = client.beginDeleteKey(keyToDelete.getName());
poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
DeletedKey deletedKeyResponse = poller.getLastPollResponse().getValue();
assertNotNull(deletedKeyResponse.getDeletedOn());
assertNotNull(deletedKeyResponse.getRecoveryId());
assertNotNull(deletedKeyResponse.getScheduledPurgeDate());
assertEquals(keyToDelete.getName(), deletedKeyResponse.getName());
StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToDelete.getName()))
.assertNext(voidResponse -> {
assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode());
}).verifyComplete();
sleepInRecordMode(15000);
});
} | class KeyAsyncClientTest extends KeyClientTestBase {
private KeyAsyncClient client;
@Override
protected void beforeTest() {
beforeTestSetup();
if (interceptorManager.isPlaybackMode()) {
client = clientSetup(pipeline -> new KeyClientBuilder()
.vaultEndpoint(getEndpoint())
.pipeline(pipeline)
.buildAsyncClient());
} else {
client = clientSetup(pipeline -> new KeyClientBuilder()
.pipeline(pipeline)
.vaultEndpoint(getEndpoint())
.buildAsyncClient());
}
}
/**
* Tests that a key can be created in the key vault.
*/
public void setKey() {
setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected))
.assertNext(response -> assertKeyEquals(expected, response))
.verifyComplete());
}
/**
* Tests that we cannot create a key when the key is an empty string.
*/
public void setKeyEmptyName() {
StepVerifier.create(client.createKey("", KeyType.RSA))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST));
}
/**
* Tests that we can create keys when value is not null or an empty string.
*/
public void setKeyNullType() {
setKeyEmptyValueRunner((key) -> {
StepVerifier.create(client.createKey(key))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST));
});
}
/**
* Verifies that an exception is thrown when null key object is passed for creation.
*/
public void setKeyNull() {
StepVerifier.create(client.createKey(null))
.verifyError(NullPointerException.class);
}
/**
* Tests that a key is able to be updated when it exists.
*/
public void updateKey() {
updateKeyRunner((original, updated) -> {
StepVerifier.create(client.createKey(original))
.assertNext(response -> assertKeyEquals(original, response))
.verifyComplete();
KeyVaultKey keyToUpdate = client.getKey(original.getName()).block();
StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn())))
.assertNext(response -> {
assertNotNull(response);
assertEquals(original.getName(), response.getName());
}).verifyComplete();
StepVerifier.create(client.getKey(original.getName()))
.assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse))
.verifyComplete();
});
}
/**
* Tests that a key is not able to be updated when it is disabled. 403 error is expected.
*/
public void updateDisabledKey() {
updateDisabledKeyRunner((original, updated) -> {
StepVerifier.create(client.createKey(original))
.assertNext(response -> assertKeyEquals(original, response))
.verifyComplete();
KeyVaultKey keyToUpdate = client.getKey(original.getName()).block();
StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn())))
.assertNext(response -> {
assertNotNull(response);
assertEquals(original.getName(), response.getName());
}).verifyComplete();
StepVerifier.create(client.getKey(original.getName()))
.assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse))
.verifyComplete();
});
}
/**
* Tests that an existing key can be retrieved.
*/
public void getKey() {
getKeyRunner((original) -> {
client.createKey(original);
StepVerifier.create(client.getKey(original.getName()))
.assertNext(response -> assertKeyEquals(original, response))
.verifyComplete();
});
}
/**
* Tests that a specific version of the key can be retrieved.
*/
public void getKeySpecificVersion() {
getKeySpecificVersionRunner((key, keyWithNewVal) -> {
final KeyVaultKey keyVersionOne = client.createKey(key).block();
final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block();
StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion()))
.assertNext(response -> assertKeyEquals(key, response))
.verifyComplete();
StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion()))
.assertNext(response -> assertKeyEquals(keyWithNewVal, response))
.verifyComplete();
});
}
/**
* Tests that an attempt to get a non-existing key throws an error.
*/
public void getKeyNotFound() {
StepVerifier.create(client.getKey("non-existing"))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that an existing key can be deleted.
*/
public void deleteKeyNotFound() {
}
/**
* Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault.
*/
public void getDeletedKeyNotFound() {
StepVerifier.create(client.getDeletedKey("non-existing"))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that a deleted key can be recovered on a soft-delete enabled vault.
*/
public void recoverDeletedKey() {
}
/**
* Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault.
*/
public void recoverDeletedKeyNotFound() {
}
/**
* Tests that a key can be backed up in the key vault.
*/
public void backupKey() {
backupKeyRunner((keyToBackup) -> {
StepVerifier.create(client.createKey(keyToBackup))
.assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete();
StepVerifier.create(client.backupKey(keyToBackup.getName()))
.assertNext(response -> {
assertNotNull(response);
assertTrue(response.length > 0);
}).verifyComplete();
});
}
/**
* Tests that an attempt to backup a non existing key throws an error.
*/
public void backupKeyNotFound() {
StepVerifier.create(client.backupKey("non-existing"))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that a key can be backed up in the key vault.
*/
public void restoreKey() {
}
/**
* Tests that an attempt to restore a key from malformed backup bytes throws an error.
*/
public void restoreKeyFromMalformedBackup() {
byte[] keyBackupBytes = "non-existing".getBytes();
StepVerifier.create(client.restoreKeyBackup(keyBackupBytes))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST));
}
/**
* Tests that a deleted key can be retrieved on a soft-delete enabled vault.
*/
public void getDeletedKey() {
}
/**
* Tests that deleted keys can be listed in the key vault.
*/
@Override
public void listDeletedKeys() {
}
/**
* Tests that key versions can be listed in the key vault.
*/
@Override
public void listKeyVersions() {
}
/**
* Tests that keys can be listed in the key vault.
*/
public void listKeys() {
listKeysRunner((keys) -> {
List<KeyProperties> output = new ArrayList<>();
for (CreateKeyOptions key : keys.values()) {
client.createKey(key).subscribe(keyResponse -> assertKeyEquals(key, keyResponse));
sleepInRecordMode(1000);
}
sleepInRecordMode(30000);
client.listPropertiesOfKeys().subscribe(output::add);
sleepInRecordMode(30000);
for (KeyProperties actualKey : output) {
if (keys.containsKey(actualKey.getName())) {
CreateKeyOptions expectedKey = keys.get(actualKey.getName());
assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn());
assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore());
keys.remove(actualKey.getName());
}
}
assertEquals(0, keys.size());
});
}
private void pollOnKeyDeletion(String keyName) {
int pendingPollCount = 0;
while (pendingPollCount < 30) {
DeletedKey deletedKey = null;
try {
deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue();
} catch (ResourceNotFoundException e) {
}
if (deletedKey == null) {
sleepInRecordMode(2000);
pendingPollCount += 1;
} else {
return;
}
}
System.err.printf("Deleted Key %s not found \n", keyName);
}
private void pollOnKeyPurge(String keyName) {
int pendingPollCount = 0;
while (pendingPollCount < 10) {
DeletedKey deletedKey = null;
try {
deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue();
} catch (ResourceNotFoundException e) {
}
if (deletedKey != null) {
sleepInRecordMode(2000);
pendingPollCount += 1;
} else {
return;
}
}
System.err.printf("Deleted Key %s was not purged \n", keyName);
}
} | class KeyAsyncClientTest extends KeyClientTestBase {
private KeyAsyncClient client;
@Override
protected void beforeTest() {
beforeTestSetup();
if (interceptorManager.isPlaybackMode()) {
client = clientSetup(pipeline -> new KeyClientBuilder()
.vaultUrl(getEndpoint())
.pipeline(pipeline)
.buildAsyncClient());
} else {
client = clientSetup(pipeline -> new KeyClientBuilder()
.pipeline(pipeline)
.vaultUrl(getEndpoint())
.buildAsyncClient());
}
}
/**
* Tests that a key can be created in the key vault.
*/
public void setKey() {
setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected))
.assertNext(response -> assertKeyEquals(expected, response))
.verifyComplete());
}
/**
* Tests that we cannot create a key when the key is an empty string.
*/
public void setKeyEmptyName() {
StepVerifier.create(client.createKey("", KeyType.RSA))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST));
}
/**
* Tests that we can create keys when value is not null or an empty string.
*/
public void setKeyNullType() {
setKeyEmptyValueRunner((key) -> {
StepVerifier.create(client.createKey(key))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST));
});
}
/**
* Verifies that an exception is thrown when null key object is passed for creation.
*/
public void setKeyNull() {
StepVerifier.create(client.createKey(null))
.verifyError(NullPointerException.class);
}
/**
* Tests that a key is able to be updated when it exists.
*/
public void updateKey() {
updateKeyRunner((original, updated) -> {
StepVerifier.create(client.createKey(original))
.assertNext(response -> assertKeyEquals(original, response))
.verifyComplete();
KeyVaultKey keyToUpdate = client.getKey(original.getName()).block();
StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn())))
.assertNext(response -> {
assertNotNull(response);
assertEquals(original.getName(), response.getName());
}).verifyComplete();
StepVerifier.create(client.getKey(original.getName()))
.assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse))
.verifyComplete();
});
}
/**
* Tests that a key is not able to be updated when it is disabled. 403 error is expected.
*/
public void updateDisabledKey() {
updateDisabledKeyRunner((original, updated) -> {
StepVerifier.create(client.createKey(original))
.assertNext(response -> assertKeyEquals(original, response))
.verifyComplete();
KeyVaultKey keyToUpdate = client.getKey(original.getName()).block();
StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn())))
.assertNext(response -> {
assertNotNull(response);
assertEquals(original.getName(), response.getName());
}).verifyComplete();
StepVerifier.create(client.getKey(original.getName()))
.assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse))
.verifyComplete();
});
}
/**
* Tests that an existing key can be retrieved.
*/
public void getKey() {
getKeyRunner((original) -> {
client.createKey(original);
StepVerifier.create(client.getKey(original.getName()))
.assertNext(response -> assertKeyEquals(original, response))
.verifyComplete();
});
}
/**
* Tests that a specific version of the key can be retrieved.
*/
public void getKeySpecificVersion() {
getKeySpecificVersionRunner((key, keyWithNewVal) -> {
final KeyVaultKey keyVersionOne = client.createKey(key).block();
final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block();
StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion()))
.assertNext(response -> assertKeyEquals(key, response))
.verifyComplete();
StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion()))
.assertNext(response -> assertKeyEquals(keyWithNewVal, response))
.verifyComplete();
});
}
/**
* Tests that an attempt to get a non-existing key throws an error.
*/
public void getKeyNotFound() {
StepVerifier.create(client.getKey("non-existing"))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that an existing key can be deleted.
*/
public void deleteKeyNotFound() {
Poller<DeletedKey, Void> deletedKeyPoller = client.beginDeleteKey("non-existing");
while (!deletedKeyPoller.isComplete()) { sleepInRecordMode(1000); }
assertEquals(deletedKeyPoller.getLastPollResponse().getStatus(), PollResponse.OperationStatus.FAILED);
}
/**
* Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault.
*/
public void getDeletedKeyNotFound() {
StepVerifier.create(client.getDeletedKey("non-existing"))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that a deleted key can be recovered on a soft-delete enabled vault.
*/
public void recoverDeletedKey() {
recoverDeletedKeyRunner((keyToDeleteAndRecover) -> {
StepVerifier.create(client.createKey(keyToDeleteAndRecover))
.assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete();
Poller<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName());
poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
assertNotNull(poller.getLastPollResponse().getValue());
Poller<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName());
recoverPoller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
KeyVaultKey keyResponse = recoverPoller.getLastPollResponse().getValue();
assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName());
assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore());
assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn());
});
}
/**
* Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault.
*/
public void recoverDeletedKeyNotFound() {
Poller<KeyVaultKey, Void> poller = client.beginRecoverDeletedKey("non-existing");
while (!poller.isComplete()) { sleepInRecordMode(1000); }
assertEquals(poller.getStatus(), PollResponse.OperationStatus.FAILED);
}
/**
* Tests that a key can be backed up in the key vault.
*/
public void backupKey() {
Poller<KeyVaultKey, Void> poller = client.beginRecoverDeletedKey("non-existing");
while (!poller.isComplete()) { sleepInRecordMode(1000); }
assertEquals(poller.getStatus(), PollResponse.OperationStatus.FAILED);
}
/**
* Tests that an attempt to backup a non existing key throws an error.
*/
public void backupKeyNotFound() {
StepVerifier.create(client.backupKey("non-existing"))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that a key can be backed up in the key vault.
*/
public void restoreKey() {
restoreKeyRunner((keyToBackupAndRestore) -> {
StepVerifier.create(client.createKey(keyToBackupAndRestore))
.assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)).verifyComplete();
byte[] backup = client.backupKey(keyToBackupAndRestore.getName()).block();
Poller<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName());
poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
assertNotNull(poller.getLastPollResponse().getValue());
StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName()))
.assertNext(voidResponse -> {
assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode());
}).verifyComplete();
pollOnKeyPurge(keyToBackupAndRestore.getName());
sleepInRecordMode(60000);
StepVerifier.create(client.restoreKeyBackup(backup))
.assertNext(response -> {
assertEquals(keyToBackupAndRestore.getName(), response.getName());
assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore());
assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn());
}).verifyComplete();
});
}
/**
* Tests that an attempt to restore a key from malformed backup bytes throws an error.
*/
public void restoreKeyFromMalformedBackup() {
byte[] keyBackupBytes = "non-existing".getBytes();
StepVerifier.create(client.restoreKeyBackup(keyBackupBytes))
.verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST));
}
/**
* Tests that a deleted key can be retrieved on a soft-delete enabled vault.
*/
public void getDeletedKey() {
getDeletedKeyRunner((keyToDeleteAndGet) -> {
StepVerifier.create(client.createKey(keyToDeleteAndGet))
.assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)).verifyComplete();
Poller<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName());
poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
assertNotNull(poller.getLastPollResponse().getValue());
StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.getName()))
.assertNext(deletedKeyResponse -> {
assertNotNull(deletedKeyResponse.getDeletedOn());
assertNotNull(deletedKeyResponse.getRecoveryId());
assertNotNull(deletedKeyResponse.getScheduledPurgeDate());
assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName());
}).verifyComplete();
StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToDeleteAndGet.getName()))
.assertNext(voidResponse -> {
assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode());
}).verifyComplete();
pollOnKeyPurge(keyToDeleteAndGet.getName());
sleepInRecordMode(15000);
});
}
/**
* Tests that deleted keys can be listed in the key vault.
*/
@Override
public void listDeletedKeys() {
listDeletedKeysRunner((keys) -> {
List<DeletedKey> deletedKeys = new ArrayList<>();
for (CreateKeyOptions key : keys.values()) {
StepVerifier.create(client.createKey(key))
.assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete();
}
sleepInRecordMode(10000);
for (CreateKeyOptions key : keys.values()) {
Poller<DeletedKey, Void> poller = client.beginDeleteKey(key.getName());
poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
assertNotNull(poller.getLastPollResponse().getValue());
}
sleepInRecordMode(60000);
client.listDeletedKeys().subscribe(deletedKeys::add);
sleepInRecordMode(30000);
for (DeletedKey actualKey : deletedKeys) {
if (keys.containsKey(actualKey.getName())) {
assertNotNull(actualKey.getDeletedOn());
assertNotNull(actualKey.getRecoveryId());
keys.remove(actualKey.getName());
}
}
assertEquals(0, keys.size());
for (DeletedKey deletedKey : deletedKeys) {
StepVerifier.create(client.purgeDeletedKeyWithResponse(deletedKey.getName()))
.assertNext(voidResponse -> {
assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode());
}).verifyComplete();
pollOnKeyPurge(deletedKey.getName());
}
});
}
/**
* Tests that key versions can be listed in the key vault.
*/
@Override
public void listKeyVersions() {
listKeyVersionsRunner((keys) -> {
List<KeyProperties> output = new ArrayList<>();
String keyName = null;
for (CreateKeyOptions key : keys) {
keyName = key.getName();
client.createKey(key).subscribe(keyResponse -> assertKeyEquals(key, keyResponse));
sleepInRecordMode(1000);
}
sleepInRecordMode(30000);
client.listPropertiesOfKeyVersions(keyName).subscribe(output::add);
sleepInRecordMode(30000);
assertEquals(keys.size(), output.size());
Poller<DeletedKey, Void> poller = client.beginDeleteKey(keyName);
poller.blockUntil(PollResponse.OperationStatus.SUCCESSFULLY_COMPLETED);
assertNotNull(poller.getLastPollResponse().getValue());
StepVerifier.create(client.purgeDeletedKeyWithResponse(keyName))
.assertNext(voidResponse -> {
assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode());
}).verifyComplete();
pollOnKeyPurge(keyName);
});
}
/**
* Tests that keys can be listed in the key vault.
*/
public void listKeys() {
listKeysRunner((keys) -> {
List<KeyProperties> output = new ArrayList<>();
for (CreateKeyOptions key : keys.values()) {
client.createKey(key).subscribe(keyResponse -> assertKeyEquals(key, keyResponse));
sleepInRecordMode(1000);
}
sleepInRecordMode(30000);
client.listPropertiesOfKeys().subscribe(output::add);
sleepInRecordMode(30000);
for (KeyProperties actualKey : output) {
if (keys.containsKey(actualKey.getName())) {
CreateKeyOptions expectedKey = keys.get(actualKey.getName());
assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn());
assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore());
keys.remove(actualKey.getName());
}
}
assertEquals(0, keys.size());
});
}
private void pollOnKeyDeletion(String keyName) {
int pendingPollCount = 0;
while (pendingPollCount < 30) {
DeletedKey deletedKey = null;
try {
deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue();
} catch (ResourceNotFoundException e) {
}
if (deletedKey == null) {
sleepInRecordMode(2000);
pendingPollCount += 1;
} else {
return;
}
}
System.err.printf("Deleted Key %s not found \n", keyName);
}
private void pollOnKeyPurge(String keyName) {
int pendingPollCount = 0;
while (pendingPollCount < 10) {
DeletedKey deletedKey = null;
try {
deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue();
} catch (ResourceNotFoundException e) {
}
if (deletedKey != null) {
sleepInRecordMode(2000);
pendingPollCount += 1;
} else {
return;
}
}
System.err.printf("Deleted Key %s was not purged \n", keyName);
}
} | |
Taken as future improvement. | private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
} | "The Json Web Key Type: %s is not supported.", key.getKeyType().toString()))); | private void initializeCryptoClients() {
if (localKeyCryptographyClient != null) {
return;
}
if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) {
localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) {
localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient);
} else if (key.getKeyType().equals(OCT)) {
localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient);
} else {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"The Json Web Key Type: %s is not supported.", key.getKeyType().toString())));
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getKeyId())) {
unpackAndValidateId(key.getKeyId());
cryptographyServiceClient = new CryptographyServiceClient(key.getKeyId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getKeyId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getKeyId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getKeyId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getKeyId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getKeyId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getKeyId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getKeyId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getKeyId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class);
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param key the JsonWebKey to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline, CryptographyServiceVersion version) {
Objects.requireNonNull(key);
if (!key.isValid()) {
throw new IllegalArgumentException("Json Web Key is not valid");
}
if (key.getKeyOps() == null) {
throw new IllegalArgumentException("Json Web Key's key operations property is not configured");
}
if (key.getKeyType() == null) {
throw new IllegalArgumentException("Json Web Key's key type property is not configured");
}
this.key = key;
service = RestProxy.create(CryptographyService.class, pipeline);
if (!Strings.isNullOrEmpty(key.getId())) {
unpackAndValidateId(key.getId());
cryptographyServiceClient = new CryptographyServiceClient(key.getId(), service);
} else {
cryptographyServiceClient = null;
}
initializeCryptoClients();
}
/**
* Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests
*
* @param keyId THe Azure Key vault key identifier to use for cryptography operations.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CryptographyServiceVersion} of the service to be used when making requests.
*/
CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) {
unpackAndValidateId(keyId);
service = RestProxy.create(CryptographyService.class, pipeline);
cryptographyServiceClient = new CryptographyServiceClient(keyId, service);
this.key = null;
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse}
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<KeyVaultKey>> getKeyWithResponse() {
try {
return withContext(context -> getKeyWithResponse(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the configured key. The get key operation is applicable to all key types and it requires
* the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey}
*
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* @throws ResourceNotFoundException when the configured key doesn't exist in the key vault.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<KeyVaultKey> getKey() {
try {
return getKeyWithResponse().flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(Context context) {
return cryptographyServiceClient.getKey(context);
}
/**
* Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
* single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
* The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
* portion of the key is used for encryption. This operation requires the keys/encrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the
* specified {@code plaintext}. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
* a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt
*
* @param algorithm The algorithm to be used for encryption.
* @param plaintext The content to be encrypted.
* @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult
* contains the encrypted content.
* @throws ResourceNotFoundException if the key cannot be found for encryption.
* @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code plainText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
try {
return withContext(context -> encrypt(algorithm, plaintext, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Encrypt Operation is missing "
+ "permission/not supported for key with id %s", key.getId()))));
}
return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, context, key);
}
/**
* Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
* single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
* be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
* keys/decrypt permission.
*
* <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
* specified encrypted content. Possible values for assymetric keys include:
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* Possible values for symmetric keys include: {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* {@link EncryptionAlgorithm
* EncryptionAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
* details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt
*
* @param algorithm The algorithm to be used for decryption.
* @param cipherText The content to be decrypted.
* @return A {@link Mono} containing the decrypted blob.
* @throws ResourceNotFoundException if the key cannot be found for decryption.
* @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
try {
return withContext(context -> decrypt(algorithm, cipherText, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, Context context) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.decrypt(algorithm, cipherText, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, context, key);
}
/**
* Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
* symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
* signature from the digest. Possible values include:
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) {
try {
return withContext(context -> sign(algorithm, digest, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.sign(algorithm, digest, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", key.getId()))));
}
return localKeyCryptographyClient.signAsync(algorithm, digest, context, key);
}
/**
* Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
* keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation
* requires the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify
*
* @param algorithm The algorithm to use for signing.
* @param digest The content from which signature is to be created.
* @param signature The signature to be verified.
* @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
try {
return withContext(context -> verify(algorithm, digest, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(digest, "Digest content cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verify(algorithm, digest, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Verify Operation is not allowed for "
+ "key with id %s", key.getId()))));
}
return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key);
}
/**
* Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
* symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
* key content. Possible values include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param key The key content to be wrapped
* @return A {@link Mono} containing a {@link WrapResult} whose {@link WrapResult
* key} contains the wrapped key result.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code key} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
try {
return withContext(context -> wrapKey(algorithm, key, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<WrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(key, "Key content to be wrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.wrapKey(algorithm, key, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for "
+ "key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key);
}
/**
* Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
* the reverse of the wrap operation.
* The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey
* permission.
*
* <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the
* specified encrypted key content. Possible values for asymmetric keys include:
* {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
* Possible values for symmetric keys include: {@link KeyWrapAlgorithm
* KeyWrapAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
* response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey
*
* @param algorithm The encryption algorithm to use for wrapping the key.
* @param encryptedKey The encrypted key content to unwrap.
* @return A {@link Mono} containing a the unwrapped key content.
* @throws ResourceNotFoundException if the key cannot be found for wrap operation.
* @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
try {
return withContext(context -> unwrapKey(algorithm, encryptedKey, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) {
Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null.");
Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed "
+ "for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key);
}
/**
* Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
* and symmetric keys. This operation requires the keys/sign permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest.
* Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
* has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData
*
* @param algorithm The algorithm to use for signing.
* @param data The content from which signature is to be created.
* @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult
* the created signature.
* @throws ResourceNotFoundException if the key cannot be found for signing.
* @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm} or {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) {
try {
return withContext(context -> signData(algorithm, data, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data to be signed cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.signData(algorithm, data, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key "
+ "with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key);
}
/**
* Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
* keys and asymmetric keys.
* In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
* the keys/verify permission.
*
* <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the
* signature. Possible values include:
* {@link SignatureAlgorithm
* ES512}, {@link SignatureAlgorithm
* SignatureAlgorithm
* {@link SignatureAlgorithm
*
* <p><strong>Code Samples</strong></p>
* <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
* verification details when a response has been received.</p>
* {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData
*
* @param algorithm The algorithm to use for signing.
* @param data The raw content against which signature is to be verified.
* @param signature The signature to be verified.
* @return The {@link Boolean} indicating the signature verification result.
* @throws ResourceNotFoundException if the key cannot be found for verifying.
* @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
* @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
try {
return withContext(context -> verifyData(algorithm, data, signature, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) {
Objects.requireNonNull(algorithm, "Signature algorithm cannot be null.");
Objects.requireNonNull(data, "Data cannot be null.");
Objects.requireNonNull(signature, "Signature to be verified cannot be null.");
boolean keyAvailableLocally = ensureValidKeyAvailable();
if (!keyAvailableLocally) {
return cryptographyServiceClient.verifyData(algorithm, data, signature, context);
}
if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"Verify Operation is not allowed for key with id %s", this.key.getId()))));
}
return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key);
}
private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
String version = (tokens.length >= 4 ? tokens[3] : null);
if (Strings.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid"));
} else if (Strings.isNullOrEmpty(keyName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid"));
} else if (Strings.isNullOrEmpty(version)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid"));
}
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e));
}
}
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) {
return operations.contains(keyOperation);
}
private boolean ensureValidKeyAvailable() {
boolean keyAvailableLocally = true;
if (this.key == null) {
try {
KeyVaultKey keyVaultKey = getKey().block();
this.key = keyVaultKey.getKey();
keyAvailableLocally = this.key.isValid();
initializeCryptoClients();
} catch (HttpResponseException | NullPointerException e) {
logger.warning("Failed to retrieve key from key vault");
logger.logExceptionAsWarning(e);
keyAvailableLocally = false;
}
}
return keyAvailableLocally;
}
CryptographyServiceClient getCryptographyServiceClient() {
return cryptographyServiceClient;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.