@InternalExtensionOnly public interface Storage extends com.google.cloud.Service<StorageOptions>, AutoCloseable
Modifier and Type | Interface and Description |
---|---|
static class |
Storage.BlobField |
static class |
Storage.BlobGetOption
Class for specifying blob get options.
|
static class |
Storage.BlobListOption
Class for specifying blob list options.
|
static class |
Storage.BlobSourceOption
Class for specifying blob source options.
|
static class |
Storage.BlobTargetOption
Class for specifying blob target options.
|
static class |
Storage.BlobWriteOption
Class for specifying blob write options.
|
static class |
Storage.BucketField |
static class |
Storage.BucketGetOption
Class for specifying bucket get options.
|
static class |
Storage.BucketListOption
Class for specifying bucket list options.
|
static class |
Storage.BucketSourceOption
Class for specifying bucket source options.
|
static class |
Storage.BucketTargetOption
Class for specifying bucket target options.
|
static class |
Storage.ComposeRequest
A class to contain all information needed for a Google Cloud Storage Compose operation.
|
static class |
Storage.CopyRequest
A class to contain all information needed for a Google Cloud Storage Copy operation.
|
static class |
Storage.CreateHmacKeyOption
Class for specifying createHmacKey options
|
static class |
Storage.DeleteHmacKeyOption
Class for specifying deleteHmacKey options
|
static class |
Storage.GetHmacKeyOption
Class for specifying getHmacKey options
|
static class |
Storage.ListHmacKeysOption
Class for specifying listHmacKeys options
|
static class |
Storage.PostPolicyV4Option
Class for specifying Post Policy V4 options.
|
static class |
Storage.PredefinedAcl |
static class |
Storage.SignUrlOption
Class for specifying signed URL options.
|
static class |
Storage.UpdateHmacKeyOption
Class for specifying updateHmacKey options
|
static class |
Storage.UriScheme |
Modifier and Type | Method and Description |
---|---|
StorageBatch |
batch()
Creates a new empty batch for grouping multiple service calls in one underlying RPC call.
|
default void |
close() |
Blob |
compose(Storage.ComposeRequest composeRequest)
Sends a compose request.
|
CopyWriter |
copy(Storage.CopyRequest copyRequest)
Sends a copy request.
|
Blob |
create(BlobInfo blobInfo,
byte[] content,
int offset,
int length,
Storage.BlobTargetOption... options)
Creates a new blob with the sub array of the given byte array.
|
Blob |
create(BlobInfo blobInfo,
byte[] content,
Storage.BlobTargetOption... options)
Creates a new blob.
|
Blob |
create(BlobInfo blobInfo,
InputStream content,
Storage.BlobWriteOption... options)
Deprecated.
|
Blob |
create(BlobInfo blobInfo,
Storage.BlobTargetOption... options)
Creates a new blob with no content.
|
Bucket |
create(BucketInfo bucketInfo,
Storage.BucketTargetOption... options)
Creates a new bucket.
|
Acl |
createAcl(BlobId blob,
Acl acl)
Creates a new ACL entry on the specified blob.
|
Acl |
createAcl(String bucket,
Acl acl) |
Acl |
createAcl(String bucket,
Acl acl,
Storage.BucketSourceOption... options)
Creates a new ACL entry on the specified bucket.
|
Acl |
createDefaultAcl(String bucket,
Acl acl)
Creates a new default blob ACL entry on the specified bucket.
|
Blob |
createFrom(BlobInfo blobInfo,
InputStream content,
int bufferSize,
Storage.BlobWriteOption... options)
Reads bytes from an input stream and uploads those bytes to the blob using
writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...) and
bufferSize . |
Blob |
createFrom(BlobInfo blobInfo,
InputStream content,
Storage.BlobWriteOption... options)
Reads bytes from an input stream and uploads those bytes to the blob using
writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...) . |
Blob |
createFrom(BlobInfo blobInfo,
Path path,
int bufferSize,
Storage.BlobWriteOption... options)
Uploads
path to the blob using writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...) and bufferSize . |
Blob |
createFrom(BlobInfo blobInfo,
Path path,
Storage.BlobWriteOption... options)
Uploads
path to the blob using writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...) . |
HmacKey |
createHmacKey(ServiceAccount serviceAccount,
Storage.CreateHmacKeyOption... options)
Creates a new HMAC Key for the provided service account, including the secret key.
|
Notification |
createNotification(String bucket,
NotificationInfo notificationInfo)
Creates the notification for a given bucket.
|
List<Boolean> |
delete(BlobId... blobIds)
Deletes the requested blobs.
|
boolean |
delete(BlobId blob)
Deletes the requested blob.
|
boolean |
delete(BlobId blob,
Storage.BlobSourceOption... options)
Deletes the requested blob.
|
List<Boolean> |
delete(Iterable<BlobId> blobIds)
Deletes the requested blobs.
|
boolean |
delete(String bucket,
Storage.BucketSourceOption... options)
Deletes the requested bucket.
|
boolean |
delete(String bucket,
String blob,
Storage.BlobSourceOption... options)
Deletes the requested blob.
|
boolean |
deleteAcl(BlobId blob,
Acl.Entity entity)
Deletes the ACL entry for the specified entity on the specified blob.
|
boolean |
deleteAcl(String bucket,
Acl.Entity entity) |
boolean |
deleteAcl(String bucket,
Acl.Entity entity,
Storage.BucketSourceOption... options)
Deletes the ACL entry for the specified entity on the specified bucket.
|
boolean |
deleteDefaultAcl(String bucket,
Acl.Entity entity)
Deletes the default object ACL entry for the specified entity on the specified bucket.
|
void |
deleteHmacKey(HmacKey.HmacKeyMetadata hmacKeyMetadata,
Storage.DeleteHmacKeyOption... options)
Deletes an HMAC key.
|
boolean |
deleteNotification(String bucket,
String notificationId)
Deletes the notification with the specified id.
|
void |
downloadTo(BlobId blob,
OutputStream outputStream,
Storage.BlobSourceOption... options)
Downloads the given blob to the given output stream using specified blob read options.
|
void |
downloadTo(BlobId blob,
Path path,
Storage.BlobSourceOption... options)
Downloads the given blob to the given path using specified blob read options.
|
PostPolicyV4 |
generateSignedPostPolicyV4(BlobInfo blobInfo,
long duration,
TimeUnit unit,
PostPolicyV4.PostConditionsV4 conditions,
Storage.PostPolicyV4Option... options)
Generates a presigned post policy without any fields.
|
PostPolicyV4 |
generateSignedPostPolicyV4(BlobInfo blobInfo,
long duration,
TimeUnit unit,
PostPolicyV4.PostFieldsV4 fields,
PostPolicyV4.PostConditionsV4 conditions,
Storage.PostPolicyV4Option... options)
Generates a URL and a map of fields that can be specified in an HTML form to submit a POST
request.
|
PostPolicyV4 |
generateSignedPostPolicyV4(BlobInfo blobInfo,
long duration,
TimeUnit unit,
PostPolicyV4.PostFieldsV4 fields,
Storage.PostPolicyV4Option... options)
Generates a presigned post policy without any conditions.
|
PostPolicyV4 |
generateSignedPostPolicyV4(BlobInfo blobInfo,
long duration,
TimeUnit unit,
Storage.PostPolicyV4Option... options)
Generates a presigned post policy without any fields or conditions.
|
List<Blob> |
get(BlobId... blobIds)
Gets the requested blobs.
|
Blob |
get(BlobId blob)
Returns the requested blob or
null if not found. |
Blob |
get(BlobId blob,
Storage.BlobGetOption... options)
Returns the requested blob or
null if not found. |
List<Blob> |
get(Iterable<BlobId> blobIds)
Gets the requested blobs.
|
Bucket |
get(String bucket,
Storage.BucketGetOption... options)
Returns the requested bucket or
null if not found. |
Blob |
get(String bucket,
String blob,
Storage.BlobGetOption... options)
Returns the requested blob or
null if not found. |
Acl |
getAcl(BlobId blob,
Acl.Entity entity)
Returns the ACL entry for the specified entity on the specified blob or
null if not
found. |
Acl |
getAcl(String bucket,
Acl.Entity entity) |
Acl |
getAcl(String bucket,
Acl.Entity entity,
Storage.BucketSourceOption... options)
Returns the ACL entry for the specified entity on the specified bucket or
null if not
found. |
Acl |
getDefaultAcl(String bucket,
Acl.Entity entity)
Returns the default object ACL entry for the specified entity on the specified bucket or
null if not found. |
HmacKey.HmacKeyMetadata |
getHmacKey(String accessId,
Storage.GetHmacKeyOption... options)
Gets an HMAC key given its access id.
|
com.google.cloud.Policy |
getIamPolicy(String bucket,
Storage.BucketSourceOption... options)
Gets the IAM policy for the provided bucket.
|
Notification |
getNotification(String bucket,
String notificationId)
Gets the notification with the specified id.
|
ServiceAccount |
getServiceAccount(String projectId)
Returns the service account associated with the given project.
|
com.google.api.gax.paging.Page<Bucket> |
list(Storage.BucketListOption... options)
Lists the project's buckets.
|
com.google.api.gax.paging.Page<Blob> |
list(String bucket,
Storage.BlobListOption... options)
Lists the bucket's blobs.
|
List<Acl> |
listAcls(BlobId blob)
Lists the ACL entries for the provided blob.
|
List<Acl> |
listAcls(String bucket) |
List<Acl> |
listAcls(String bucket,
Storage.BucketSourceOption... options)
Lists the ACL entries for the provided bucket.
|
List<Acl> |
listDefaultAcls(String bucket)
Lists the default blob ACL entries for the provided bucket.
|
com.google.api.gax.paging.Page<HmacKey.HmacKeyMetadata> |
listHmacKeys(Storage.ListHmacKeysOption... options)
Lists HMAC keys for a given service account.
|
List<Notification> |
listNotifications(String bucket)
Retrieves the list of notifications associated with the bucket.
|
Bucket |
lockRetentionPolicy(BucketInfo bucket,
Storage.BucketTargetOption... options)
Locks bucket retention policy.
|
byte[] |
readAllBytes(BlobId blob,
Storage.BlobSourceOption... options)
Reads all the bytes from a blob.
|
byte[] |
readAllBytes(String bucket,
String blob,
Storage.BlobSourceOption... options)
Reads all the bytes from a blob.
|
com.google.cloud.ReadChannel |
reader(BlobId blob,
Storage.BlobSourceOption... options)
Returns a channel for reading the blob's content.
|
com.google.cloud.ReadChannel |
reader(String bucket,
String blob,
Storage.BlobSourceOption... options)
Returns a channel for reading the blob's content.
|
com.google.cloud.Policy |
setIamPolicy(String bucket,
com.google.cloud.Policy policy,
Storage.BucketSourceOption... options)
Updates the IAM policy on the specified bucket.
|
URL |
signUrl(BlobInfo blobInfo,
long duration,
TimeUnit unit,
Storage.SignUrlOption... options)
Generates a signed URL for a blob.
|
List<Boolean> |
testIamPermissions(String bucket,
List<String> permissions,
Storage.BucketSourceOption... options)
Tests whether the caller holds the permissions on the specified bucket.
|
List<Blob> |
update(BlobInfo... blobInfos)
Updates the requested blobs.
|
Blob |
update(BlobInfo blobInfo)
Updates the properties of the blob.
|
Blob |
update(BlobInfo blobInfo,
Storage.BlobTargetOption... options)
Updates the blob properties if the preconditions specified by
options are met. |
Bucket |
update(BucketInfo bucketInfo,
Storage.BucketTargetOption... options)
Updates bucket information.
|
List<Blob> |
update(Iterable<BlobInfo> blobInfos)
Updates the requested blobs.
|
Acl |
updateAcl(BlobId blob,
Acl acl)
Updates an ACL entry on the specified blob.
|
Acl |
updateAcl(String bucket,
Acl acl) |
Acl |
updateAcl(String bucket,
Acl acl,
Storage.BucketSourceOption... options)
Updates an ACL entry on the specified bucket.
|
Acl |
updateDefaultAcl(String bucket,
Acl acl)
Updates a default blob ACL entry on the specified bucket.
|
HmacKey.HmacKeyMetadata |
updateHmacKeyState(HmacKey.HmacKeyMetadata hmacKeyMetadata,
HmacKey.HmacKeyState state,
Storage.UpdateHmacKeyOption... options)
Updates the state of an HMAC key and returns the updated metadata.
|
com.google.cloud.WriteChannel |
writer(BlobInfo blobInfo,
Storage.BlobWriteOption... options)
Creates a blob and returns a channel for writing its content.
|
com.google.cloud.WriteChannel |
writer(URL signedURL)
Accepts signed URL and return a channel for writing content.
|
@TransportCompatibility(value={HTTP,GRPC}) Bucket create(BucketInfo bucketInfo, Storage.BucketTargetOption... options)
Accepts an optional userProject Storage.BucketTargetOption
option which defines the project
id to assign operational costs.
Example of creating a bucket.
String bucketName = "my-unique-bucket";
Bucket bucket = storage.create(BucketInfo.of(bucketName));
Example of creating a bucket with storage class and location.
String bucketName = "my-unique-bucket";
Bucket bucket = storage.create(BucketInfo.newBuilder(bucketName)
// See here for possible values: http://g.co/cloud/storage/docs/storage-classes
.setStorageClass(StorageClass.COLDLINE)
// Possible values: http://g.co/cloud/storage/docs/bucket-locations#location-mr
.setLocation("asia")
.build());
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Blob create(BlobInfo blobInfo, Storage.BlobTargetOption... options)
Example of creating a blob with no content.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo);
Blob
with complete informationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Blob create(BlobInfo blobInfo, byte[] content, Storage.BlobTargetOption... options)
content
. For large content, writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...)
is recommended as it uses resumable upload. MD5 and CRC32C hashes of content
are computed and used for validating transferred data. Accepts an optional userProject Storage.BlobGetOption
option which defines the project id to assign operational costs. The content
type is detected from the blob name if not explicitly set. Note that all non-editable metadata, such as
generation or metageneration, will be ignored even if it's present in the provided BlobInfo
object.
Example of creating a blob from a byte array:
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, World!".getBytes(UTF_8));
Blob
with complete informationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Blob create(BlobInfo blobInfo, byte[] content, int offset, int length, Storage.BlobTargetOption... options)
content
. For large content, writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...)
is recommended as it uses resumable upload.
MD5 and CRC32C hashes of content
are computed and used for validating transferred data.
Accepts a userProject Storage.BlobGetOption
option, which defines the project id to assign
operational costs. Note that all non-editable metadata, such as
generation or metageneration, will be ignored even if it's present in the provided BlobInfo
object.
Example of creating a blob from a byte array:
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, World!".getBytes(UTF_8), 7, 5);
Blob
with complete informationStorageException
- upon failure@Deprecated @TransportCompatibility(value={HTTP,GRPC}) Blob create(BlobInfo blobInfo, InputStream content, Storage.BlobWriteOption... options)
content
. For large content, writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...)
is recommended as it uses resumable upload. By default any MD5 and CRC32C values in
the given blobInfo
are ignored unless requested via the BlobWriteOption.md5Match
and BlobWriteOption.crc32cMatch
options. The given input
stream is closed upon success. Note that all non-editable metadata, such as
generation or metageneration, will be ignored even if it's present in the provided BlobInfo
object.
This method is marked as Deprecated
because it cannot safely retry, given that it
accepts an InputStream
which can only be consumed once.
Example of creating a blob from an input stream.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
InputStream content = new ByteArrayInputStream("Hello, World!".getBytes(UTF_8));
BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, content);
Example of uploading an encrypted blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
String encryptionKey = "my_encryption_key";
InputStream content = new ByteArrayInputStream("Hello, World!".getBytes(UTF_8));
BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId)
.setContentType("text/plain")
.build();
Blob blob = storage.create(blobInfo, content, BlobWriteOption.encryptionKey(encryptionKey));
Blob
with complete informationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Blob createFrom(BlobInfo blobInfo, Path path, Storage.BlobWriteOption... options) throws IOException
path
to the blob using writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...)
. By default any MD5 and CRC32C values in
the given blobInfo
are ignored unless requested via the Storage.BlobWriteOption.md5Match()
and Storage.BlobWriteOption.crc32cMatch()
options. Folder upload is
not supported. Note that all
non-editable metadata, such as generation or metageneration, will be ignored even if it's
present in the provided BlobInfo object.
Example of uploading a file:
String bucketName = "my-unique-bucket";
String fileName = "readme.txt";
BlobId blobId = BlobId.of(bucketName, fileName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
storage.createFrom(blobInfo, Paths.get(fileName));
blobInfo
- blob to createpath
- file to uploadoptions
- blob write optionsBlob
with complete informationIOException
- on I/O errorStorageException
- on server side errorcreateFrom(BlobInfo, Path, int, BlobWriteOption...)
@TransportCompatibility(value={HTTP,GRPC}) Blob createFrom(BlobInfo blobInfo, Path path, int bufferSize, Storage.BlobWriteOption... options) throws IOException
path
to the blob using writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...)
and bufferSize
. By default any
MD5 and CRC32C values in the given blobInfo
are ignored unless requested via the Storage.BlobWriteOption.md5Match()
and Storage.BlobWriteOption.crc32cMatch()
options. Folder upload is
not supported. Note that all
non-editable metadata, such as generation or metageneration, will be ignored even if it's
present in the provided BlobInfo object.
createFrom(BlobInfo, Path, BlobWriteOption...)
invokes this method with a buffer
size of 15 MiB. Users can pass alternative values. Larger buffer sizes might improve the upload
performance but require more memory. This can cause an OutOfMemoryError or add significant
garbage collection overhead. Smaller buffer sizes reduce memory consumption, that is noticeable
when uploading many objects in parallel. Buffer sizes less than 256 KiB are treated as 256 KiB.
Example of uploading a humongous file:
BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("video/webm").build();
int largeBufferSize = 150 * 1024 * 1024;
Path file = Paths.get("humongous.file");
storage.createFrom(blobInfo, file, largeBufferSize);
blobInfo
- blob to createpath
- file to uploadbufferSize
- size of the buffer I/O operationsoptions
- blob write optionsBlob
with complete informationIOException
- on I/O errorStorageException
- on server side error@TransportCompatibility(value={HTTP,GRPC}) Blob createFrom(BlobInfo blobInfo, InputStream content, Storage.BlobWriteOption... options) throws IOException
writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...)
. By
default any MD5 and CRC32C values in the given blobInfo
are ignored unless requested
via the Storage.BlobWriteOption.md5Match()
and Storage.BlobWriteOption.crc32cMatch()
options.
Note that all non-editable
metadata, such as generation or metageneration, will be ignored even if it's present in the
provided BlobInfo object.
Example of uploading data with CRC32C checksum:
BlobId blobId = BlobId.of(bucketName, blobName);
byte[] content = "Hello, world".getBytes(StandardCharsets.UTF_8);
Hasher hasher = Hashing.crc32c().newHasher().putBytes(content);
String crc32c = BaseEncoding.base64().encode(Ints.toByteArray(hasher.hash().asInt()));
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setCrc32c(crc32c).build();
storage.createFrom(blobInfo, new ByteArrayInputStream(content), Storage.BlobWriteOption.crc32cMatch());
blobInfo
- blob to createcontent
- input stream to read fromoptions
- blob write optionsBlob
with complete informationIOException
- on I/O errorStorageException
- on server side errorcreateFrom(BlobInfo, InputStream, int, BlobWriteOption...)
@TransportCompatibility(value={HTTP,GRPC}) Blob createFrom(BlobInfo blobInfo, InputStream content, int bufferSize, Storage.BlobWriteOption... options) throws IOException
writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...)
and
bufferSize
. By default any MD5 and CRC32C values in the given blobInfo
are
ignored unless requested via the Storage.BlobWriteOption.md5Match()
and Storage.BlobWriteOption.crc32cMatch()
options. Note that all non-editable metadata, such as
generation or metageneration, will be ignored even if it's present in the provided BlobInfo
object.
createFrom(BlobInfo, InputStream, BlobWriteOption...)
)} invokes this method with a
buffer size of 15 MiB. Users can pass alternative values. Larger buffer sizes might improve the
upload performance but require more memory. This can cause an OutOfMemoryError or add
significant garbage collection overhead. Smaller buffer sizes reduce memory consumption, that
is noticeable when uploading many objects in parallel. Buffer sizes less than 256 KiB are
treated as 256 KiB.
blobInfo
- blob to createcontent
- input stream to read frombufferSize
- size of the buffer I/O operationsoptions
- blob write optionsBlob
with complete informationIOException
- on I/O errorStorageException
- on server side error@TransportCompatibility(value={HTTP,GRPC}) Bucket get(String bucket, Storage.BucketGetOption... options)
null
if not found.
Accepts an optional userProject Storage.BucketGetOption
option which defines the project id
to assign operational costs.
Example of getting information on a bucket, only if its metageneration matches a value,
otherwise a StorageException
is thrown.
String bucketName = "my-unique-bucket";
long bucketMetageneration = 42;
Bucket bucket = storage.get(bucketName,
BucketGetOption.metagenerationMatch(bucketMetageneration));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Bucket lockRetentionPolicy(BucketInfo bucket, Storage.BucketTargetOption... options)
Accepts an optional userProject Storage.BucketTargetOption
option which defines the project
id to assign operational costs.
Warning: Once a retention policy is locked, it can't be unlocked, removed, or shortened.
Example of locking a retention policy on a bucket, only if its local metageneration value
matches the bucket's service metageneration otherwise a StorageException
is thrown.
String bucketName = "my-unique-bucket";
Bucket bucket = storage.get(bucketName, BucketGetOption.fields(BucketField.METAGENERATION));
storage.lockRetentionPolicy(bucket, BucketTargetOption.metagenerationMatch());
Bucket
object of the locked bucketStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Blob get(String bucket, String blob, Storage.BlobGetOption... options)
null
if not found.
Accepts an optional userProject Storage.BlobGetOption
option which defines the project id to
assign operational costs.
Example of getting information on a blob, only if its metageneration matches a value,
otherwise a StorageException
is thrown.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobMetageneration = 42;
Blob blob = storage.get(bucketName, blobName,
BlobGetOption.metagenerationMatch(blobMetageneration));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Blob get(BlobId blob, Storage.BlobGetOption... options)
null
if not found.
Accepts an optional userProject Storage.BlobGetOption
option which defines the project id to
assign operational costs.
Example of getting information on a blob, only if its metageneration matches a value,
otherwise a StorageException
is thrown.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobMetageneration = 42;
BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.get(blobId, BlobGetOption.metagenerationMatch(blobMetageneration));
Example of getting information on a blob encrypted using Customer Supplied Encryption Keys,
only if supplied Decrpytion Key decrypts the blob successfully, otherwise a StorageException
is thrown. For more information review
StorageException
- upon failure{@code String bucketName = "my-unique-bucket"; String blobName = "my-blob-name"; String blobEncryptionKey = ""; BlobId blobId = BlobId.of(bucketName, blobName); Blob blob = storage.get(blobId, BlobGetOption.decryptionKey(blobEncryptionKey)); }
@TransportCompatibility(value={HTTP,GRPC}) Blob get(BlobId blob)
null
if not found.
Example of getting information on a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.get(blobId);
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) com.google.api.gax.paging.Page<Bucket> list(Storage.BucketListOption... options)
Example of listing buckets, specifying the page size and a name prefix.
String prefix = "bucket_";
Page<Bucket> buckets = storage.list(BucketListOption.pageSize(100),
BucketListOption.prefix(prefix));
Iterator<Bucket> bucketIterator = buckets.iterateAll().iterator();
while (bucketIterator.hasNext()) {
Bucket bucket = bucketIterator.next();
// do something with the bucket
}
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) com.google.api.gax.paging.Page<Blob> list(String bucket, Storage.BlobListOption... options)
Storage.BlobListOption.currentDirectory()
option is provided,
results are returned in a directory-like mode.
Example of listing blobs in a provided directory.
String bucketName = "my-unique-bucket";
String directory = "my_directory/";
Page<Blob> blobs = storage.list(bucketName, BlobListOption.currentDirectory(),
BlobListOption.prefix(directory));
Iterator<Blob> blobIterator = blobs.iterateAll().iterator();
while (blobIterator.hasNext()) {
Blob blob = blobIterator.next();
// do something with the blob
}
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Bucket update(BucketInfo bucketInfo, Storage.BucketTargetOption... options)
Accepts an optional userProject Storage.BucketTargetOption
option which defines the project
id to assign operational costs.
Example of updating bucket information.
String bucketName = "my-unique-bucket";
BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName).setVersioningEnabled(true).build();
Bucket bucket = storage.update(bucketInfo);
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Blob update(BlobInfo blobInfo, Storage.BlobTargetOption... options)
options
are met. The
property update works as described in update(BlobInfo)
.
options
parameter can contain the preconditions for applying the update. E.g. update
of the blob properties might be required only if the properties have not been updated
externally. StorageException
with the code 412
is thrown if preconditions fail.
Example of updating the content type only if the properties are not updated externally:
BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo);
doSomething();
BlobInfo update = blob.toBuilder().setContentType("multipart/form-data").build();
Storage.BlobTargetOption option = Storage.BlobTargetOption.metagenerationMatch();
try {
storage.update(update, option);
} catch (StorageException e) {
if (e.getCode() == 412) {
// the properties were updated externally
} else {
throw e;
}
}
blobInfo
- information to updateoptions
- preconditions to apply the updateStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Blob update(BlobInfo blobInfo)
blobInfo
. Properties not defined in
blobInfo
will not be updated. To unset a blob property this property in blobInfo
should be explicitly set to null
.
Bucket or blob's name cannot be changed by this method. If you want to rename the blob or
move it to a different bucket use the Blob.copyTo(com.google.cloud.storage.BlobId, com.google.cloud.storage.Blob.BlobSourceOption...)
and delete(java.lang.String, com.google.cloud.storage.Storage.BucketSourceOption...)
operations.
Property update alters the blob metadata generation and doesn't alter the blob generation.
Example of how to update blob's user provided metadata and unset the content type:
Map<String, String> metadataUpdate = new HashMap<>();
metadataUpdate.put("keyToAdd", "new value");
metadataUpdate.put("keyToRemove", null);
BlobInfo blobUpdate = BlobInfo.newBuilder(bucketName, blobName)
.setMetadata(metadataUpdate)
.setContentType(null)
.build();
Blob blob = storage.update(blobUpdate);
blobInfo
- information to updateStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) boolean delete(String bucket, Storage.BucketSourceOption... options)
Accepts an optional userProject Storage.BucketSourceOption
option which defines the project
id to assign operational costs.
Example of deleting a bucket, only if its metageneration matches a value, otherwise a StorageException
is thrown.
String bucketName = "my-unique-bucket";
long bucketMetageneration = 42;
boolean deleted = storage.delete(bucketName,
BucketSourceOption.metagenerationMatch(bucketMetageneration));
if (deleted) {
// the bucket was deleted
} else {
// the bucket was not found
}
true
if bucket was deleted, false
if it was not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) boolean delete(String bucket, String blob, Storage.BlobSourceOption... options)
Example of deleting a blob, only if its generation matches a value, otherwise a StorageException
is thrown.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42;
boolean deleted = storage.delete(bucketName, blobName,
BlobSourceOption.generationMatch(blobGeneration));
if (deleted) {
// the blob was deleted
} else {
// the blob was not found
}
true
if blob was deleted, false
if it was not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) boolean delete(BlobId blob, Storage.BlobSourceOption... options)
Accepts an optional userProject Storage.BlobSourceOption
option which defines the project id
to assign operational costs.
Example of deleting a blob, only if its generation matches a value, otherwise a StorageException
is thrown.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42;
BlobId blobId = BlobId.of(bucketName, blobName);
boolean deleted = storage.delete(blobId, BlobSourceOption.generationMatch(blobGeneration));
if (deleted) {
// the blob was deleted
} else {
// the blob was not found
}
true
if blob was deleted, false
if it was not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) boolean delete(BlobId blob)
Example of deleting a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
boolean deleted = storage.delete(blobId);
if (deleted) {
// the blob was deleted
} else {
// the blob was not found
}
true
if blob was deleted, false
if it was not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Blob compose(Storage.ComposeRequest composeRequest)
Accepts an optional userProject Storage.BlobTargetOption
option which defines the project id
to assign operational costs.
Example of composing two blobs.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
String sourceBlob1 = "source_blob_1";
String sourceBlob2 = "source_blob_2";
BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
ComposeRequest request = ComposeRequest.newBuilder()
.setTarget(blobInfo)
.addSource(sourceBlob1)
.addSource(sourceBlob2)
.build();
Blob blob = storage.compose(request);
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) CopyWriter copy(Storage.CopyRequest copyRequest)
BlobInfo
to the CopyRequest
using either Storage.CopyRequest.Builder.setTarget(BlobInfo, Storage.BlobTargetOption...)
or Storage.CopyRequest.Builder.setTarget(BlobInfo, Iterable)
.
This method returns a CopyWriter
object for the provided CopyRequest
. If
source and destination objects share the same location and storage class the source blob is
copied with one request and CopyWriter.getResult()
immediately returns, regardless of
the Storage.CopyRequest.megabytesCopiedPerChunk
parameter. If source and destination have
different location or storage class CopyWriter.getResult()
might issue multiple RPC
calls depending on blob's size.
Example of copying a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
String copyBlobName = "copy_blob_name";
CopyRequest request = CopyRequest.newBuilder()
.setSource(BlobId.of(bucketName, blobName))
.setTarget(BlobId.of(bucketName, copyBlobName))
.build();
Blob blob = storage.copy(request).getResult();
Example of copying a blob in chunks.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
String copyBlobName = "copy_blob_name";
CopyRequest request = CopyRequest.newBuilder()
.setSource(BlobId.of(bucketName, blobName))
.setTarget(BlobId.of(bucketName, copyBlobName))
.build();
CopyWriter copyWriter = storage.copy(request);
while (!copyWriter.isDone()) {
copyWriter.copyChunk();
}
Blob blob = copyWriter.getResult();
Example of rotating the encryption key of a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
String oldEncryptionKey = "old_encryption_key";
String newEncryptionKey = "new_encryption_key";
BlobId blobId = BlobId.of(bucketName, blobName);
CopyRequest request = CopyRequest.newBuilder()
.setSource(blobId)
.setSourceOptions(BlobSourceOption.decryptionKey(oldEncryptionKey))
.setTarget(blobId, BlobTargetOption.encryptionKey(newEncryptionKey))
.build();
Blob blob = storage.copy(request).getResult();
CopyWriter
object that can be used to get information on the newly created
blob or to complete the copy if more than one RPC request is neededStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) byte[] readAllBytes(String bucket, String blob, Storage.BlobSourceOption... options)
Example of reading all bytes of a blob, if generation matches a value, otherwise a StorageException
is thrown.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42";
byte[] content = storage.readAllBytes(bucketName, blobName,
BlobSourceOption.generationMatch(blobGeneration));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) byte[] readAllBytes(BlobId blob, Storage.BlobSourceOption... options)
Example of reading all bytes of a blob's specific generation, otherwise a StorageException
is thrown.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42;
BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
byte[] content = storage.readAllBytes(blobId);
Example of reading all bytes of an encrypted blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
String decryptionKey = "my_encryption_key";
byte[] content = storage.readAllBytes(
bucketName, blobName, BlobSourceOption.decryptionKey(decryptionKey));
StorageException
- upon failure@TransportCompatibility(value=HTTP) StorageBatch batch()
Example of using a batch request to delete, update and get a blob.
String bucketName = "my-unique-bucket";
String blobName1 = "my-blob-name1";
String blobName2 = "my-blob-name2";
StorageBatch batch = storage.batch();
BlobId firstBlob = BlobId.of(bucketName, blobName1);
BlobId secondBlob = BlobId.of(bucketName, blobName2);
batch.delete(firstBlob).notify(new BatchResult.Callback<Boolean, StorageException>() {
public void success(Boolean result) {
// deleted successfully
}
public void error(StorageException exception) {
// delete failed
}
});
batch.update(BlobInfo.newBuilder(secondBlob).setContentType("text/plain").build());
StorageBatchResult<Blob> result = batch.get(secondBlob);
batch.submit();
Blob blob = result.get(); // returns get result or throws StorageException
@TransportCompatibility(value={HTTP,GRPC}) com.google.cloud.ReadChannel reader(String bucket, String blob, Storage.BlobSourceOption... options)
BlobInfo.getEtag()
changes), subsequent calls to
blobReadChannel.read(ByteBuffer)
may throw StorageException
.
Example of reading a blob's content through a reader.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
try (ReadChannel reader = storage.reader(bucketName, blobName)) {
ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
while (reader.read(bytes) > 0) {
bytes.flip();
// do something with bytes
bytes.clear();
}
}
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) com.google.cloud.ReadChannel reader(BlobId blob, Storage.BlobSourceOption... options)
blob.generation()
is set data
corresponding to that generation is read. If blob.generation()
is null
the
blob's latest generation is read. If the blob changes while reading (i.e. BlobInfo.getEtag()
changes), subsequent calls to blobReadChannel.read(ByteBuffer)
may
throw StorageException
.
The Storage.BlobSourceOption.generationMatch()
and Storage.BlobSourceOption.generationMatch(long)
options can be used to ensure that blobReadChannel.read(ByteBuffer)
calls will throw StorageException
if the blob`s
generation differs from the expected one.
Example of reading a blob's content through a reader.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
try (ReadChannel reader = storage.reader(blobId)) {
ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
while (reader.read(bytes) > 0) {
bytes.flip();
// do something with bytes
bytes.clear();
}
}
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) void downloadTo(BlobId blob, Path path, Storage.BlobSourceOption... options)
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
Path destination = Paths.get("my-blob-destination.txt");
downloadTo(blobId, destination);
// do stuff with destination
blob
- path
- options
- StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) void downloadTo(BlobId blob, OutputStream outputStream, Storage.BlobSourceOption... options)
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
Path destination = Paths.get("my-blob-destination.txt");
try (OutputStream outputStream = Files.newOutputStream(path)) {
downloadTo(blob, outputStream);
// do stuff with destination
}
blob
- outputStream
- options
- @TransportCompatibility(value={HTTP,GRPC}) com.google.cloud.WriteChannel writer(BlobInfo blobInfo, Storage.BlobWriteOption... options)
blobInfo
are ignored unless requested via the BlobWriteOption.md5Match
and BlobWriteOption.crc32cMatch
options.
Example of writing a blob's content through a writer:
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
byte[] content = "Hello, World!".getBytes(UTF_8);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
try (WriteChannel writer = storage.writer(blobInfo)) {
writer.write(ByteBuffer.wrap(content, 0, content.length));
} catch (IOException ex) {
// handle exception
}
StorageException
- upon failure@TransportCompatibility(value=HTTP) com.google.cloud.WriteChannel writer(URL signedURL)
Example of writing content through a writer using signed URL.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
BlobId blobId = BlobId.of(bucketName, blobName);
byte[] content = "Hello, World!".getBytes(UTF_8);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
URL signedURL = storage.signUrl(
blobInfo,
1, TimeUnit.HOURS,
Storage.SignUrlOption.httpMethod(HttpMethod.POST));
try (WriteChannel writer = storage.writer(signedURL)) {
writer.write(ByteBuffer.wrap(content, 0, content.length));
}
StorageException
- upon failure@TransportCompatibility(value=HTTP) URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, Storage.SignUrlOption... options)
ServiceAccountSigner
was passed to
StorageOptions
' builder via setCredentials(Credentials)
or the default
credentials are being used and the environment variable GOOGLE_APPLICATION_CREDENTIALS
is set or your application is running in App Engine, then signUrl
will use that
credentials to sign the URL. If the credentials passed to StorageOptions
do not
implement ServiceAccountSigner
(this is the case, for instance, for Google Cloud SDK
credentials) then signUrl
will throw an IllegalStateException
unless an
implementation of ServiceAccountSigner
is passed using the Storage.SignUrlOption.signWith(ServiceAccountSigner)
option.
A service account signer is looked for in the following order:
Storage.SignUrlOption.signWith(ServiceAccountSigner)
StorageOptions
StorageOptions
Example of creating a signed URL that is valid for 1 week, using the default credentials for signing the URL, the default signing method (V2), and the default URL style (path-style):
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
URL signedUrl = storage.signUrl(
BlobInfo.newBuilder(bucketName, blobName).build(),
7, TimeUnit.DAYS);
Example of creating a signed URL passing the Storage.SignUrlOption.withV4Signature()
option,
which enables V4 signing:
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
URL signedUrl = storage.signUrl(
BlobInfo.newBuilder(bucketName, blobName).build(),
7, TimeUnit.DAYS,
Storage.SignUrlOption.withV4Signature());
Example of creating a signed URL passing the Storage.SignUrlOption.withVirtualHostedStyle()
option, which specifies the bucket name in the hostname of the URI, rather than in the path:
URL signedUrl = storage.signUrl(
BlobInfo.newBuilder(bucketName, blobName).build(),
1, TimeUnit.DAYS,
Storage.SignUrlOption.withVirtualHostedStyle());
Example of creating a signed URL passing the Storage.SignUrlOption.withPathStyle()
option,
which specifies the bucket name in path portion of the URI, rather than in the hostname:
URL signedUrl = storage.signUrl(
BlobInfo.newBuilder(bucketName, blobName).build(),
1, TimeUnit.DAYS,
Storage.SignUrlOption.withPathStyle());
Example of creating a signed URL passing the Storage.SignUrlOption.signWith(ServiceAccountSigner)
option, that will be used for signing the URL:
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
String kfPath = "/path/to/keyfile.json";
URL signedUrl = storage.signUrl(
BlobInfo.newBuilder(bucketName, blobName).build(),
7, TimeUnit.DAYS,
SignUrlOption.signWith(ServiceAccountCredentials.fromStream(new FileInputStream(kfPath))));
Note that the ServiceAccountSigner
may require additional configuration to enable
URL signing. See the documentation for the implementation for more details.
Example of creating a signed URL for a blob with generation:
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long generation = 1576656755290328L;
URL signedUrl = storage.signUrl(
BlobInfo.newBuilder(bucketName, blobName, generation).build(),
7, TimeUnit.DAYS,
SignUrlOption.withQueryParams(ImmutableMap.of("generation", String.valueOf(generation))));
blobInfo
- the blob associated with the signed URLduration
- time until the signed URL expires, expressed in unit
. The finest
granularity supported is 1 second, finer granularities will be truncatedunit
- time unit of the duration
parameteroptions
- optional URL signing optionsIllegalStateException
- if Storage.SignUrlOption.signWith(ServiceAccountSigner)
was not
used and no implementation of ServiceAccountSigner
was provided to StorageOptions
IllegalArgumentException
- if SignUrlOption.withMd5()
option is used and blobInfo.md5()
is null
IllegalArgumentException
- if SignUrlOption.withContentType()
option is used and
blobInfo.contentType()
is null
com.google.auth.ServiceAccountSigner.SigningException
- if the attempt to sign the URL failed@TransportCompatibility(value=HTTP) PostPolicyV4 generateSignedPostPolicyV4(BlobInfo blobInfo, long duration, TimeUnit unit, PostPolicyV4.PostFieldsV4 fields, PostPolicyV4.PostConditionsV4 conditions, Storage.PostPolicyV4Option... options)
ServiceAccountSigner
was passed to StorageOptions
' builder via setCredentials(Credentials)
or the default credentials are being used and the environment
variable GOOGLE_APPLICATION_CREDENTIALS
is set, generatPresignedPostPolicyV4 will use
that credentials to sign the URL. If the credentials passed to StorageOptions
do not
implement ServiceAccountSigner
(this is the case, for instance, for Google Cloud SDK
credentials) then signUrl
will throw an IllegalStateException
unless an
implementation of ServiceAccountSigner
is passed using the Storage.PostPolicyV4Option.signWith(ServiceAccountSigner)
option.
Example of generating a presigned post policy which has the condition that only jpeg images can be uploaded, and applies the public read acl to each image uploaded, and making the POST request:
PostFieldsV4 fields = PostFieldsV4.newBuilder().setAcl("public-read").build();
PostConditionsV4 conditions = PostConditionsV4.newBuilder().addContentTypeCondition(ConditionV4Type.MATCHES, "image/jpeg").build();
PostPolicyV4 policy = storage.generateSignedPostPolicyV4(
BlobInfo.newBuilder("my-bucket", "my-object").build(),
7, TimeUnit.DAYS, fields, conditions);
HttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(policy.getUrl());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Map.Entry<String, String> entry : policy.getFields().entrySet()) {
builder.addTextBody(entry.getKey(), entry.getValue());
}
File file = new File("path/to/your/file/to/upload");
builder.addBinaryBody("file", new FileInputStream(file), ContentType.APPLICATION_OCTET_STREAM, file.getName());
request.setEntity(builder.build());
client.execute(request);
blobInfo
- the blob uploaded in the formduration
- time before expirationunit
- duration time unitfields
- the fields specified in the formconditions
- which conditions every upload must satisfyduration
- how long until the form expires, in millisecondsoptions
- optional post policy options@TransportCompatibility(value=HTTP) PostPolicyV4 generateSignedPostPolicyV4(BlobInfo blobInfo, long duration, TimeUnit unit, PostPolicyV4.PostFieldsV4 fields, Storage.PostPolicyV4Option... options)
generateSignedPostPolicyV4(BlobInfo, long,
TimeUnit, PostPolicyV4.PostFieldsV4, PostPolicyV4.PostConditionsV4, PostPolicyV4Option...)
.@TransportCompatibility(value=HTTP) PostPolicyV4 generateSignedPostPolicyV4(BlobInfo blobInfo, long duration, TimeUnit unit, PostPolicyV4.PostConditionsV4 conditions, Storage.PostPolicyV4Option... options)
generateSignedPostPolicyV4(BlobInfo, long, TimeUnit,
PostPolicyV4.PostFieldsV4, PostPolicyV4.PostConditionsV4, PostPolicyV4Option...)
.@TransportCompatibility(value=HTTP) PostPolicyV4 generateSignedPostPolicyV4(BlobInfo blobInfo, long duration, TimeUnit unit, Storage.PostPolicyV4Option... options)
generateSignedPostPolicyV4(BlobInfo, long, TimeUnit, PostPolicyV4.PostFieldsV4,
PostPolicyV4.PostConditionsV4, PostPolicyV4Option...)
.@TransportCompatibility(value=HTTP) List<Blob> get(BlobId... blobIds)
Example of getting information on several blobs using a single batch request.
String bucketName = "my-unique-bucket";
String blobName1 = "my-blob-name1";
String blobName2 = "my-blob-name2";
BlobId firstBlob = BlobId.of(bucketName, blobName1);
BlobId secondBlob = BlobId.of(bucketName, blobName2);
List<Blob> blobs = storage.get(firstBlob, secondBlob);
blobIds
- blobs to getBlob
objects. If a blob does not exist or access to it has
been denied the corresponding item in the list is null
.StorageException
- upon failure@TransportCompatibility(value=HTTP) List<Blob> get(Iterable<BlobId> blobIds)
Example of getting information on several blobs using a single batch request.
String bucketName = "my-unique-bucket";
String blobName1 = "my-blob-name1";
String blobName2 = "my-blob-name2";
List<BlobId> blobIds = new LinkedList<>();
blobIds.add(BlobId.of(bucketName, blobName1));
blobIds.add(BlobId.of(bucketName, blobName2));
List<Blob> blobs = storage.get(blobIds);
blobIds
- blobs to getBlob
objects. If a blob does not exist or access to it has
been denied the corresponding item in the list is null
.StorageException
- upon failure@TransportCompatibility(value=HTTP) List<Blob> update(BlobInfo... blobInfos)
BlobInfo
objects. Unsetting a
property can be done by setting the property of the provided BlobInfo
objects to null
. See update(BlobInfo)
for a code example.
Example of updating information on several blobs using a single batch request.
String bucketName = "my-unique-bucket";
String blobName1 = "my-blob-name1";
String blobName2 = "my-blob-name2";
Blob firstBlob = storage.get(bucketName, blobName1);
Blob secondBlob = storage.get(bucketName, blobName2);
List<Blob> updatedBlobs = storage.update(
firstBlob.toBuilder().setContentType("text/plain").build(),
secondBlob.toBuilder().setContentType("text/plain").build());
blobInfos
- blobs to updateBlob
objects. If a blob does not exist or access to it has
been denied the corresponding item in the list is null
.StorageException
- upon failure@TransportCompatibility(value=HTTP) List<Blob> update(Iterable<BlobInfo> blobInfos)
BlobInfo
objects. Unsetting a
property can be done by setting the property of the provided BlobInfo
objects to null
. See update(BlobInfo)
for a code example.
Example of updating information on several blobs using a single batch request.
String bucketName = "my-unique-bucket";
String blobName1 = "my-blob-name1";
String blobName2 = "my-blob-name2";
Blob firstBlob = storage.get(bucketName, blobName1);
Blob secondBlob = storage.get(bucketName, blobName2);
List<BlobInfo> blobs = new LinkedList<>();
blobs.add(firstBlob.toBuilder().setContentType("text/plain").build());
blobs.add(secondBlob.toBuilder().setContentType("text/plain").build());
List<Blob> updatedBlobs = storage.update(blobs);
blobInfos
- blobs to updateBlob
objects. If a blob does not exist or access to it has
been denied the corresponding item in the list is null
.StorageException
- upon failure@TransportCompatibility(value=HTTP) List<Boolean> delete(BlobId... blobIds)
Example of deleting several blobs using a single batch request.
String bucketName = "my-unique-bucket";
String blobName1 = "my-blob-name1";
String blobName2 = "my-blob-name2";
BlobId firstBlob = BlobId.of(bucketName, blobName1);
BlobId secondBlob = BlobId.of(bucketName, blobName2);
List<Boolean> deleted = storage.delete(firstBlob, secondBlob);
blobIds
- blobs to deletetrue
. If a blob was not found, deletion failed or access to the resource
was denied the corresponding item is false
.StorageException
- upon failure@TransportCompatibility(value=HTTP) List<Boolean> delete(Iterable<BlobId> blobIds)
Example of deleting several blobs using a single batch request.
String bucketName = "my-unique-bucket";
String blobName1 = "my-blob-name1";
String blobName2 = "my-blob-name2";
List<BlobId> blobIds = new LinkedList<>();
blobIds.add(BlobId.of(bucketName, blobName1));
blobIds.add(BlobId.of(bucketName, blobName2));
List<Boolean> deleted = storage.delete(blobIds);
blobIds
- blobs to deletetrue
. If a blob was not found, deletion failed or access to the resource
was denied the corresponding item is false
.StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Acl getAcl(String bucket, Acl.Entity entity, Storage.BucketSourceOption... options)
null
if not
found.
Example of getting the ACL entry for an entity on a bucket.
String bucketName = "my-unique-bucket";
Acl acl = storage.getAcl(bucketName, User.ofAllAuthenticatedUsers());
Example of getting the ACL entry for a specific user on a requester_pays bucket with a user_project option.
String bucketName = "my-unique-bucket";
String userEmail = "google-cloud-java-tests@java-docs-samples-tests.iam.gserviceaccount.com";
BucketSourceOption userProjectOption = BucketSourceOption.userProject("myProject");
Acl acl = storage.getAcl(bucketName, new User(userEmail), userProjectOption);
TransportCompatibility.Transport
is used. For JSON, an HTTP 400 Bad Request error will be thrown. Whereas for
gRPC, an empty list will be returned.
bucket
- name of the bucket where the getAcl operation takes placeentity
- ACL entity to fetchoptions
- extra parameters to apply to this operationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Acl getAcl(String bucket, Acl.Entity entity)
#getAcl(String, Entity, BucketSourceOption...)
@TransportCompatibility(value={HTTP,GRPC}) boolean deleteAcl(String bucket, Acl.Entity entity, Storage.BucketSourceOption... options)
Example of deleting the ACL entry for an entity on a bucket.
String bucketName = "my-unique-bucket";
boolean deleted = storage.deleteAcl(bucketName, User.ofAllAuthenticatedUsers());
if (deleted) {
// the acl entry was deleted
} else {
// the acl entry was not found
}
Example of deleting the ACL entry for a specific user on a requester_pays bucket with a user_project option.
String bucketName = "my-unique-bucket";
BucketSourceOption userProject = BucketSourceOption.userProject("myProject");
boolean deleted = storage.deleteAcl(bucketName, User.ofAllAuthenticatedUsers(), userProject);
bucket
- name of the bucket to delete an ACL fromentity
- ACL entity to deleteoptions
- extra parameters to apply to this operationtrue
if the ACL was deleted, false
if it was not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) boolean deleteAcl(String bucket, Acl.Entity entity)
#deleteAcl(String, Entity, BucketSourceOption...)
@TransportCompatibility(value={HTTP,GRPC}) Acl createAcl(String bucket, Acl acl, Storage.BucketSourceOption... options)
Example of creating a new ACL entry on a bucket.
String bucketName = "my-unique-bucket";
Acl acl = storage.createAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER));
Example of creating a new ACL entry on a requester_pays bucket with a user_project option.
String bucketName = "my-unique-bucket";
Acl acl = storage.createAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER),
BucketSourceOption.userProject("myProject"));
bucket
- name of the bucket for which an ACL should be createdacl
- ACL to createoptions
- extra parameters to apply to this operationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Acl updateAcl(String bucket, Acl acl, Storage.BucketSourceOption... options)
Example of updating a new ACL entry on a bucket.
String bucketName = "my-unique-bucket";
Acl acl = storage.updateAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.OWNER));
Example of updating a new ACL entry on a requester_pays bucket with a user_project option.
String bucketName = "my-unique-bucket";
Acl acl = storage.updateAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.OWNER),
BucketSourceOption.userProject("myProject"));
bucket
- name of the bucket where the updateAcl operation takes placeacl
- ACL to updateoptions
- extra parameters to apply to this operationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) List<Acl> listAcls(String bucket, Storage.BucketSourceOption... options)
Example of listing the ACL entries for a blob.
String bucketName = "my-unique-bucket";
List<Acl> acls = storage.listAcls(bucketName);
for (Acl acl : acls) {
// do something with ACL entry
}
Example of listing the ACL entries for a blob in a requester_pays bucket with a user_project option.
String bucketName = "my-unique-bucket";
List<Acl> acls = storage.listAcls(bucketName, BucketSourceOption.userProject("myProject"));
for (Acl acl : acls) {
// do something with ACL entry
}
TransportCompatibility.Transport
is used. For JSON, an HTTP 400 Bad Request error will be thrown. Whereas for
gRPC, an empty list will be returned.
bucket
- the name of the bucket to list ACLs foroptions
- any number of BucketSourceOptions to apply to this operationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) List<Acl> listAcls(String bucket)
listAcls(String, BucketSourceOption...)
@TransportCompatibility(value={HTTP,GRPC}) Acl getDefaultAcl(String bucket, Acl.Entity entity)
null
if not found.
Default ACLs are applied to a new blob within the bucket when no ACL was provided for that blob.
Example of getting the default ACL entry for an entity on a bucket.
String bucketName = "my-unique-bucket";
Acl acl = storage.getDefaultAcl(bucketName, User.ofAllAuthenticatedUsers());
TransportCompatibility.Transport
is used. For JSON, an HTTP 400 Bad Request error will be thrown. Whereas for
gRPC, an empty list will be returned.
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) boolean deleteDefaultAcl(String bucket, Acl.Entity entity)
Default ACLs are applied to a new blob within the bucket when no ACL was provided for that blob.
Example of deleting the default ACL entry for an entity on a bucket.
String bucketName = "my-unique-bucket";
boolean deleted = storage.deleteDefaultAcl(bucketName, User.ofAllAuthenticatedUsers());
if (deleted) {
// the acl entry was deleted
} else {
// the acl entry was not found
}
true
if the ACL was deleted, false
if it was not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Acl createDefaultAcl(String bucket, Acl acl)
Default ACLs are applied to a new blob within the bucket when no ACL was provided for that blob.
Example of creating a new default ACL entry on a bucket.
String bucketName = "my-unique-bucket";
Acl acl =
storage.createDefaultAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Acl updateDefaultAcl(String bucket, Acl acl)
Default ACLs are applied to a new blob within the bucket when no ACL was provided for that blob.
Example of updating a new default ACL entry on a bucket.
String bucketName = "my-unique-bucket";
Acl acl =
storage.updateDefaultAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.OWNER));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) List<Acl> listDefaultAcls(String bucket)
Default ACLs are applied to a new blob within the bucket when no ACL was provided for that blob.
Example of listing the default ACL entries for a blob.
String bucketName = "my-unique-bucket";
List<Acl> acls = storage.listDefaultAcls(bucketName);
for (Acl acl : acls) {
// do something with ACL entry
}
TransportCompatibility.Transport
is used. For JSON, an HTTP 400 Bad Request error will be thrown. Whereas for
gRPC, an empty list will be returned.
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Acl getAcl(BlobId blob, Acl.Entity entity)
null
if not
found.
Example of getting the ACL entry for an entity on a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42;
BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
Acl acl = storage.getAcl(blobId, User.ofAllAuthenticatedUsers());
Example of getting the ACL entry for a specific user on a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
String userEmail = "google-cloud-java-tests@java-docs-samples-tests.iam.gserviceaccount.com";
BlobId blobId = BlobId.of(bucketName, blobName);
Acl acl = storage.getAcl(blobId, new User(userEmail));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) boolean deleteAcl(BlobId blob, Acl.Entity entity)
Example of deleting the ACL entry for an entity on a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42;
BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
boolean deleted = storage.deleteAcl(blobId, User.ofAllAuthenticatedUsers());
if (deleted) {
// the acl entry was deleted
} else {
// the acl entry was not found
}
true
if the ACL was deleted, false
if it was not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Acl createAcl(BlobId blob, Acl acl)
Example of creating a new ACL entry on a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42;
BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
Acl acl = storage.createAcl(blobId, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER));
Example of updating a blob to be public-read.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42;
BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
Acl acl = storage.createAcl(blobId, Acl.of(User.ofAllUsers(), Role.READER));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Acl updateAcl(BlobId blob, Acl acl)
Example of updating a new ACL entry on a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42;
BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
Acl acl = storage.updateAcl(blobId, Acl.of(User.ofAllAuthenticatedUsers(), Role.OWNER));
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) List<Acl> listAcls(BlobId blob)
Example of listing the ACL entries for a blob.
String bucketName = "my-unique-bucket";
String blobName = "my-blob-name";
long blobGeneration = 42;
BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
List<Acl> acls = storage.listAcls(blobId);
for (Acl acl : acls) {
// do something with ACL entry
}
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) HmacKey createHmacKey(ServiceAccount serviceAccount, Storage.CreateHmacKeyOption... options)
Example of creating a new HMAC Key.
ServiceAccount serviceAccount = ServiceAccount.of("my-service-account@google.com");
HmacKey hmacKey = storage.createHmacKey(serviceAccount);
String secretKey = hmacKey.getSecretKey();
HmacKey.HmacKeyMetadata metadata = hmacKey.getMetadata();
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) com.google.api.gax.paging.Page<HmacKey.HmacKeyMetadata> listHmacKeys(Storage.ListHmacKeysOption... options)
HmacKeyMetadata
objects,
which do not contain secret keys.
Example of listing HMAC keys, specifying project id.
Page<HmacKey.HmacKeyMetadata> metadataPage = storage.listHmacKeys(
Storage.ListHmacKeysOption.projectId("my-project-id"));
for (HmacKey.HmacKeyMetadata hmacKeyMetadata : metadataPage.getValues()) {
//do something with the metadata
}
Example of listing HMAC keys, specifying max results and showDeletedKeys. Since projectId is not specified, the same project ID as the storage client instance will be used
ServiceAccount serviceAccount = ServiceAccount.of("my-service-account@google.com");
Page<HmacKey.HmacKeyMetadata> metadataPage = storage.listHmacKeys(
Storage.ListHmacKeysOption.serviceAccount(serviceAccount),
Storage.ListHmacKeysOption.maxResults(10L),
Storage.ListHmacKeysOption.showDeletedKeys(true));
for (HmacKey.HmacKeyMetadata hmacKeyMetadata : metadataPage.getValues()) {
//do something with the metadata
}
options
- the options to apply to this operationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) HmacKey.HmacKeyMetadata getHmacKey(String accessId, Storage.GetHmacKeyOption... options)
HmacKeyMetadata
object,
which does not contain the secret key.
Example of getting an HMAC key. Since projectId isn't specified, the same project ID as the storage client instance will be used.
String hmacKeyAccessId = "my-access-id";
HmacKey.HmackeyMetadata hmacKeyMetadata = storage.getHmacKey(hmacKeyAccessId);
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) void deleteHmacKey(HmacKey.HmacKeyMetadata hmacKeyMetadata, Storage.DeleteHmacKeyOption... options)
INACTIVE
key can be deleted. Attempting to
delete a key whose HmacKey.HmacKeyState
is anything other than INACTIVE
will
fail.
Example of updating an HMAC key's state to INACTIVE and then deleting it.
String hmacKeyAccessId = "my-access-id";
HmacKey.HmacKeyMetadata hmacKeyMetadata = storage.getHmacKey(hmacKeyAccessId);
storage.updateHmacKeyState(hmacKeyMetadata, HmacKey.HmacKeyState.INACTIVE);
storage.deleteHmacKey(hmacKeyMetadata);
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) HmacKey.HmacKeyMetadata updateHmacKeyState(HmacKey.HmacKeyMetadata hmacKeyMetadata, HmacKey.HmacKeyState state, Storage.UpdateHmacKeyOption... options)
Example of updating the state of an HMAC key.
String hmacKeyAccessId = "my-access-id";
HmacKey.HmacKeyMetadata hmacKeyMetadata = storage.getHmacKey(hmacKeyAccessId);
storage.updateHmacKeyState(hmacKeyMetadata, HmacKey.HmacKeyState.INACTIVE);
StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) com.google.cloud.Policy getIamPolicy(String bucket, Storage.BucketSourceOption... options)
It's possible for bindings to be empty and instead have permissions inherited through
Project or Organization IAM Policies. To prevent corrupting policies when you update an IAM
policy with Storage.setIamPolicy
, the ETAG value is used to perform optimistic
concurrency.
Example of getting the IAM policy for a bucket.
String bucketName = "my-unique-bucket";
Policy policy = storage.getIamPolicy(bucketName);
bucket
- name of the bucket where the getIamPolicy operation takes placeoptions
- extra parameters to apply to this operationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) com.google.cloud.Policy setIamPolicy(String bucket, com.google.cloud.Policy policy, Storage.BucketSourceOption... options)
To prevent corrupting policies when you update an IAM policy with Storage.setIamPolicy
, the ETAG value is used to perform optimistic concurrency.
Example of updating the IAM policy on a bucket.
// We want to make all objects in our bucket publicly readable.
String bucketName = "my-unique-bucket";
Policy currentPolicy = storage.getIamPolicy(bucketName);
Policy updatedPolicy =
storage.setIamPolicy(
bucketName,
currentPolicy.toBuilder()
.addIdentity(StorageRoles.objectViewer(), Identity.allUsers())
.build());
bucket
- name of the bucket where the setIamPolicy operation takes placepolicy
- policy to be set on the specified bucketoptions
- extra parameters to apply to this operationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) List<Boolean> testIamPermissions(String bucket, List<String> permissions, Storage.BucketSourceOption... options)
Example of testing permissions on a bucket.
String bucketName = "my-unique-bucket";
List<Boolean> response =
storage.testIamPermissions(
bucketName,
ImmutableList.of("storage.buckets.get", "storage.buckets.getIamPolicy"));
for (boolean hasPermission : response) {
// Do something with permission test response
}
bucket
- name of the bucket where the testIamPermissions operation takes placepermissions
- list of permissions to test on the bucketoptions
- extra parameters to apply to this operationStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) ServiceAccount getServiceAccount(String projectId)
Example of getting a service account.
String projectId = "test@gmail.com";
ServiceAccount account = storage.getServiceAccount(projectId);
projectId
- the ID of the project for which the service account should be fetched.StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Notification createNotification(String bucket, NotificationInfo notificationInfo)
Example of creating a notification:
String bucketName = "my-unique-bucket";
String topic = "projects/myProject/topics/myTopic"
NotificationInfo notificationInfo = NotificationInfo.newBuilder(topic)
.setCustomAttributes(ImmutableMap.of("label1", "value1"))
.setEventTypes(NotificationInfo.EventType.OBJECT_FINALIZE)
.setPayloadFormat(NotificationInfo.PayloadFormat.JSON_API_V1)
.build();
Notification notification = storage.createNotification(bucketName, notificationInfo);
bucket
- name of the bucketnotificationInfo
- notification to createStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) Notification getNotification(String bucket, String notificationId)
Example of getting the notification:
String bucketName = "my-unique-bucket";
String notificationId = "my-unique-notification-id";
Notification notification = storage.getNotification(bucketName, notificationId);
bucket
- name of the bucketnotificationId
- notification IDNotification
object with the given id or null
if not foundStorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) List<Notification> listNotifications(String bucket)
Example of listing the bucket notifications:
String bucketName = "my-unique-bucket";
List<Notification> notifications = storage.listNotifications(bucketName);
bucket
- name of the bucketNotification
objects added to the bucket.StorageException
- upon failure@TransportCompatibility(value={HTTP,GRPC}) boolean deleteNotification(String bucket, String notificationId)
Example of deleting the notification:
String bucketName = "my-unique-bucket";
String notificationId = "my-unique-notification-id";
boolean deleted = storage.deleteNotification(bucketName, notificationId);
if (deleted) {
// the notification was deleted
} else {
// the notification was not found
}
bucket
- name of the bucketnotificationId
- ID of the notification to deletetrue
if the notification has been deleted, false
if not foundStorageException
- upon failuredefault void close() throws Exception
close
in interface AutoCloseable
InterruptedException
- thrown if interrupted while awaiting termination of underlying
resourcesException
Copyright © 2023 Google LLC. All rights reserved.