Skip to content

Commit

Permalink
chore(samples): update UploadObjectFromMemory to use the most appropr…
Browse files Browse the repository at this point in the history
…iate method (#2495)
  • Loading branch information
BenWhitehead committed Apr 11, 2024
1 parent f548335 commit 0dc9b9e
Showing 1 changed file with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

Expand All @@ -45,7 +44,25 @@ public static void uploadObjectFromMemory(
BlobId blobId = BlobId.of(bucketName, objectName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
byte[] content = contents.getBytes(StandardCharsets.UTF_8);
storage.createFrom(blobInfo, new ByteArrayInputStream(content));

// Optional: set a generation-match precondition to enable automatic retries, avoid potential
// race
// conditions and data corruptions. The request returns a 412 error if the
// preconditions are not met.
Storage.BlobTargetOption precondition;
if (storage.get(bucketName, objectName) == null) {
// For a target object that does not yet exist, set the DoesNotExist precondition.
// This will cause the request to fail if the object is created before the request runs.
precondition = Storage.BlobTargetOption.doesNotExist();
} else {
// If the destination already exists in your bucket, instead set a generation-match
// precondition. This will cause the request to fail if the existing object's generation
// changes before the request runs.
precondition =
Storage.BlobTargetOption.generationMatch(
storage.get(bucketName, objectName).getGeneration());
}
storage.create(blobInfo, content, precondition);

System.out.println(
"Object "
Expand Down

0 comments on commit 0dc9b9e

Please sign in to comment.