Skip to content

Instantly share code, notes, and snippets.

@anishi1222
Created December 24, 2020 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anishi1222/90ddfcfeead076f56861ad23885ddd8d to your computer and use it in GitHub Desktop.
Save anishi1222/90ddfcfeead076f56861ad23885ddd8d to your computer and use it in GitHub Desktop.
// 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