blobs = bucket.list(Storage.BlobListOption.versions(true));
- for (Blob blob : blobs.iterateAll()) {
- System.out.println(blob.getName() + "," + blob.getGeneration());
+ for (Blob blob : blobs.iterateAll()) {
+ System.out.println(blob.getName() + "," + blob.getGeneration());
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/object/ListObjectsWithPrefix.java b/samples/snippets/src/main/java/com/example/storage/object/ListObjectsWithPrefix.java
index 3a9f564a9c..9bb0f07e88 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/ListObjectsWithPrefix.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/ListObjectsWithPrefix.java
@@ -24,7 +24,7 @@
public class ListObjectsWithPrefix {
public static void listObjectsWithPrefix(
- String projectId, String bucketName, String directoryPrefix) {
+ String projectId, String bucketName, String directoryPrefix) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -34,35 +34,38 @@ public static void listObjectsWithPrefix(
// The directory prefix to search for
// String directoryPrefix = "myDirectory/"
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- /**
- * Using the Storage.BlobListOption.currentDirectory() option here causes the results to display
- * in a "directory-like" mode, showing what objects are in the directory you've specified, as
- * well as what other directories exist in that directory. For example, given these blobs:
- *
- * a/1.txt a/b/2.txt a/b/3.txt
- *
- *
If you specify prefix = "a/" and don't use Storage.BlobListOption.currentDirectory(),
- * you'll get back:
- *
- *
a/1.txt a/b/2.txt a/b/3.txt
- *
- *
However, if you specify prefix = "a/" and do use
- * Storage.BlobListOption.currentDirectory(), you'll get back:
- *
- *
a/1.txt a/b/
- *
- *
Because a/1.txt is the only file in the a/ directory and a/b/ is a directory inside the
- * /a/ directory.
- */
- Page blobs =
- storage.list(
- bucketName,
- Storage.BlobListOption.prefix(directoryPrefix),
- Storage.BlobListOption.currentDirectory());
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ /**
+ * Using the Storage.BlobListOption.currentDirectory() option here causes the results to
+ * display in a "directory-like" mode, showing what objects are in the directory you've
+ * specified, as well as what other directories exist in that directory. For example, given
+ * these blobs:
+ *
+ * a/1.txt a/b/2.txt a/b/3.txt
+ *
+ *
If you specify prefix = "a/" and don't use Storage.BlobListOption.currentDirectory(),
+ * you'll get back:
+ *
+ *
a/1.txt a/b/2.txt a/b/3.txt
+ *
+ *
However, if you specify prefix = "a/" and do use
+ * Storage.BlobListOption.currentDirectory(), you'll get back:
+ *
+ *
a/1.txt a/b/
+ *
+ *
Because a/1.txt is the only file in the a/ directory and a/b/ is a directory inside the
+ * /a/ directory.
+ */
+ Page blobs =
+ storage.list(
+ bucketName,
+ Storage.BlobListOption.prefix(directoryPrefix),
+ Storage.BlobListOption.currentDirectory());
- for (Blob blob : blobs.iterateAll()) {
- System.out.println(blob.getName());
+ for (Blob blob : blobs.iterateAll()) {
+ System.out.println(blob.getName());
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/object/ListSoftDeletedObjects.java b/samples/snippets/src/main/java/com/example/storage/object/ListSoftDeletedObjects.java
index eb3b5d158b..9f5130cad6 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/ListSoftDeletedObjects.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/ListSoftDeletedObjects.java
@@ -23,18 +23,20 @@
import com.google.cloud.storage.StorageOptions;
public class ListSoftDeletedObjects {
- public static void listSoftDeletedObjects(String projectId, String bucketName) {
+ public static void listSoftDeletedObjects(String projectId, String bucketName) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- Page blobs = storage.list(bucketName, Storage.BlobListOption.softDeleted(true));
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ Page blobs = storage.list(bucketName, Storage.BlobListOption.softDeleted(true));
- for (Blob blob : blobs.iterateAll()) {
- System.out.println(blob.getName());
+ for (Blob blob : blobs.iterateAll()) {
+ System.out.println(blob.getName());
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/object/ListSoftDeletedVersionsOfObject.java b/samples/snippets/src/main/java/com/example/storage/object/ListSoftDeletedVersionsOfObject.java
index 87532cdc8e..950f8b1464 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/ListSoftDeletedVersionsOfObject.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/ListSoftDeletedVersionsOfObject.java
@@ -25,7 +25,7 @@
public class ListSoftDeletedVersionsOfObject {
public static void listSoftDeletedVersionOfObject(
- String projectId, String bucketName, String objectName) {
+ String projectId, String bucketName, String objectName) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -35,16 +35,18 @@ public static void listSoftDeletedVersionOfObject(
// The name of your GCS object
// String objectName = "your-object-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- Page blobs =
- storage.list(
- bucketName,
- Storage.BlobListOption.softDeleted(true),
- // See https://cloud.google.com/storage/docs/json_api/v1/objects/list#matchGlob
- Storage.BlobListOption.matchGlob(objectName));
-
- for (Blob blob : blobs.iterateAll()) {
- System.out.println(blob.getName());
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ Page blobs =
+ storage.list(
+ bucketName,
+ Storage.BlobListOption.softDeleted(true),
+ // See https://cloud.google.com/storage/docs/json_api/v1/objects/list#matchGlob
+ Storage.BlobListOption.matchGlob(objectName));
+
+ for (Blob blob : blobs.iterateAll()) {
+ System.out.println(blob.getName());
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/object/MakeObjectPublic.java b/samples/snippets/src/main/java/com/example/storage/object/MakeObjectPublic.java
index 245c030a6b..7ac041c81e 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/MakeObjectPublic.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/MakeObjectPublic.java
@@ -23,16 +23,19 @@
import com.google.cloud.storage.StorageOptions;
public class MakeObjectPublic {
- public static void makeObjectPublic(String projectId, String bucketName, String objectName) {
+ public static void makeObjectPublic(String projectId, String bucketName, String objectName)
+ throws Exception {
// String projectId = "your-project-id";
// String bucketName = "your-bucket-name";
// String objectName = "your-object-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- storage.createAcl(blobId, Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ storage.createAcl(blobId, Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
- System.out.println(
- "Object " + objectName + " in bucket " + bucketName + " was made publicly readable");
+ System.out.println(
+ "Object " + objectName + " in bucket " + bucketName + " was made publicly readable");
+ }
}
}
// [END storage_make_public]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/PrintBlobAcl.java b/samples/snippets/src/main/java/com/example/storage/object/PrintBlobAcl.java
index 34089a56f9..f5434ea201 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/PrintBlobAcl.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/PrintBlobAcl.java
@@ -27,7 +27,7 @@
public class PrintBlobAcl {
- public static void printBlobAcl(String bucketName, String blobName) {
+ public static void printBlobAcl(String bucketName, String blobName) throws Exception {
// The ID to give your GCS bucket
// String bucketName = "your-unique-bucket-name";
@@ -35,21 +35,22 @@ public static void printBlobAcl(String bucketName, String blobName) {
// The name of the blob/file that you wish to view Acls of
// String blobName = "your-blob-name";
- Storage storage = StorageOptions.newBuilder().build().getService();
- Blob blob = storage.get(BlobId.of(bucketName, blobName));
- List blobAcls = blob.getAcl();
+ try (Storage storage = StorageOptions.newBuilder().build().getService()) {
+ Blob blob = storage.get(BlobId.of(bucketName, blobName));
+ List blobAcls = blob.getAcl();
- for (Acl acl : blobAcls) {
+ for (Acl acl : blobAcls) {
- // This will give you the role.
- // See https://cloud.google.com/storage/docs/access-control/lists#permissions
- String role = acl.getRole().name();
+ // This will give you the role.
+ // See https://cloud.google.com/storage/docs/access-control/lists#permissions
+ String role = acl.getRole().name();
- // This will give you the Entity type (i.e. User, Group, Project etc.)
- // See https://cloud.google.com/storage/docs/access-control/lists#scopes
- String entityType = acl.getEntity().getType().name();
+ // This will give you the Entity type (i.e. User, Group, Project etc.)
+ // See https://cloud.google.com/storage/docs/access-control/lists#scopes
+ String entityType = acl.getEntity().getType().name();
- System.out.printf("%s: %s %n", role, entityType);
+ System.out.printf("%s: %s %n", role, entityType);
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/object/ReleaseEventBasedHold.java b/samples/snippets/src/main/java/com/example/storage/object/ReleaseEventBasedHold.java
index 6ce3e13379..01c9f73a09 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/ReleaseEventBasedHold.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/ReleaseEventBasedHold.java
@@ -21,12 +21,11 @@
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
-import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
public class ReleaseEventBasedHold {
public static void releaseEventBasedHold(String projectId, String bucketName, String objectName)
- throws StorageException {
+ throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -36,22 +35,24 @@ public static void releaseEventBasedHold(String projectId, String bucketName, St
// The ID of your GCS object
// String objectName = "your-object-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- Blob blob = storage.get(blobId);
- if (blob == null) {
- System.out.println("The object " + objectName + " was not found in " + bucketName);
- return;
- }
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ Blob blob = storage.get(blobId);
+ if (blob == null) {
+ System.out.println("The object " + objectName + " was not found in " + bucketName);
+ return;
+ }
- // Optional: set a generation-match precondition to avoid potential race
- // conditions and data corruptions. The request to upload returns a 412 error if
- // the object's generation number does not match your precondition.
- Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
+ // Optional: set a generation-match precondition to avoid potential race
+ // conditions and data corruptions. The request to upload returns a 412 error if
+ // the object's generation number does not match your precondition.
+ Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
- blob.toBuilder().setEventBasedHold(false).build().update(precondition);
+ blob.toBuilder().setEventBasedHold(false).build().update(precondition);
- System.out.println("Event-based hold was released for " + objectName);
+ System.out.println("Event-based hold was released for " + objectName);
+ }
}
}
// [END storage_release_event_based_hold]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/ReleaseTemporaryHold.java b/samples/snippets/src/main/java/com/example/storage/object/ReleaseTemporaryHold.java
index eae54db368..6d055661e4 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/ReleaseTemporaryHold.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/ReleaseTemporaryHold.java
@@ -21,12 +21,11 @@
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
-import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
public class ReleaseTemporaryHold {
public static void releaseTemporaryHold(String projectId, String bucketName, String objectName)
- throws StorageException {
+ throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -36,23 +35,25 @@ public static void releaseTemporaryHold(String projectId, String bucketName, Str
// The ID of your GCS object
// String objectName = "your-object-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
- BlobId blobId = BlobId.of(bucketName, objectName);
- Blob blob = storage.get(blobId);
- if (blob == null) {
- System.out.println("The object " + objectName + " was not found in " + bucketName);
- return;
- }
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ Blob blob = storage.get(blobId);
+ if (blob == null) {
+ System.out.println("The object " + objectName + " was not found in " + bucketName);
+ return;
+ }
- // Optional: set a generation-match precondition to avoid potential race
- // conditions and data corruptions. The request to upload returns a 412 error if
- // the object's generation number does not match your precondition.
- Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
+ // Optional: set a generation-match precondition to avoid potential race
+ // conditions and data corruptions. The request to upload returns a 412 error if
+ // the object's generation number does not match your precondition.
+ Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
- blob.toBuilder().setTemporaryHold(false).build().update(precondition);
+ blob.toBuilder().setTemporaryHold(false).build().update(precondition);
- System.out.println("Temporary hold was released for " + objectName);
+ System.out.println("Temporary hold was released for " + objectName);
+ }
}
}
// [END storage_release_temporary_hold]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/RemoveBlobOwner.java b/samples/snippets/src/main/java/com/example/storage/object/RemoveBlobOwner.java
index ecbb0e41df..d8a8f37224 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/RemoveBlobOwner.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/RemoveBlobOwner.java
@@ -27,7 +27,7 @@
public class RemoveBlobOwner {
public static void removeBlobOwner(
- String projectId, String bucketName, String userEmail, String blobName) {
+ String projectId, String bucketName, String userEmail, String blobName) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -40,21 +40,23 @@ public static void removeBlobOwner(
// The name of the blob/file that you wish to modify permissions on
// String blobName = "your-blob-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- Blob blob = storage.get(BlobId.of(bucketName, blobName));
- User ownerToRemove = new User(userEmail);
-
- boolean success = blob.deleteAcl(ownerToRemove);
- if (success) {
- System.out.println(
- "Removed user "
- + userEmail
- + " as an owner on file "
- + blobName
- + " in bucket "
- + bucketName);
- } else {
- System.out.println("User " + userEmail + " was not found");
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ Blob blob = storage.get(BlobId.of(bucketName, blobName));
+ User ownerToRemove = new User(userEmail);
+
+ boolean success = blob.deleteAcl(ownerToRemove);
+ if (success) {
+ System.out.println(
+ "Removed user "
+ + userEmail
+ + " as an owner on file "
+ + blobName
+ + " in bucket "
+ + bucketName);
+ } else {
+ System.out.println("User " + userEmail + " was not found");
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/object/RestoreSoftDeletedObject.java b/samples/snippets/src/main/java/com/example/storage/object/RestoreSoftDeletedObject.java
index 86f09a39ec..809999981b 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/RestoreSoftDeletedObject.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/RestoreSoftDeletedObject.java
@@ -24,7 +24,7 @@
public class RestoreSoftDeletedObject {
public static void restoreSoftDeletedObject(
- String projectId, String bucketName, String objectName, long generation) {
+ String projectId, String bucketName, String objectName, long generation) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -34,10 +34,12 @@ public static void restoreSoftDeletedObject(
// The name of your GCS object
// String objectName = "your-object-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- Blob blob = storage.restore(BlobId.of(bucketName, objectName, generation));
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ Blob blob = storage.restore(BlobId.of(bucketName, objectName, generation));
- System.out.println("Restored previously soft-deleted object " + blob.getName());
+ System.out.println("Restored previously soft-deleted object " + blob.getName());
+ }
}
}
// [END storage_restore_object]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/RotateObjectEncryptionKey.java b/samples/snippets/src/main/java/com/example/storage/object/RotateObjectEncryptionKey.java
index 3fbd8c5e56..b60ca694b4 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/RotateObjectEncryptionKey.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/RotateObjectEncryptionKey.java
@@ -28,7 +28,8 @@ public static void rotateObjectEncryptionKey(
String bucketName,
String objectName,
String oldEncryptionKey,
- String newEncryptionKey) {
+ String newEncryptionKey)
+ throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -47,32 +48,35 @@ public static void rotateObjectEncryptionKey(
// The new encryption key to use
// String newEncryptionKey = "0mMWhFvQOdS4AmxRpo8SJxXn5MjFhbz7DkKBUdUIef8="
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- Blob blob = storage.get(blobId);
- if (blob == null) {
- System.out.println("The object " + objectName + " wasn't found in " + bucketName);
- return;
- }
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ Blob blob = storage.get(blobId);
+ if (blob == null) {
+ System.out.println("The object " + objectName + " wasn't found in " + bucketName);
+ return;
+ }
- // Optional: set a generation-match precondition to avoid potential race
- // conditions and data corruptions. The request to upload returns a 412 error if
- // the object's generation number does not match your precondition.
- Storage.BlobSourceOption precondition =
- Storage.BlobSourceOption.generationMatch(blob.getGeneration());
+ // Optional: set a generation-match precondition to avoid potential race
+ // conditions and data corruptions. The request to upload returns a 412 error if
+ // the object's generation number does not match your precondition.
+ Storage.BlobSourceOption precondition =
+ Storage.BlobSourceOption.generationMatch(blob.getGeneration());
- // You can't change an object's encryption key directly, the only way is to overwrite the object
- Storage.CopyRequest request =
- Storage.CopyRequest.newBuilder()
- .setSource(blobId)
- .setSourceOptions(
- Storage.BlobSourceOption.decryptionKey(oldEncryptionKey), precondition)
- .setTarget(blobId, Storage.BlobTargetOption.encryptionKey(newEncryptionKey))
- .build();
- storage.copy(request);
+ // You can't change an object's encryption key directly, the only way is to overwrite the
+ // object
+ Storage.CopyRequest request =
+ Storage.CopyRequest.newBuilder()
+ .setSource(blobId)
+ .setSourceOptions(
+ Storage.BlobSourceOption.decryptionKey(oldEncryptionKey), precondition)
+ .setTarget(blobId, Storage.BlobTargetOption.encryptionKey(newEncryptionKey))
+ .build();
+ storage.copy(request);
- System.out.println(
- "Rotated encryption key for object " + objectName + "in bucket " + bucketName);
+ System.out.println(
+ "Rotated encryption key for object " + objectName + "in bucket " + bucketName);
+ }
}
}
// [END storage_rotate_encryption_key]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/SetEventBasedHold.java b/samples/snippets/src/main/java/com/example/storage/object/SetEventBasedHold.java
index c0f8f088d4..d5177fbb22 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/SetEventBasedHold.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/SetEventBasedHold.java
@@ -21,12 +21,11 @@
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
-import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
public class SetEventBasedHold {
public static void setEventBasedHold(String projectId, String bucketName, String objectName)
- throws StorageException {
+ throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -36,22 +35,24 @@ public static void setEventBasedHold(String projectId, String bucketName, String
// The ID of your GCS object
// String objectName = "your-object-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- Blob blob = storage.get(blobId);
- if (blob == null) {
- System.out.println("The object " + objectName + " was not found in " + bucketName);
- return;
- }
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ Blob blob = storage.get(blobId);
+ if (blob == null) {
+ System.out.println("The object " + objectName + " was not found in " + bucketName);
+ return;
+ }
- // Optional: set a generation-match precondition to avoid potential race
- // conditions and data corruptions. The request to upload returns a 412 error if
- // the object's generation number does not match your precondition.
- Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
+ // Optional: set a generation-match precondition to avoid potential race
+ // conditions and data corruptions. The request to upload returns a 412 error if
+ // the object's generation number does not match your precondition.
+ Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
- blob.toBuilder().setEventBasedHold(true).build().update(precondition);
+ blob.toBuilder().setEventBasedHold(true).build().update(precondition);
- System.out.println("Event-based hold was set for " + objectName);
+ System.out.println("Event-based hold was set for " + objectName);
+ }
}
}
// [END storage_set_event_based_hold]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/SetObjectMetadata.java b/samples/snippets/src/main/java/com/example/storage/object/SetObjectMetadata.java
index ae05011e8e..1442ea72fb 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/SetObjectMetadata.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/SetObjectMetadata.java
@@ -27,7 +27,8 @@
import java.util.Map;
public class SetObjectMetadata {
- public static void setObjectMetadata(String projectId, String bucketName, String objectName) {
+ public static void setObjectMetadata(String projectId, String bucketName, String objectName)
+ throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -37,28 +38,31 @@ public static void setObjectMetadata(String projectId, String bucketName, String
// The ID of your GCS object
// String objectName = "your-object-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- Map newMetadata = new HashMap<>();
- newMetadata.put("keyToAddOrUpdate", "value");
- BlobId blobId = BlobId.of(bucketName, objectName);
- Blob blob = storage.get(blobId);
- if (blob == null) {
- System.out.println("The object " + objectName + " was not found in " + bucketName);
- return;
- }
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ Map newMetadata = new HashMap<>();
+ newMetadata.put("keyToAddOrUpdate", "value");
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ Blob blob = storage.get(blobId);
+ if (blob == null) {
+ System.out.println("The object " + objectName + " was not found in " + bucketName);
+ return;
+ }
- // Optional: set a generation-match precondition to avoid potential race
- // conditions and data corruptions. The request to upload returns a 412 error if
- // the object's generation number does not match your precondition.
- Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
+ // Optional: set a generation-match precondition to avoid potential race
+ // conditions and data corruptions. The request to upload returns a 412 error if
+ // the object's generation number does not match your precondition.
+ Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
- // Does an upsert operation, if the key already exists it's replaced by the new value, otherwise
- // it's added.
- BlobInfo pendingUpdate = blob.toBuilder().setMetadata(newMetadata).build();
- storage.update(pendingUpdate, precondition);
+ // Does an upsert operation, if the key already exists it's replaced by the new value,
+ // otherwise
+ // it's added.
+ BlobInfo pendingUpdate = blob.toBuilder().setMetadata(newMetadata).build();
+ storage.update(pendingUpdate, precondition);
- System.out.println(
- "Updated custom metadata for object " + objectName + " in bucket " + bucketName);
+ System.out.println(
+ "Updated custom metadata for object " + objectName + " in bucket " + bucketName);
+ }
}
}
// [END storage_set_metadata]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/SetObjectRetentionPolicy.java b/samples/snippets/src/main/java/com/example/storage/object/SetObjectRetentionPolicy.java
index 6903445af0..a14c5e5652 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/SetObjectRetentionPolicy.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/SetObjectRetentionPolicy.java
@@ -24,12 +24,11 @@
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo.Retention;
import com.google.cloud.storage.Storage;
-import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
public class SetObjectRetentionPolicy {
public static void setObjectRetentionPolicy(
- String projectId, String bucketName, String objectName) throws StorageException {
+ String projectId, String bucketName, String objectName) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -39,36 +38,38 @@ public static void setObjectRetentionPolicy(
// The ID of your GCS object
// String objectName = "your-object-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- Blob blob = storage.get(blobId);
- if (blob == null) {
- System.out.println("The object " + objectName + " was not found in " + bucketName);
- return;
- }
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ Blob blob = storage.get(blobId);
+ if (blob == null) {
+ System.out.println("The object " + objectName + " was not found in " + bucketName);
+ return;
+ }
- Blob updated =
- blob.toBuilder()
- .setRetention(
- Retention.newBuilder()
- .setMode(Retention.Mode.UNLOCKED)
- .setRetainUntilTime(now().plusDays(10))
- .build())
- .build()
- .update();
+ Blob updated =
+ blob.toBuilder()
+ .setRetention(
+ Retention.newBuilder()
+ .setMode(Retention.Mode.UNLOCKED)
+ .setRetainUntilTime(now().plusDays(10))
+ .build())
+ .build()
+ .update();
- System.out.println("Retention policy for object " + objectName + " was set to:");
- System.out.println(updated.getRetention().toString());
+ System.out.println("Retention policy for object " + objectName + " was set to:");
+ System.out.println(updated.getRetention().toString());
- // To modify an existing policy on an Unlocked object, pass in the override parameter
- blob.toBuilder()
- .setRetention(
- updated.getRetention().toBuilder().setRetainUntilTime(now().plusDays(9)).build())
- .build()
- .update(Storage.BlobTargetOption.overrideUnlockedRetention(true));
+ // To modify an existing policy on an Unlocked object, pass in the override parameter
+ blob.toBuilder()
+ .setRetention(
+ updated.getRetention().toBuilder().setRetainUntilTime(now().plusDays(9)).build())
+ .build()
+ .update(Storage.BlobTargetOption.overrideUnlockedRetention(true));
- System.out.println("Retention policy for object " + objectName + " was updated to:");
- System.out.println(storage.get(blobId).getRetention().toString());
+ System.out.println("Retention policy for object " + objectName + " was updated to:");
+ System.out.println(storage.get(blobId).getRetention().toString());
+ }
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/object/SetTemporaryHold.java b/samples/snippets/src/main/java/com/example/storage/object/SetTemporaryHold.java
index c22de2f390..f9d54347ad 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/SetTemporaryHold.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/SetTemporaryHold.java
@@ -21,12 +21,11 @@
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
-import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
public class SetTemporaryHold {
public static void setTemporaryHold(String projectId, String bucketName, String objectName)
- throws StorageException {
+ throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -36,22 +35,24 @@ public static void setTemporaryHold(String projectId, String bucketName, String
// The ID of your GCS object
// String objectName = "your-object-name";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- Blob blob = storage.get(blobId);
- if (blob == null) {
- System.out.println("The object " + objectName + " was not found in " + bucketName);
- return;
- }
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ Blob blob = storage.get(blobId);
+ if (blob == null) {
+ System.out.println("The object " + objectName + " was not found in " + bucketName);
+ return;
+ }
- // Optional: set a generation-match precondition to avoid potential race
- // conditions and data corruptions. The request to upload returns a 412 error if
- // the object's generation number does not match your precondition.
- Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
+ // Optional: set a generation-match precondition to avoid potential race
+ // conditions and data corruptions. The request to upload returns a 412 error if
+ // the object's generation number does not match your precondition.
+ Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();
- blob.toBuilder().setTemporaryHold(true).build().update(precondition);
+ blob.toBuilder().setTemporaryHold(true).build().update(precondition);
- System.out.println("Temporary hold was set for " + objectName);
+ System.out.println("Temporary hold was set for " + objectName);
+ }
}
}
// [END storage_set_temporary_hold]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/StreamObjectDownload.java b/samples/snippets/src/main/java/com/example/storage/object/StreamObjectDownload.java
index 4dd38bafd1..32b66c587b 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/StreamObjectDownload.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/StreamObjectDownload.java
@@ -23,7 +23,6 @@
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.io.ByteStreams;
-import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -32,8 +31,7 @@
public class StreamObjectDownload {
public static void streamObjectDownload(
- String projectId, String bucketName, String objectName, String targetFile)
- throws IOException {
+ String projectId, String bucketName, String objectName, String targetFile) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -47,21 +45,23 @@ public static void streamObjectDownload(
// String targetFile = "path/to/your/file";
Path targetFilePath = Paths.get(targetFile);
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- try (ReadChannel reader = storage.reader(BlobId.of(bucketName, objectName));
- FileChannel targetFileChannel =
- FileChannel.open(targetFilePath, StandardOpenOption.WRITE)) {
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ try (ReadChannel reader = storage.reader(BlobId.of(bucketName, objectName));
+ FileChannel targetFileChannel =
+ FileChannel.open(targetFilePath, StandardOpenOption.WRITE)) {
- ByteStreams.copy(reader, targetFileChannel);
+ ByteStreams.copy(reader, targetFileChannel);
- System.out.println(
- "Downloaded object "
- + objectName
- + " from bucket "
- + bucketName
- + " to "
- + targetFile
- + " using a ReadChannel.");
+ System.out.println(
+ "Downloaded object "
+ + objectName
+ + " from bucket "
+ + bucketName
+ + " to "
+ + targetFile
+ + " using a ReadChannel.");
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/object/StreamObjectUpload.java b/samples/snippets/src/main/java/com/example/storage/object/StreamObjectUpload.java
index b5b82d82c5..db310bf02a 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/StreamObjectUpload.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/StreamObjectUpload.java
@@ -23,14 +23,13 @@
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
-import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class StreamObjectUpload {
public static void streamObjectUpload(
- String projectId, String bucketName, String objectName, String contents) throws IOException {
+ String projectId, String bucketName, String objectName, String contents) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -43,14 +42,16 @@ public static void streamObjectUpload(
// The string of contents you wish to upload
// String contents = "Hello world!";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
- byte[] content = contents.getBytes(StandardCharsets.UTF_8);
- try (WriteChannel writer = storage.writer(blobInfo)) {
- writer.write(ByteBuffer.wrap(content));
- System.out.println(
- "Wrote to " + objectName + " in bucket " + bucketName + " using a WriteChannel.");
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
+ byte[] content = contents.getBytes(StandardCharsets.UTF_8);
+ try (WriteChannel writer = storage.writer(blobInfo)) {
+ writer.write(ByteBuffer.wrap(content));
+ System.out.println(
+ "Wrote to " + objectName + " in bucket " + bucketName + " using a WriteChannel.");
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/object/UploadEncryptedObject.java b/samples/snippets/src/main/java/com/example/storage/object/UploadEncryptedObject.java
index e51067c264..9a0b2b8514 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/UploadEncryptedObject.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/UploadEncryptedObject.java
@@ -22,14 +22,13 @@
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
-import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class UploadEncryptedObject {
public static void uploadEncryptedObject(
String projectId, String bucketName, String objectName, String filePath, String encryptionKey)
- throws IOException {
+ throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -45,41 +44,43 @@ public static void uploadEncryptedObject(
// The key to encrypt the object with
// String encryptionKey = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
- // Optional: set a generation-match precondition to 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());
- }
+ // Optional: set a generation-match precondition to 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,
- Files.readAllBytes(Paths.get(filePath)),
- Storage.BlobTargetOption.encryptionKey(encryptionKey),
- precondition);
+ storage.create(
+ blobInfo,
+ Files.readAllBytes(Paths.get(filePath)),
+ Storage.BlobTargetOption.encryptionKey(encryptionKey),
+ precondition);
- System.out.println(
- "File "
- + filePath
- + " uploaded to bucket "
- + bucketName
- + " as "
- + objectName
- + " with supplied encryption key");
+ System.out.println(
+ "File "
+ + filePath
+ + " uploaded to bucket "
+ + bucketName
+ + " as "
+ + objectName
+ + " with supplied encryption key");
+ }
}
}
// [END storage_upload_encrypted_file]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/UploadKmsEncryptedObject.java b/samples/snippets/src/main/java/com/example/storage/object/UploadKmsEncryptedObject.java
index 3876971ca8..55c4eba6d3 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/UploadKmsEncryptedObject.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/UploadKmsEncryptedObject.java
@@ -27,7 +27,7 @@
public class UploadKmsEncryptedObject {
public static void uploadKmsEncryptedObject(
- String projectId, String bucketName, String objectName, String kmsKeyName) {
+ String projectId, String bucketName, String objectName, String kmsKeyName) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -40,38 +40,40 @@ public static void uploadKmsEncryptedObject(
// The name of the KMS key to encrypt with
// String kmsKeyName = "projects/my-project/locations/us/keyRings/my_key_ring/cryptoKeys/my_key"
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- byte[] data = "Hello, World!".getBytes(UTF_8);
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ byte[] data = "Hello, World!".getBytes(UTF_8);
- BlobId blobId = BlobId.of(bucketName, objectName);
- BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
- // Optional: set a generation-match precondition to 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());
- }
+ // Optional: set a generation-match precondition to 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, data, Storage.BlobTargetOption.kmsKeyName(kmsKeyName), precondition);
+ storage.create(blobInfo, data, Storage.BlobTargetOption.kmsKeyName(kmsKeyName), precondition);
- System.out.println(
- "Uploaded object "
- + objectName
- + " in bucket "
- + bucketName
- + " encrypted with "
- + kmsKeyName);
+ System.out.println(
+ "Uploaded object "
+ + objectName
+ + " in bucket "
+ + bucketName
+ + " encrypted with "
+ + kmsKeyName);
+ }
}
}
// [END storage_upload_with_kms_key]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/UploadObject.java b/samples/snippets/src/main/java/com/example/storage/object/UploadObject.java
index 6fa796d62f..b3e1139ec2 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/UploadObject.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/UploadObject.java
@@ -22,12 +22,11 @@
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
-import java.io.IOException;
import java.nio.file.Paths;
public class UploadObject {
public static void uploadObject(
- String projectId, String bucketName, String objectName, String filePath) throws IOException {
+ String projectId, String bucketName, String objectName, String filePath) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -40,30 +39,32 @@ public static void uploadObject(
// The path to your file to upload
// String filePath = "path/to/your/file"
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
- // Optional: set a generation-match precondition to avoid potential race
- // conditions and data corruptions. The request returns a 412 error if the
- // preconditions are not met.
- Storage.BlobWriteOption 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.BlobWriteOption.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.BlobWriteOption.generationMatch(
- storage.get(bucketName, objectName).getGeneration());
- }
- storage.createFrom(blobInfo, Paths.get(filePath), precondition);
+ // Optional: set a generation-match precondition to avoid potential race
+ // conditions and data corruptions. The request returns a 412 error if the
+ // preconditions are not met.
+ Storage.BlobWriteOption 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.BlobWriteOption.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.BlobWriteOption.generationMatch(
+ storage.get(bucketName, objectName).getGeneration());
+ }
+ storage.createFrom(blobInfo, Paths.get(filePath), precondition);
- System.out.println(
- "File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
+ System.out.println(
+ "File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
+ }
}
}
// [END storage_upload_file]
diff --git a/samples/snippets/src/main/java/com/example/storage/object/UploadObjectFromMemory.java b/samples/snippets/src/main/java/com/example/storage/object/UploadObjectFromMemory.java
index 98d0020200..723a0317b7 100644
--- a/samples/snippets/src/main/java/com/example/storage/object/UploadObjectFromMemory.java
+++ b/samples/snippets/src/main/java/com/example/storage/object/UploadObjectFromMemory.java
@@ -22,12 +22,11 @@
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
-import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class UploadObjectFromMemory {
public static void uploadObjectFromMemory(
- String projectId, String bucketName, String objectName, String contents) throws IOException {
+ String projectId, String bucketName, String objectName, String contents) throws Exception {
// The ID of your GCP project
// String projectId = "your-project-id";
@@ -40,37 +39,39 @@ public static void uploadObjectFromMemory(
// The string of contents you wish to upload
// String contents = "Hello world!";
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- BlobId blobId = BlobId.of(bucketName, objectName);
- BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
- byte[] content = contents.getBytes(StandardCharsets.UTF_8);
+ try (Storage storage =
+ StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
+ BlobId blobId = BlobId.of(bucketName, objectName);
+ BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
+ byte[] content = contents.getBytes(StandardCharsets.UTF_8);
- // 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);
+ // 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 "
- + objectName
- + " uploaded to bucket "
- + bucketName
- + " with contents "
- + contents);
+ System.out.println(
+ "Object "
+ + objectName
+ + " uploaded to bucket "
+ + bucketName
+ + " with contents "
+ + contents);
+ }
}
}
// [END storage_file_upload_from_memory]
diff --git a/samples/snippets/src/main/java/com/example/storage/transfermanager/AllowDivideAndConquerDownload.java b/samples/snippets/src/main/java/com/example/storage/transfermanager/AllowDivideAndConquerDownload.java
index 7b41ce2fb5..61d581940b 100644
--- a/samples/snippets/src/main/java/com/example/storage/transfermanager/AllowDivideAndConquerDownload.java
+++ b/samples/snippets/src/main/java/com/example/storage/transfermanager/AllowDivideAndConquerDownload.java
@@ -29,26 +29,25 @@
class AllowDivideAndConquerDownload {
public static void divideAndConquerDownloadAllowed(
- List blobs, String bucketName, Path destinationDirectory) {
- TransferManager transferManager =
- TransferManagerConfig.newBuilder()
- .setAllowDivideAndConquerDownload(true)
- .build()
- .getService();
- ParallelDownloadConfig parallelDownloadConfig =
- ParallelDownloadConfig.newBuilder()
- .setBucketName(bucketName)
- .setDownloadDirectory(destinationDirectory)
- .build();
- List results =
- transferManager.downloadBlobs(blobs, parallelDownloadConfig).getDownloadResults();
+ List blobs, String bucketName, Path destinationDirectory) throws Exception {
+ TransferManagerConfig transferManagerConfig =
+ TransferManagerConfig.newBuilder().setAllowDivideAndConquerDownload(true).build();
+ try (TransferManager transferManager = transferManagerConfig.getService()) {
+ ParallelDownloadConfig parallelDownloadConfig =
+ ParallelDownloadConfig.newBuilder()
+ .setBucketName(bucketName)
+ .setDownloadDirectory(destinationDirectory)
+ .build();
+ List results =
+ transferManager.downloadBlobs(blobs, parallelDownloadConfig).getDownloadResults();
- for (DownloadResult result : results) {
- System.out.println(
- "Download of "
- + result.getInput().getName()
- + " completed with status "
- + result.getStatus());
+ for (DownloadResult result : results) {
+ System.out.println(
+ "Download of "
+ + result.getInput().getName()
+ + " completed with status "
+ + result.getStatus());
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/transfermanager/AllowParallelCompositeUpload.java b/samples/snippets/src/main/java/com/example/storage/transfermanager/AllowParallelCompositeUpload.java
index 1aab8f4b67..f9760bfecd 100644
--- a/samples/snippets/src/main/java/com/example/storage/transfermanager/AllowParallelCompositeUpload.java
+++ b/samples/snippets/src/main/java/com/example/storage/transfermanager/AllowParallelCompositeUpload.java
@@ -18,33 +18,32 @@
package com.example.storage.transfermanager;
// [START storage_transfer_manager_upload_chunks_concurrently]
+
import com.google.cloud.storage.transfermanager.ParallelUploadConfig;
import com.google.cloud.storage.transfermanager.TransferManager;
import com.google.cloud.storage.transfermanager.TransferManagerConfig;
import com.google.cloud.storage.transfermanager.UploadResult;
-import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
class AllowParallelCompositeUpload {
public static void parallelCompositeUploadAllowed(String bucketName, List files)
- throws IOException {
- TransferManager transferManager =
- TransferManagerConfig.newBuilder()
- .setAllowParallelCompositeUpload(true)
- .build()
- .getService();
- ParallelUploadConfig parallelUploadConfig =
- ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();
- List results =
- transferManager.uploadFiles(files, parallelUploadConfig).getUploadResults();
- for (UploadResult result : results) {
- System.out.println(
- "Upload for "
- + result.getInput().getName()
- + " completed with status "
- + result.getStatus());
+ throws Exception {
+ TransferManagerConfig transferManagerConfig =
+ TransferManagerConfig.newBuilder().setAllowParallelCompositeUpload(true).build();
+ try (TransferManager transferManager = transferManagerConfig.getService()) {
+ ParallelUploadConfig parallelUploadConfig =
+ ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();
+ List results =
+ transferManager.uploadFiles(files, parallelUploadConfig).getUploadResults();
+ for (UploadResult result : results) {
+ System.out.println(
+ "Upload for "
+ + result.getInput().getName()
+ + " completed with status "
+ + result.getStatus());
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/transfermanager/DownloadBucket.java b/samples/snippets/src/main/java/com/example/storage/transfermanager/DownloadBucket.java
index b77a6fee67..5905480823 100644
--- a/samples/snippets/src/main/java/com/example/storage/transfermanager/DownloadBucket.java
+++ b/samples/snippets/src/main/java/com/example/storage/transfermanager/DownloadBucket.java
@@ -31,30 +31,36 @@
class DownloadBucket {
public static void downloadBucketContents(
- String projectId, String bucketName, Path destinationDirectory) {
- Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
- List blobs =
- storage
- .list(bucketName)
- .streamAll()
- .map(blob -> blob.asBlobInfo())
- .collect(Collectors.toList());
- TransferManager transferManager = TransferManagerConfig.newBuilder().build().getService();
- ParallelDownloadConfig parallelDownloadConfig =
- ParallelDownloadConfig.newBuilder()
- .setBucketName(bucketName)
- .setDownloadDirectory(destinationDirectory)
- .build();
+ String projectId, String bucketName, Path destinationDirectory) throws Exception {
+ StorageOptions storageOptions = StorageOptions.newBuilder().setProjectId(projectId).build();
+ List blobs;
+ try (Storage storage = storageOptions.getService()) {
+ blobs =
+ storage
+ .list(bucketName)
+ .streamAll()
+ .map(blob -> blob.asBlobInfo())
+ .collect(Collectors.toList());
+ }
+
+ TransferManagerConfig transferManagerConfig = TransferManagerConfig.newBuilder().build();
+ try (TransferManager transferManager = transferManagerConfig.getService()) {
+ ParallelDownloadConfig parallelDownloadConfig =
+ ParallelDownloadConfig.newBuilder()
+ .setBucketName(bucketName)
+ .setDownloadDirectory(destinationDirectory)
+ .build();
- List results =
- transferManager.downloadBlobs(blobs, parallelDownloadConfig).getDownloadResults();
+ List results =
+ transferManager.downloadBlobs(blobs, parallelDownloadConfig).getDownloadResults();
- for (DownloadResult result : results) {
- System.out.println(
- "Download of "
- + result.getInput().getName()
- + " completed with status "
- + result.getStatus());
+ for (DownloadResult result : results) {
+ System.out.println(
+ "Download of "
+ + result.getInput().getName()
+ + " completed with status "
+ + result.getStatus());
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/transfermanager/DownloadMany.java b/samples/snippets/src/main/java/com/example/storage/transfermanager/DownloadMany.java
index a79e18cdcf..3e30671067 100644
--- a/samples/snippets/src/main/java/com/example/storage/transfermanager/DownloadMany.java
+++ b/samples/snippets/src/main/java/com/example/storage/transfermanager/DownloadMany.java
@@ -30,8 +30,8 @@ class DownloadMany {
public static void downloadManyBlobs(
String bucketName, List blobs, Path destinationDirectory) throws Exception {
- try (TransferManager transferManager =
- TransferManagerConfig.newBuilder().build().getService()) {
+ TransferManagerConfig transferManagerConfig = TransferManagerConfig.newBuilder().build();
+ try (TransferManager transferManager = transferManagerConfig.getService()) {
ParallelDownloadConfig parallelDownloadConfig =
ParallelDownloadConfig.newBuilder()
.setBucketName(bucketName)
diff --git a/samples/snippets/src/main/java/com/example/storage/transfermanager/UploadDirectory.java b/samples/snippets/src/main/java/com/example/storage/transfermanager/UploadDirectory.java
index 0a14bec049..3145f2aead 100644
--- a/samples/snippets/src/main/java/com/example/storage/transfermanager/UploadDirectory.java
+++ b/samples/snippets/src/main/java/com/example/storage/transfermanager/UploadDirectory.java
@@ -17,11 +17,11 @@
package com.example.storage.transfermanager;
// [START storage_transfer_manager_upload_directory]
+
import com.google.cloud.storage.transfermanager.ParallelUploadConfig;
import com.google.cloud.storage.transfermanager.TransferManager;
import com.google.cloud.storage.transfermanager.TransferManagerConfig;
import com.google.cloud.storage.transfermanager.UploadResult;
-import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -31,26 +31,28 @@
class UploadDirectory {
public static void uploadDirectoryContents(String bucketName, Path sourceDirectory)
- throws IOException {
- TransferManager transferManager = TransferManagerConfig.newBuilder().build().getService();
- ParallelUploadConfig parallelUploadConfig =
- ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();
+ throws Exception {
+ TransferManagerConfig transferManagerConfig = TransferManagerConfig.newBuilder().build();
+ try (TransferManager transferManager = transferManagerConfig.getService()) {
+ ParallelUploadConfig parallelUploadConfig =
+ ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();
- // Create a list to store the file paths
- List filePaths = new ArrayList<>();
- // Get all files in the directory
- // try-with-resource to ensure pathStream is closed
- try (Stream pathStream = Files.walk(sourceDirectory)) {
- pathStream.filter(Files::isRegularFile).forEach(filePaths::add);
- }
- List results =
- transferManager.uploadFiles(filePaths, parallelUploadConfig).getUploadResults();
- for (UploadResult result : results) {
- System.out.println(
- "Upload for "
- + result.getInput().getName()
- + " completed with status "
- + result.getStatus());
+ // Create a list to store the file paths
+ List filePaths = new ArrayList<>();
+ // Get all files in the directory
+ // try-with-resource to ensure pathStream is closed
+ try (Stream pathStream = Files.walk(sourceDirectory)) {
+ pathStream.filter(Files::isRegularFile).forEach(filePaths::add);
+ }
+ List results =
+ transferManager.uploadFiles(filePaths, parallelUploadConfig).getUploadResults();
+ for (UploadResult result : results) {
+ System.out.println(
+ "Upload for "
+ + result.getInput().getName()
+ + " completed with status "
+ + result.getStatus());
+ }
}
}
}
diff --git a/samples/snippets/src/main/java/com/example/storage/transfermanager/UploadMany.java b/samples/snippets/src/main/java/com/example/storage/transfermanager/UploadMany.java
index b477f87bdd..8908e9fcad 100644
--- a/samples/snippets/src/main/java/com/example/storage/transfermanager/UploadMany.java
+++ b/samples/snippets/src/main/java/com/example/storage/transfermanager/UploadMany.java
@@ -21,24 +21,25 @@
import com.google.cloud.storage.transfermanager.TransferManager;
import com.google.cloud.storage.transfermanager.TransferManagerConfig;
import com.google.cloud.storage.transfermanager.UploadResult;
-import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
class UploadMany {
- public static void uploadManyFiles(String bucketName, List files) throws IOException {
- TransferManager transferManager = TransferManagerConfig.newBuilder().build().getService();
- ParallelUploadConfig parallelUploadConfig =
- ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();
- List results =
- transferManager.uploadFiles(files, parallelUploadConfig).getUploadResults();
- for (UploadResult result : results) {
- System.out.println(
- "Upload for "
- + result.getInput().getName()
- + " completed with status "
- + result.getStatus());
+ public static void uploadManyFiles(String bucketName, List files) throws Exception {
+ TransferManagerConfig transferManagerConfig = TransferManagerConfig.newBuilder().build();
+ try (TransferManager transferManager = transferManagerConfig.getService()) {
+ ParallelUploadConfig parallelUploadConfig =
+ ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();
+ List results =
+ transferManager.uploadFiles(files, parallelUploadConfig).getUploadResults();
+ for (UploadResult result : results) {
+ System.out.println(
+ "Upload for "
+ + result.getInput().getName()
+ + " completed with status "
+ + result.getStatus());
+ }
}
}
}
diff --git a/samples/snippets/src/test/java/com/example/storage/ConfigureRetriesTest.java b/samples/snippets/src/test/java/com/example/storage/ConfigureRetriesTest.java
index 8b40189b8e..80e3b1c98f 100644
--- a/samples/snippets/src/test/java/com/example/storage/ConfigureRetriesTest.java
+++ b/samples/snippets/src/test/java/com/example/storage/ConfigureRetriesTest.java
@@ -57,7 +57,7 @@ public void tearDown() throws Exception {
}
@Test
- public void testConfigureRetries() {
+ public void testConfigureRetries() throws Exception {
ConfigureRetries.deleteBlob(bucketName, blobName);
assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("Deletion");
assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("successfully");
diff --git a/samples/snippets/src/test/java/com/example/storage/ITBucketSnippets.java b/samples/snippets/src/test/java/com/example/storage/ITBucketSnippets.java
index 051bd05e23..de6785b2ae 100644
--- a/samples/snippets/src/test/java/com/example/storage/ITBucketSnippets.java
+++ b/samples/snippets/src/test/java/com/example/storage/ITBucketSnippets.java
@@ -159,7 +159,7 @@ public void after() throws Exception {
}
@Test
- public void testAddBucketLabel() {
+ public void testAddBucketLabel() throws Exception {
int oldSize = storage.get(BUCKET).getLabels().size();
AddBucketLabel.addBucketLabel(PROJECT_ID, BUCKET, "key", "value");
assertEquals(oldSize + 1, storage.get(BUCKET).getLabels().size());
@@ -177,7 +177,7 @@ public void testChangeDefaultStorageClass() throws Throwable {
}
@Test
- public void testCreateBucket() {
+ public void testCreateBucket() throws Exception {
String newBucket = RemoteStorageHelper.generateBucketName();
CreateBucket.createBucket(PROJECT_ID, newBucket);
try {
@@ -189,7 +189,7 @@ public void testCreateBucket() {
}
@Test
- public void testCreateBucketWithStorageClassAndLocation() {
+ public void testCreateBucketWithStorageClassAndLocation() throws Exception {
String newBucket = RemoteStorageHelper.generateBucketName();
CreateBucketWithStorageClassAndLocation.createBucketWithStorageClassAndLocation(
PROJECT_ID, newBucket);
@@ -211,13 +211,15 @@ public void testDeleteBucket() {
try {
DeleteBucket.deleteBucket(PROJECT_ID, newBucket);
assertNull(storage.get(newBucket));
+ } catch (Exception e) {
+ throw new RuntimeException(e);
} finally {
storage.delete(newBucket);
}
}
@Test
- public void testGetBucketMetadata() {
+ public void testGetBucketMetadata() throws Exception {
Bucket bucket =
storage.get(BUCKET, Storage.BucketGetOption.fields(Storage.BucketField.values()));
bucket =
@@ -262,14 +264,14 @@ public void testGetBucketMetadata() {
}
@Test
- public void testListBuckets() {
+ public void testListBuckets() throws Exception {
ListBuckets.listBuckets(PROJECT_ID);
String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String();
assertTrue(snippetOutput.contains(BUCKET));
}
@Test
- public void testRemoveBucketLabel() {
+ public void testRemoveBucketLabel() throws Exception {
storage.get(BUCKET).toBuilder().setLabels(ImmutableMap.of("k", "v")).build().update();
int oldSize = storage.get(BUCKET).getLabels().size();
RemoveBucketLabel.removeBucketLabel(PROJECT_ID, BUCKET, "k");
@@ -477,7 +479,7 @@ public void testSetBucketWebsiteInfo() throws Throwable {
}
@Test
- public void testSetClientEndpoint() {
+ public void testSetClientEndpoint() throws Exception {
SetClientEndpoint.setClientEndpoint(PROJECT_ID, "https://storage.googleapis.com");
String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String();
assertTrue(snippetOutput.contains("https://storage.googleapis.com"));
@@ -645,13 +647,15 @@ public void testLockRetentionPolicy() {
assertEquals(5L, (long) storage.get(tempBucket).getRetentionPeriod());
LockRetentionPolicy.lockRetentionPolicy(PROJECT_ID, tempBucket);
assertTrue(storage.get(tempBucket).retentionPolicyIsLocked());
+ } catch (Exception e) {
+ throw new RuntimeException(e);
} finally {
storage.delete(tempBucket);
}
}
@Test
- public void testUniformBucketLevelAccess() {
+ public void testUniformBucketLevelAccess() throws Exception {
EnableUniformBucketLevelAccess.enableUniformBucketLevelAccess(PROJECT_ID, BUCKET);
Bucket bucket = storage.get(BUCKET);
assertTrue(bucket.getIamConfiguration().isUniformBucketLevelAccessEnabled());
@@ -666,7 +670,7 @@ public void testUniformBucketLevelAccess() {
}
@Test
- public void testCreateBucketWithObjectRetention() {
+ public void testCreateBucketWithObjectRetention() throws Exception {
String tempBucket = RemoteStorageHelper.generateBucketName();
try {
@@ -680,7 +684,7 @@ public void testCreateBucketWithObjectRetention() {
}
@Test
- public void testSetSoftDeletePolicy() {
+ public void testSetSoftDeletePolicy() throws Exception {
String tempBucket = RemoteStorageHelper.generateBucketName();
Bucket bucket = storage.create(BucketInfo.of(tempBucket));
try {
@@ -696,7 +700,7 @@ public void testSetSoftDeletePolicy() {
}
@Test
- public void testDisableSoftDelete() {
+ public void testDisableSoftDelete() throws Exception {
String tempBucket = RemoteStorageHelper.generateBucketName();
Bucket bucket = storage.create(BucketInfo.of(tempBucket));
try {
diff --git a/samples/snippets/src/test/java/com/example/storage/ITHmacSnippets.java b/samples/snippets/src/test/java/com/example/storage/ITHmacSnippets.java
index 632142a618..6e6770d48b 100644
--- a/samples/snippets/src/test/java/com/example/storage/ITHmacSnippets.java
+++ b/samples/snippets/src/test/java/com/example/storage/ITHmacSnippets.java
@@ -111,7 +111,7 @@ public void testDeactivateHmacKey() throws Exception {
}
@Test
- public void testDeleteHmacKey() {
+ public void testDeleteHmacKey() throws Exception {
HmacKey hmacKey = storage.createHmacKey(ServiceAccount.of(HMAC_KEY_TEST_SERVICE_ACCOUNT));
HmacKeyMetadata metadata =
storage.updateHmacKeyState(hmacKey.getMetadata(), HmacKeyState.INACTIVE);
@@ -121,7 +121,7 @@ public void testDeleteHmacKey() {
}
@Test
- public void testListHmacKeys() {
+ public void testListHmacKeys() throws Exception {
// Create 2 HMAC keys
final HmacKey one =
storage.createHmacKey(
diff --git a/samples/snippets/src/test/java/com/example/storage/ITObjectSnippets.java b/samples/snippets/src/test/java/com/example/storage/ITObjectSnippets.java
index 28ceeb3081..a99600bb82 100644
--- a/samples/snippets/src/test/java/com/example/storage/ITObjectSnippets.java
+++ b/samples/snippets/src/test/java/com/example/storage/ITObjectSnippets.java
@@ -106,7 +106,7 @@ public class ITObjectSnippets extends TestBase {
@Inject public KmsFixture kmsFixture;
@Test
- public void testChangeObjectStorageClass() {
+ public void testChangeObjectStorageClass() throws Exception {
String objectName = generator.randomObjectName();
BlobInfo gen1 = storage.create(info(objectName), CONTENT, BlobTargetOption.doesNotExist());
Assert.assertNotEquals(StorageClass.COLDLINE, gen1.getStorageClass());
@@ -135,7 +135,7 @@ public void testCopyObject() throws Exception {
}
@Test
- public void testDeleteObject() {
+ public void testDeleteObject() throws Exception {
String blob = generator.randomObjectName();
storage.create(BlobInfo.newBuilder(BlobId.of(bucket.getName(), blob)).build());
assertNotNull(storage.get(bucket.getName(), blob));
@@ -158,7 +158,7 @@ public void testDownloadObject() throws Exception {
}
@Test
- public void testDownloadObjectIntoMemory() throws IOException {
+ public void testDownloadObjectIntoMemory() throws Exception {
String objectName = generator.randomObjectName();
storage.create(info(objectName), CONTENT, BlobTargetOption.doesNotExist());
DownloadObjectIntoMemory.downloadObjectIntoMemory(
@@ -195,7 +195,7 @@ public void testDownloadPublicObject() throws Exception {
}
@Test
- public void testGetObjectMetadata() {
+ public void testGetObjectMetadata() throws Exception {
String blobName = generator.randomObjectName();
BlobId blobId = BlobId.of(bucket.getName(), blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setMetadata(ImmutableMap.of("k", "v")).build();
@@ -236,7 +236,7 @@ public void testGetObjectMetadata() {
}
@Test
- public void testListObjects() {
+ public void testListObjects() throws Exception {
String name1 = generator.randomObjectName();
storage.create(info(name1), BlobTargetOption.doesNotExist());
ListObjects.listObjects(GOOGLE_CLOUD_PROJECT, bucket.getName());
@@ -245,7 +245,7 @@ public void testListObjects() {
}
@Test
- public void testListObjectsWithPrefix() {
+ public void testListObjectsWithPrefix() throws Exception {
String prefix = generator.randomObjectName();
storage.create(BlobInfo.newBuilder(bucket.getName(), prefix + "a/1.txt").build());
storage.create(BlobInfo.newBuilder(bucket.getName(), prefix + "a/b/2.txt").build());
@@ -278,7 +278,7 @@ public void testCopyDeleteObject() throws Exception {
}
@Test
- public void testAtomicMoveObject() {
+ public void testAtomicMoveObject() throws Exception {
String blob1 = generator.randomObjectName();
String blob2 = generator.randomObjectName();
@@ -291,7 +291,7 @@ public void testAtomicMoveObject() {
}
@Test
- public void testSetObjectMetadata() {
+ public void testSetObjectMetadata() throws Exception {
String bucketName = bucket.getName();
String name1 = generator.randomObjectName();
BlobInfo b1Gen1 = storage.create(BlobInfo.newBuilder(bucketName, name1).build());
@@ -312,11 +312,13 @@ public void testUploadObject() throws IOException {
byte[] expected = Files.readAllBytes(file1.getPath());
byte[] actual = storage.readAllBytes(bucket.getName(), objectName);
assertArrayEquals(expected, actual);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
}
}
@Test
- public void testUploadObjectFromMemory() throws IOException {
+ public void testUploadObjectFromMemory() throws Exception {
String objectName = "uploadobjectfrommemorytest";
UploadObjectFromMemory.uploadObjectFromMemory(
GOOGLE_CLOUD_PROJECT, bucket.getName(), objectName, STRING_CONTENT);
@@ -325,7 +327,7 @@ public void testUploadObjectFromMemory() throws IOException {
}
@Test
- public void testObjectCSEKOperations() throws IOException {
+ public void testObjectCSEKOperations() throws Exception {
GenerateEncryptionKey.generateEncryptionKey();
String snippetOutput = stdOut.getCapturedOutputAsUtf8String();
String encryptionKey = snippetOutput.split(": ")[1].trim();
@@ -408,7 +410,7 @@ public void testObjectVersioningOperations() throws Exception {
}
@Test
- public void testV4SignedURLs() throws IOException {
+ public void testV4SignedURLs() throws Exception {
String tempObject = "test-upload-signed-url-object";
GenerateV4PutObjectSignedUrl.generateV4PutObjectSignedUrl(
GOOGLE_CLOUD_PROJECT, bucket.getName(), tempObject);
@@ -437,7 +439,7 @@ public void testV4SignedURLs() throws IOException {
}
@Test
- public void testMakeObjectPublic() {
+ public void testMakeObjectPublic() throws Exception {
String aclBlob = generator.randomObjectName();
assertNull(
storage
@@ -448,7 +450,7 @@ public void testMakeObjectPublic() {
}
@Test
- public void testComposeObject() {
+ public void testComposeObject() throws Exception {
String firstObject = generator.randomObjectName();
String secondObject = generator.randomObjectName();
String targetObject = generator.randomObjectName();
@@ -484,7 +486,7 @@ public void testStreamUploadDownload() throws Exception {
}
@Test
- public void testUploadKMSEncryptedObject() {
+ public void testUploadKMSEncryptedObject() throws Exception {
String blobName = generator.randomObjectName();
UploadKmsEncryptedObject.uploadKmsEncryptedObject(
GOOGLE_CLOUD_PROJECT, bucket.getName(), blobName, kmsFixture.getKey1().getName());
@@ -492,7 +494,7 @@ public void testUploadKMSEncryptedObject() {
}
@Test
- public void testBatchSetObjectMetadata() {
+ public void testBatchSetObjectMetadata() throws Exception {
String prefix = generator.randomObjectName();
String name1 = prefix + "/1.txt";
String name2 = prefix + "/2.txt";
@@ -511,7 +513,7 @@ public void testBatchSetObjectMetadata() {
}
@Test
- public void testSetObjectRetentionPolicy() {
+ public void testSetObjectRetentionPolicy() throws Exception {
BucketInfo bucketInfo = BucketInfo.newBuilder(generator.randomBucketName()).build();
Bucket tmpBucket = storage.create(bucketInfo, BucketTargetOption.enableObjectRetention(true));
String tempBucket = tmpBucket.getName();
diff --git a/samples/snippets/src/test/java/com/example/storage/ITStorageSnippets.java b/samples/snippets/src/test/java/com/example/storage/ITStorageSnippets.java
index 805eef2f2c..5759ce3e40 100644
--- a/samples/snippets/src/test/java/com/example/storage/ITStorageSnippets.java
+++ b/samples/snippets/src/test/java/com/example/storage/ITStorageSnippets.java
@@ -70,7 +70,7 @@ public static void afterClass() throws Exception {
}
@Test
- public void testGetServiceAccount() {
+ public void testGetServiceAccount() throws Exception {
GetServiceAccount.getServiceAccount(PROJECT_ID);
String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String();
diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketDualRegionTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketDualRegionTest.java
index 9b1ce9c74e..cf264f6ccc 100644
--- a/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketDualRegionTest.java
+++ b/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketDualRegionTest.java
@@ -27,7 +27,7 @@
public class CreateBucketDualRegionTest extends TestBase {
@Test
- public void testCreateBucketDualRegion() {
+ public void testCreateBucketDualRegion() throws Exception {
assertNotNull("Unable to determine Project ID", GOOGLE_CLOUD_PROJECT);
String newBucket = RemoteStorageHelper.generateBucketName();
CreateBucketDualRegion.createBucketDualRegion(
diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/PubSubNotificationTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/PubSubNotificationTest.java
index 3cccbaa10a..524d9e81d3 100644
--- a/samples/snippets/src/test/java/com/example/storage/bucket/PubSubNotificationTest.java
+++ b/samples/snippets/src/test/java/com/example/storage/bucket/PubSubNotificationTest.java
@@ -110,7 +110,7 @@ public void tearDown() {
}
@Test
- public void testCreateBucketPubSubNotification() {
+ public void testCreateBucketPubSubNotification() throws Exception {
CreateBucketPubSubNotification.createBucketPubSubNotification(
bucketName,
topic,
@@ -122,7 +122,7 @@ public void testCreateBucketPubSubNotification() {
}
@Test
- public void testDeleteBucketPubSubNotification() {
+ public void testDeleteBucketPubSubNotification() throws Exception {
Notification notification = storage.createNotification(bucketName, notificationInfo);
DeleteBucketPubSubNotification.deleteBucketPubSubNotification(
bucketName, notification.getNotificationId());
@@ -131,7 +131,7 @@ public void testDeleteBucketPubSubNotification() {
}
@Test
- public void testNotificationNotFound() {
+ public void testNotificationNotFound() throws Exception {
Notification notification = storage.createNotification(bucketName, notificationInfo);
// Do a delete first.
storage.deleteNotification(bucketName, notification.getNotificationId());
@@ -142,14 +142,14 @@ public void testNotificationNotFound() {
}
@Test
- public void testListBucketPubSubNotification() {
+ public void testListBucketPubSubNotification() throws Exception {
storage.createNotification(bucketName, notificationInfo);
ListPubSubNotifications.listPubSubNotifications(bucketName);
assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(topic);
}
@Test
- public void testPrintBucketPubSubNotification() {
+ public void testPrintBucketPubSubNotification() throws Exception {
Notification notification = storage.createNotification(bucketName, notificationInfo);
PrintPubSubNotification.printPubSubNotification(bucketName, notification.getNotificationId());
assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(topic);
diff --git a/samples/snippets/src/test/java/com/example/storage/object/AddBlobOwnerTest.java b/samples/snippets/src/test/java/com/example/storage/object/AddBlobOwnerTest.java
index 09d3c76e53..357b8e6546 100644
--- a/samples/snippets/src/test/java/com/example/storage/object/AddBlobOwnerTest.java
+++ b/samples/snippets/src/test/java/com/example/storage/object/AddBlobOwnerTest.java
@@ -30,7 +30,7 @@
public class AddBlobOwnerTest extends TestBase {
@Test
- public void testAddBlobOwner() {
+ public void testAddBlobOwner() throws Exception {
// Check for user email before the actual test.
assertWithMessage("Unable to determine user email").that(IT_SERVICE_ACCOUNT_EMAIL).isNotEmpty();
diff --git a/samples/snippets/src/test/java/com/example/storage/object/DownloadBytesRangeTest.java b/samples/snippets/src/test/java/com/example/storage/object/DownloadBytesRangeTest.java
index 5ad25abe01..05c8ac6674 100644
--- a/samples/snippets/src/test/java/com/example/storage/object/DownloadBytesRangeTest.java
+++ b/samples/snippets/src/test/java/com/example/storage/object/DownloadBytesRangeTest.java
@@ -24,7 +24,6 @@
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage.BlobTargetOption;
import java.io.File;
-import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
@@ -37,7 +36,7 @@ public class DownloadBytesRangeTest extends TestBase {
@Rule public final TemporaryFolder tmp = new TemporaryFolder();
@Test
- public void testDownloadByteRange() throws IOException {
+ public void testDownloadByteRange() throws Exception {
byte[] bytes = { // 18 elements per row
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
diff --git a/samples/snippets/src/test/java/com/example/storage/object/PrintBlobAclTest.java b/samples/snippets/src/test/java/com/example/storage/object/PrintBlobAclTest.java
index 04eb9e65bd..96ef12b261 100644
--- a/samples/snippets/src/test/java/com/example/storage/object/PrintBlobAclTest.java
+++ b/samples/snippets/src/test/java/com/example/storage/object/PrintBlobAclTest.java
@@ -33,7 +33,7 @@ public class PrintBlobAclTest extends TestBase {
public static final String IT_SERVICE_ACCOUNT_EMAIL = Env.IT_SERVICE_ACCOUNT_EMAIL;
@Test
- public void testPrintBlobAcls() {
+ public void testPrintBlobAcls() throws Exception {
// Check for user email before the actual test.
assertWithMessage("Unable to determine user email").that(IT_SERVICE_ACCOUNT_EMAIL).isNotEmpty();
diff --git a/samples/snippets/src/test/java/com/example/storage/object/RemoveBlobOwnerTest.java b/samples/snippets/src/test/java/com/example/storage/object/RemoveBlobOwnerTest.java
index 325054041a..a9aa00856a 100644
--- a/samples/snippets/src/test/java/com/example/storage/object/RemoveBlobOwnerTest.java
+++ b/samples/snippets/src/test/java/com/example/storage/object/RemoveBlobOwnerTest.java
@@ -32,7 +32,7 @@
public class RemoveBlobOwnerTest extends TestBase {
@Test
- public void testRemoveBlobOwner() {
+ public void testRemoveBlobOwner() throws Exception {
// Check for user email before the actual test.
assertWithMessage("Unable to determine user email").that(IT_SERVICE_ACCOUNT_EMAIL).isNotEmpty();
@@ -50,7 +50,7 @@ public void testRemoveBlobOwner() {
}
@Test
- public void testUserNotFound() {
+ public void testUserNotFound() throws Exception {
// Check for user email before the actual test.
assertWithMessage("Unable to determine user email").that(IT_SERVICE_ACCOUNT_EMAIL).isNotEmpty();
diff --git a/samples/snippets/src/test/java/com/example/storage/transfermanager/ITTransferManagerSamples.java b/samples/snippets/src/test/java/com/example/storage/transfermanager/ITTransferManagerSamples.java
index 97fb2cea9c..93d56339dd 100644
--- a/samples/snippets/src/test/java/com/example/storage/transfermanager/ITTransferManagerSamples.java
+++ b/samples/snippets/src/test/java/com/example/storage/transfermanager/ITTransferManagerSamples.java
@@ -29,7 +29,6 @@
import com.google.cloud.storage.TmpFile;
import com.google.cloud.storage.it.TemporaryBucket;
import com.google.common.collect.ImmutableList;
-import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
@@ -119,7 +118,7 @@ public void downloadBlobs() throws Exception {
}
@Test
- public void uploadAllowPCU() throws IOException {
+ public void uploadAllowPCU() throws Exception {
Path baseDir = uploadDirectory.getRoot().toPath();
try (TmpFile file1 = DataGenerator.base64Characters().tempFile(baseDir, 313 * 1024 * 1024)) {
AllowParallelCompositeUpload.parallelCompositeUploadAllowed(