Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Optimistic
void optimistic(BlobClient blobClient) {
try {
// 1st
String blobContents1 = "First update. Overwrite blob if it exists.";
byte[] byteArray = blobContents1.getBytes(StandardCharsets.UTF_8);
InputStream targetStream = new ByteArrayInputStream(byteArray);
BlobParallelUploadOptions blobParallelUploadOptions = new BlobParallelUploadOptions(targetStream, byteArray.length);
Response<BlockBlobItem> blobItemResponse = blobClient.uploadWithResponse(blobParallelUploadOptions, null, Context.NONE);
System.out.println("Content: " + blobContents1);
System.out.println("Status: " + blobItemResponse.getStatusCode());
System.out.println("ETag: " + blobItemResponse.getValue().getETag());
String originalEtag = blobItemResponse.getValue().getETag();
// 2nd
String blobContents2 = "Second update overwrites first update.";
byteArray = blobContents2.getBytes(StandardCharsets.UTF_8);
targetStream = new ByteArrayInputStream(byteArray);
blobParallelUploadOptions = new BlobParallelUploadOptions(targetStream, byteArray.length);
blobItemResponse = blobClient.uploadWithResponse(blobParallelUploadOptions, null, Context.NONE);
System.out.println("Content: " + blobContents2);
System.out.println("Status: " + blobItemResponse.getStatusCode());
System.out.println("ETag: " + blobItemResponse.getValue().getETag());
// 3rd ETagが一致する場合に上書き(書き換わっているから失敗する)
String blobContents3 = "Third update. If-Match condition set to original ETag.";
byteArray = blobContents3.getBytes(StandardCharsets.UTF_8);
targetStream = new ByteArrayInputStream(byteArray);
BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setIfMatch(originalEtag);
blobParallelUploadOptions = new BlobParallelUploadOptions(targetStream, byteArray.length)
.setRequestConditions(blobRequestConditions);
blobItemResponse = blobClient.uploadWithResponse(blobParallelUploadOptions, null, Context.NONE);
System.out.println("Content: " + blobContents3);
System.out.println("Status: " + blobItemResponse.getStatusCode());
System.out.println("ETag: " + blobItemResponse.getValue().getETag());
}
catch(BlobStorageException e) {
if(e.getStatusCode() == HttpURLConnection.HTTP_PRECON_FAILED) {
System.out.println("Precondition failure as expected. Blob's ETag does not match ETag provided.");
}
else {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment