2222import com .google .cloud .storage .BlobInfo ;
2323import com .google .cloud .storage .Storage ;
2424import com .google .cloud .storage .StorageOptions ;
25- import java .io .ByteArrayInputStream ;
2625import java .io .IOException ;
2726import 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