Skip to content

Commit 487e3e7

Browse files
authored
chore(samples): update UploadObjectFromMemory to use the most appropriate method (#2495)
1 parent 2b78dd7 commit 487e3e7

1 file changed

Lines changed: 19 additions & 2 deletions

File tree

java-storage/samples/snippets/src/main/java/com/example/storage/object/UploadObjectFromMemory.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
import com.google.cloud.storage.BlobInfo;
2323
import com.google.cloud.storage.Storage;
2424
import com.google.cloud.storage.StorageOptions;
25-
import java.io.ByteArrayInputStream;
2625
import java.io.IOException;
2726
import java.nio.charset.StandardCharsets;
2827

@@ -45,7 +44,25 @@ public static void uploadObjectFromMemory(
4544
BlobId blobId = BlobId.of(bucketName, objectName);
4645
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
4746
byte[] content = contents.getBytes(StandardCharsets.UTF_8);
48-
storage.createFrom(blobInfo, new ByteArrayInputStream(content));
47+
48+
// Optional: set a generation-match precondition to enable automatic retries, avoid potential
49+
// race
50+
// conditions and data corruptions. The request returns a 412 error if the
51+
// preconditions are not met.
52+
Storage.BlobTargetOption precondition;
53+
if (storage.get(bucketName, objectName) == null) {
54+
// For a target object that does not yet exist, set the DoesNotExist precondition.
55+
// This will cause the request to fail if the object is created before the request runs.
56+
precondition = Storage.BlobTargetOption.doesNotExist();
57+
} else {
58+
// If the destination already exists in your bucket, instead set a generation-match
59+
// precondition. This will cause the request to fail if the existing object's generation
60+
// changes before the request runs.
61+
precondition =
62+
Storage.BlobTargetOption.generationMatch(
63+
storage.get(bucketName, objectName).getGeneration());
64+
}
65+
storage.create(blobInfo, content, precondition);
4966

5067
System.out.println(
5168
"Object "

0 commit comments

Comments
 (0)