Interface Storage

All Superinterfaces:
AutoCloseable, com.google.cloud.Service<StorageOptions>

@InternalExtensionOnly public interface Storage extends com.google.cloud.Service<StorageOptions>, AutoCloseable
An interface for Google Cloud Storage.
See Also:
  • Method Details

    • create

      Creates a new bucket.

      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());
       
      Returns:
      a complete bucket
      Throws:
      StorageException - upon failure
    • create

      Creates a new blob with no content. 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 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);
       
      Returns:
      a Blob with complete information
      Throws:
      StorageException - upon failure
    • create

      @TransportCompatibility({HTTP,GRPC}) Blob create(BlobInfo blobInfo, byte[] content, Storage.BlobTargetOption... options)
      Creates a new blob. Direct upload is used to upload 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));
       
      Returns:
      a Blob with complete information
      Throws:
      StorageException - upon failure
      See Also:
    • create

      @TransportCompatibility({HTTP,GRPC}) 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. Direct upload is used to upload 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);
       
      Returns:
      a Blob with complete information
      Throws:
      StorageException - upon failure
      See Also:
    • create

      Deprecated.
      Creates a new blob. Direct upload is used to upload 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));
       
      Returns:
      a Blob with complete information
      Throws:
      StorageException - upon failure
    • createFrom

      @TransportCompatibility({HTTP,GRPC}) Blob createFrom(BlobInfo blobInfo, Path path, Storage.BlobWriteOption... options) throws IOException
      Uploads 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));
       
      Parameters:
      blobInfo - blob to create
      path - file to upload
      options - blob write options
      Returns:
      a Blob with complete information
      Throws:
      IOException - on I/O error
      StorageException - on server side error
      See Also:
    • createFrom

      @TransportCompatibility({HTTP,GRPC}) Blob createFrom(BlobInfo blobInfo, Path path, int bufferSize, Storage.BlobWriteOption... options) throws IOException
      Uploads 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);
       
      Parameters:
      blobInfo - blob to create
      path - file to upload
      bufferSize - size of the buffer I/O operations
      options - blob write options
      Returns:
      a Blob with complete information
      Throws:
      IOException - on I/O error
      StorageException - on server side error
    • createFrom

      @TransportCompatibility({HTTP,GRPC}) Blob createFrom(BlobInfo blobInfo, InputStream content, Storage.BlobWriteOption... options) throws IOException
      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...). 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());
       
      Parameters:
      blobInfo - blob to create
      content - input stream to read from
      options - blob write options
      Returns:
      a Blob with complete information
      Throws:
      IOException - on I/O error
      StorageException - on server side error
      See Also:
    • createFrom

      @TransportCompatibility({HTTP,GRPC}) Blob createFrom(BlobInfo blobInfo, InputStream content, int bufferSize, Storage.BlobWriteOption... options) throws IOException
      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. 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.

      Parameters:
      blobInfo - blob to create
      content - input stream to read from
      bufferSize - size of the buffer I/O operations
      options - blob write options
      Returns:
      a Blob with complete information
      Throws:
      IOException - on I/O error
      StorageException - on server side error
    • get

      Returns the requested bucket or 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));
       
      Throws:
      StorageException - upon failure
    • lockRetentionPolicy

      @TransportCompatibility({HTTP,GRPC}) Bucket lockRetentionPolicy(BucketInfo bucket, Storage.BucketTargetOption... options)
      Locks bucket retention policy. Requires a local metageneration value in the request. Review example below.

      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());
       
      Returns:
      a Bucket object of the locked bucket
      Throws:
      StorageException - upon failure
    • get

      Returns the requested blob or 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));
       
      Throws:
      StorageException - upon failure
    • get

      Returns the requested blob or 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

      Throws:
      StorageException - upon failure
      See Also:
      • Encrypted Elements
        
         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));
         
    • get

      Returns the requested blob or 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);
       
      Throws:
      StorageException - upon failure
    • list

      @TransportCompatibility({HTTP,GRPC}) com.google.api.gax.paging.Page<Bucket> list(Storage.BucketListOption... options)
      Lists the project's buckets.

      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
       }
       
      Throws:
      StorageException - upon failure
    • list

      @TransportCompatibility({HTTP,GRPC}) com.google.api.gax.paging.Page<Blob> list(String bucket, Storage.BlobListOption... options)
      Lists the bucket's blobs. If the 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
       }
       
      Throws:
      StorageException - upon failure
    • update

      Updates bucket information.

      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);
       
      Returns:
      the updated bucket
      Throws:
      StorageException - upon failure
    • update

      Updates the blob properties if the preconditions specified by 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;
         }
       }
       
      Parameters:
      blobInfo - information to update
      options - preconditions to apply the update
      Returns:
      the updated blob
      Throws:
      StorageException - upon failure
      See Also:
    • update

      Updates the properties of the blob. This method issues an RPC request to merge the current blob properties with the properties in the provided 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);
       
      Parameters:
      blobInfo - information to update
      Returns:
      the updated blob
      Throws:
      StorageException - upon failure
      See Also:
    • delete

      @TransportCompatibility({HTTP,GRPC}) boolean delete(String bucket, Storage.BucketSourceOption... options)
      Deletes the requested bucket.

      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
       }
       
      Returns:
      true if bucket was deleted, false if it was not found
      Throws:
      StorageException - upon failure
    • delete

      @TransportCompatibility({HTTP,GRPC}) boolean delete(String bucket, String blob, Storage.BlobSourceOption... options)
      Deletes the requested blob.

      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
       }
       
      Returns:
      true if blob was deleted, false if it was not found
      Throws:
      StorageException - upon failure
    • delete

      @TransportCompatibility({HTTP,GRPC}) boolean delete(BlobId blob, Storage.BlobSourceOption... options)
      Deletes the requested blob.

      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
       }
       
      Returns:
      true if blob was deleted, false if it was not found
      Throws:
      StorageException - upon failure
    • delete

      @TransportCompatibility({HTTP,GRPC}) boolean delete(BlobId blob)
      Deletes the requested 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
       }
       
      Returns:
      true if blob was deleted, false if it was not found
      Throws:
      StorageException - upon failure
    • compose

      Sends a compose request.

      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);
       
      Returns:
      the composed blob
      Throws:
      StorageException - upon failure
    • copy

      Sends a copy request. This method copies both blob's data and information. To override source blob's information supply a 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();
       
      Returns:
      a 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 needed
      Throws:
      StorageException - upon failure
      See Also:
    • readAllBytes

      @TransportCompatibility({HTTP,GRPC}) byte[] readAllBytes(String bucket, String blob, Storage.BlobSourceOption... options)
      Reads all the bytes from a blob.

      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));
       
      Returns:
      the blob's content
      Throws:
      StorageException - upon failure
    • readAllBytes

      @TransportCompatibility({HTTP,GRPC}) byte[] readAllBytes(BlobId blob, Storage.BlobSourceOption... options)
      Reads all the bytes from a blob.

      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));
       
      Returns:
      the blob's content
      Throws:
      StorageException - upon failure
    • batch

      Creates a new empty batch for grouping multiple service calls in one underlying RPC call.

      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
       
    • reader

      @TransportCompatibility({HTTP,GRPC}) com.google.cloud.ReadChannel reader(String bucket, String blob, Storage.BlobSourceOption... options)
      Returns a channel for reading the blob's content. 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.

      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();
         }
       }
       
      Throws:
      StorageException - upon failure
    • reader

      @TransportCompatibility({HTTP,GRPC}) com.google.cloud.ReadChannel reader(BlobId blob, Storage.BlobSourceOption... options)
      Returns a channel for reading the blob's content. If 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();
         }
       }
       
      Throws:
      StorageException - upon failure
    • downloadTo

      @TransportCompatibility({HTTP,GRPC}) void downloadTo(BlobId blob, Path path, Storage.BlobSourceOption... options)
      Downloads the given blob to the given path using specified blob read 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
       
      Parameters:
      blob -
      path -
      options -
      Throws:
      StorageException - upon failure
    • downloadTo

      @TransportCompatibility({HTTP,GRPC}) void downloadTo(BlobId blob, OutputStream outputStream, Storage.BlobSourceOption... options)
      Downloads the given blob to the given output stream using specified blob read 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
       }
       
      Parameters:
      blob -
      outputStream -
      options -
    • writer

      @TransportCompatibility({HTTP,GRPC}) com.google.cloud.WriteChannel writer(BlobInfo blobInfo, Storage.BlobWriteOption... options)
      Creates a blob and returns a channel for writing its content. By default any MD5 and CRC32C values in the given 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
       }
       
      Throws:
      StorageException - upon failure
    • writer

      @TransportCompatibility(HTTP) com.google.cloud.WriteChannel writer(URL signedURL)
      Accepts signed URL and return a channel for writing content.

      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));
       }
       
      Throws:
      StorageException - upon failure
    • signUrl

      @TransportCompatibility(HTTP) URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, Storage.SignUrlOption... options)
      Generates a signed URL for a blob. If you have a blob that you want to allow access to for a fixed amount of time, you can use this method to generate a URL that is only valid within a certain time period. This is particularly useful if you don't want publicly accessible blobs, but also don't want to require users to explicitly log in. Signing a URL requires a service account signer. If an instance of 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:

      1. The signer passed with the option Storage.SignUrlOption.signWith(ServiceAccountSigner)
      2. The credentials passed to StorageOptions
      3. The default credentials, if no credentials were passed to 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))));
       
      Parameters:
      blobInfo - the blob associated with the signed URL
      duration - time until the signed URL expires, expressed in unit. The finest granularity supported is 1 second, finer granularities will be truncated
      unit - time unit of the duration parameter
      options - optional URL signing options
      Throws:
      IllegalStateException - 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
      See Also:
    • generateSignedPostPolicyV4

      @TransportCompatibility(HTTP) 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. The returned map includes a signature which must be provided with the request. Generating a presigned POST policy requires a service account signer. If an instance of 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);
       
      Parameters:
      blobInfo - the blob uploaded in the form
      duration - time before expiration
      unit - duration time unit
      fields - the fields specified in the form
      conditions - which conditions every upload must satisfy
      duration - how long until the form expires, in milliseconds
      options - optional post policy options
      See Also:
    • generateSignedPostPolicyV4

      @TransportCompatibility(HTTP) PostPolicyV4 generateSignedPostPolicyV4(BlobInfo blobInfo, long duration, TimeUnit unit, PostPolicyV4.PostFieldsV4 fields, Storage.PostPolicyV4Option... options)
      Generates a presigned post policy without any conditions. Automatically creates required conditions. See full documentation for generateSignedPostPolicyV4(BlobInfo, long, TimeUnit, PostPolicyV4.PostFieldsV4, PostPolicyV4.PostConditionsV4, PostPolicyV4Option...).
    • generateSignedPostPolicyV4

      @TransportCompatibility(HTTP) PostPolicyV4 generateSignedPostPolicyV4(BlobInfo blobInfo, long duration, TimeUnit unit, PostPolicyV4.PostConditionsV4 conditions, Storage.PostPolicyV4Option... options)
      Generates a presigned post policy without any fields. Automatically creates required fields. See full documentation for generateSignedPostPolicyV4(BlobInfo, long, TimeUnit, PostPolicyV4.PostFieldsV4, PostPolicyV4.PostConditionsV4, PostPolicyV4Option...).
    • generateSignedPostPolicyV4

      @TransportCompatibility(HTTP) PostPolicyV4 generateSignedPostPolicyV4(BlobInfo blobInfo, long duration, TimeUnit unit, Storage.PostPolicyV4Option... options)
      Generates a presigned post policy without any fields or conditions. Automatically creates required fields and conditions. See full documentation for generateSignedPostPolicyV4(BlobInfo, long, TimeUnit, PostPolicyV4.PostFieldsV4, PostPolicyV4.PostConditionsV4, PostPolicyV4Option...).
    • get

      Gets the requested blobs. A batch request is used to perform this call.

      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);
       
      Parameters:
      blobIds - blobs to get
      Returns:
      an immutable list of Blob objects. If a blob does not exist or access to it has been denied the corresponding item in the list is null.
      Throws:
      StorageException - upon failure
    • get

      Gets the requested blobs. A batch request is used to perform this call.

      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);
       
      Parameters:
      blobIds - blobs to get
      Returns:
      an immutable list of Blob objects. If a blob does not exist or access to it has been denied the corresponding item in the list is null.
      Throws:
      StorageException - upon failure
    • update

      @TransportCompatibility(HTTP) List<Blob> update(BlobInfo... blobInfos)
      Updates the requested blobs. A batch request is used to perform this call. The original properties are merged with the properties in the provided 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());
       
      Parameters:
      blobInfos - blobs to update
      Returns:
      an immutable list of Blob objects. If a blob does not exist or access to it has been denied the corresponding item in the list is null.
      Throws:
      StorageException - upon failure
    • update

      Updates the requested blobs. A batch request is used to perform this call. The original properties are merged with the properties in the provided 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);
       
      Parameters:
      blobInfos - blobs to update
      Returns:
      an immutable list of Blob objects. If a blob does not exist or access to it has been denied the corresponding item in the list is null.
      Throws:
      StorageException - upon failure
    • delete

      Deletes the requested blobs. A batch request is used to perform this call.

      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);
       
      Parameters:
      blobIds - blobs to delete
      Returns:
      an immutable list of booleans. If a blob has been deleted the corresponding item in the list is true. If a blob was not found, deletion failed or access to the resource was denied the corresponding item is false.
      Throws:
      StorageException - upon failure
    • delete

      Deletes the requested blobs. A batch request is used to perform this call.

      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);
       
      Parameters:
      blobIds - blobs to delete
      Returns:
      an immutable list of booleans. If a blob has been deleted the corresponding item in the list is true. If a blob was not found, deletion failed or access to the resource was denied the corresponding item is false.
      Throws:
      StorageException - upon failure
    • getAcl

      Returns the ACL entry for the specified entity on the specified bucket or 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);
       

      Behavioral Differences between HTTP and gRPC

      1. Calling this method for a Bucket which has Uniform bucket-level access enabled exhibits different behavior Depending on which TransportCompatibility.Transport is used. For JSON, an HTTP 400 Bad Request error will be thrown. Whereas for gRPC, an empty list will be returned.
      Parameters:
      bucket - name of the bucket where the getAcl operation takes place
      entity - ACL entity to fetch
      options - extra parameters to apply to this operation
      Throws:
      StorageException - upon failure
    • getAcl

      @TransportCompatibility({HTTP,GRPC}) Acl getAcl(String bucket, Acl.Entity entity)
      See Also:
    • deleteAcl

      @TransportCompatibility({HTTP,GRPC}) boolean deleteAcl(String bucket, Acl.Entity entity, Storage.BucketSourceOption... options)
      Deletes the ACL entry for the specified entity on the specified bucket.

      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);
       
      Parameters:
      bucket - name of the bucket to delete an ACL from
      entity - ACL entity to delete
      options - extra parameters to apply to this operation
      Returns:
      true if the ACL was deleted, false if it was not found
      Throws:
      StorageException - upon failure
    • deleteAcl

      @TransportCompatibility({HTTP,GRPC}) boolean deleteAcl(String bucket, Acl.Entity entity)
      See Also:
    • createAcl

      @TransportCompatibility({HTTP,GRPC}) Acl createAcl(String bucket, Acl acl, Storage.BucketSourceOption... options)
      Creates a new ACL entry on the specified bucket.

      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"));
       
      Parameters:
      bucket - name of the bucket for which an ACL should be created
      acl - ACL to create
      options - extra parameters to apply to this operation
      Throws:
      StorageException - upon failure
    • createAcl

      @TransportCompatibility({HTTP,GRPC}) Acl createAcl(String bucket, Acl acl)
      See Also:
    • updateAcl

      @TransportCompatibility({HTTP,GRPC}) Acl updateAcl(String bucket, Acl acl, Storage.BucketSourceOption... options)
      Updates an ACL entry on the specified bucket.

      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"));
       
      Parameters:
      bucket - name of the bucket where the updateAcl operation takes place
      acl - ACL to update
      options - extra parameters to apply to this operation
      Throws:
      StorageException - upon failure
    • updateAcl

      @TransportCompatibility({HTTP,GRPC}) Acl updateAcl(String bucket, Acl acl)
      See Also:
    • listAcls

      Lists the ACL entries for the provided bucket.

      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
       }
       

      Behavioral Differences between HTTP and gRPC

      1. Calling this method for a Bucket which has Uniform bucket-level access enabled exhibits different behavior Depending on which TransportCompatibility.Transport is used. For JSON, an HTTP 400 Bad Request error will be thrown. Whereas for gRPC, an empty list will be returned.
      Parameters:
      bucket - the name of the bucket to list ACLs for
      options - any number of BucketSourceOptions to apply to this operation
      Throws:
      StorageException - upon failure
    • listAcls

      See Also:
    • getDefaultAcl

      @TransportCompatibility({HTTP,GRPC}) 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.

      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());
       

      Behavioral Differences between HTTP and gRPC

      1. Calling this method for a Bucket which has Uniform bucket-level access enabled exhibits different behavior Depending on which TransportCompatibility.Transport is used. For JSON, an HTTP 400 Bad Request error will be thrown. Whereas for gRPC, an empty list will be returned.
      Throws:
      StorageException - upon failure
    • deleteDefaultAcl

      @TransportCompatibility({HTTP,GRPC}) boolean deleteDefaultAcl(String bucket, Acl.Entity entity)
      Deletes the default object ACL entry for the specified entity on the specified bucket.

      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
       }
       
      Returns:
      true if the ACL was deleted, false if it was not found
      Throws:
      StorageException - upon failure
    • createDefaultAcl

      @TransportCompatibility({HTTP,GRPC}) Acl createDefaultAcl(String bucket, Acl acl)
      Creates a new default blob ACL entry on the specified bucket.

      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));
       
      Throws:
      StorageException - upon failure
    • updateDefaultAcl

      @TransportCompatibility({HTTP,GRPC}) Acl updateDefaultAcl(String bucket, Acl acl)
      Updates a default blob ACL entry on the specified bucket.

      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));
       
      Throws:
      StorageException - upon failure
    • listDefaultAcls

      @TransportCompatibility({HTTP,GRPC}) List<Acl> listDefaultAcls(String bucket)
      Lists the default blob ACL entries for the provided 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
       }
       

      Behavioral Differences between HTTP and gRPC

      1. Calling this method for a Bucket which has Uniform bucket-level access enabled exhibits different behavior Depending on which TransportCompatibility.Transport is used. For JSON, an HTTP 400 Bad Request error will be thrown. Whereas for gRPC, an empty list will be returned.
      Throws:
      StorageException - upon failure
    • getAcl

      Returns the ACL entry for the specified entity on the specified blob or 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));
       
      Throws:
      StorageException - upon failure
    • deleteAcl

      @TransportCompatibility({HTTP,GRPC}) boolean deleteAcl(BlobId blob, Acl.Entity entity)
      Deletes the ACL entry for the specified entity on the specified blob.

      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
       }
       
      Returns:
      true if the ACL was deleted, false if it was not found
      Throws:
      StorageException - upon failure
    • createAcl

      @TransportCompatibility({HTTP,GRPC}) Acl createAcl(BlobId blob, Acl acl)
      Creates a new ACL entry on the specified blob.

      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));
       
      Throws:
      StorageException - upon failure
    • updateAcl

      @TransportCompatibility({HTTP,GRPC}) Acl updateAcl(BlobId blob, Acl acl)
      Updates an ACL entry on the specified blob.

      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));
       
      Throws:
      StorageException - upon failure
    • listAcls

      Lists the ACL entries for the provided 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
       }
       
      Throws:
      StorageException - upon failure
    • createHmacKey

      @TransportCompatibility({HTTP,GRPC}) HmacKey createHmacKey(ServiceAccount serviceAccount, Storage.CreateHmacKeyOption... options)
      Creates a new HMAC Key for the provided service account, including the secret key. Note that the secret key is only returned upon creation via this method.

      Example of creating a new HMAC Key.

      
       ServiceAccount serviceAccount = ServiceAccount.of("[email protected]");
      
       HmacKey hmacKey = storage.createHmacKey(serviceAccount);
      
       String secretKey = hmacKey.getSecretKey();
       HmacKey.HmacKeyMetadata metadata = hmacKey.getMetadata();
       
      Throws:
      StorageException - upon failure
    • listHmacKeys

      @TransportCompatibility({HTTP,GRPC}) com.google.api.gax.paging.Page<HmacKey.HmacKeyMetadata> listHmacKeys(Storage.ListHmacKeysOption... options)
      Lists HMAC keys for a given service account. Note this returns 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("[email protected]");
      
       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
       }
       
      Parameters:
      options - the options to apply to this operation
      Throws:
      StorageException - upon failure
    • getHmacKey

      Gets an HMAC key given its access id. Note that this returns a 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);
       
      Throws:
      StorageException - upon failure
    • deleteHmacKey

      @TransportCompatibility({HTTP,GRPC}) void deleteHmacKey(HmacKey.HmacKeyMetadata hmacKeyMetadata, Storage.DeleteHmacKeyOption... options)
      Deletes an HMAC key. Note that only an 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);
       
      Throws:
      StorageException - upon failure
    • updateHmacKeyState

      Updates the state of an HMAC key and returns the updated metadata.

      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);
       
      Throws:
      StorageException - upon failure
    • getIamPolicy

      @TransportCompatibility({HTTP,GRPC}) com.google.cloud.Policy getIamPolicy(String bucket, Storage.BucketSourceOption... options)
      Gets the IAM policy for the provided bucket.

      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);
       
      Parameters:
      bucket - name of the bucket where the getIamPolicy operation takes place
      options - extra parameters to apply to this operation
      Throws:
      StorageException - upon failure
    • setIamPolicy

      @TransportCompatibility({HTTP,GRPC}) com.google.cloud.Policy setIamPolicy(String bucket, com.google.cloud.Policy policy, Storage.BucketSourceOption... options)
      Updates the IAM policy on the specified bucket.

      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());
       
      Parameters:
      bucket - name of the bucket where the setIamPolicy operation takes place
      policy - policy to be set on the specified bucket
      options - extra parameters to apply to this operation
      Throws:
      StorageException - upon failure
    • testIamPermissions

      @TransportCompatibility({HTTP,GRPC}) List<Boolean> testIamPermissions(String bucket, List<String> permissions, Storage.BucketSourceOption... options)
      Tests whether the caller holds the permissions on the specified bucket. Returns a list of booleans in the same placement and order in which the permissions were specified.

      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
       }
       
      Parameters:
      bucket - name of the bucket where the testIamPermissions operation takes place
      permissions - list of permissions to test on the bucket
      options - extra parameters to apply to this operation
      Throws:
      StorageException - upon failure
    • getServiceAccount

      @TransportCompatibility({HTTP,GRPC}) ServiceAccount getServiceAccount(String projectId)
      Returns the service account associated with the given project.

      Example of getting a service account.

      
       String projectId = "[email protected]";
       ServiceAccount account = storage.getServiceAccount(projectId);
       
      Parameters:
      projectId - the ID of the project for which the service account should be fetched.
      Returns:
      the service account associated with this project
      Throws:
      StorageException - upon failure
    • createNotification

      @TransportCompatibility({HTTP,GRPC}) Notification createNotification(String bucket, NotificationInfo notificationInfo)
      Creates the notification for a given bucket.

      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);
       
      Parameters:
      bucket - name of the bucket
      notificationInfo - notification to create
      Returns:
      the created notification
      Throws:
      StorageException - upon failure
    • getNotification

      @TransportCompatibility({HTTP,GRPC}) Notification getNotification(String bucket, String notificationId)
      Gets the notification with the specified id.

      Example of getting the notification:

      
       String bucketName = "my-unique-bucket";
       String notificationId = "my-unique-notification-id";
       Notification notification = storage.getNotification(bucketName, notificationId);
       
      Parameters:
      bucket - name of the bucket
      notificationId - notification ID
      Returns:
      the Notification object with the given id or null if not found
      Throws:
      StorageException - upon failure
    • listNotifications

      @TransportCompatibility({HTTP,GRPC}) List<Notification> listNotifications(String bucket)
      Retrieves the list of notifications associated with the bucket.

      Example of listing the bucket notifications:

      
       String bucketName = "my-unique-bucket";
       List<Notification> notifications = storage.listNotifications(bucketName);
       
      Parameters:
      bucket - name of the bucket
      Returns:
      a list of Notification objects added to the bucket.
      Throws:
      StorageException - upon failure
    • deleteNotification

      @TransportCompatibility({HTTP,GRPC}) boolean deleteNotification(String bucket, String notificationId)
      Deletes the notification with the specified id.

      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
       }
       
      Parameters:
      bucket - name of the bucket
      notificationId - ID of the notification to delete
      Returns:
      true if the notification has been deleted, false if not found
      Throws:
      StorageException - upon failure
    • close

      default void close() throws Exception
      Specified by:
      close in interface AutoCloseable
      Throws:
      InterruptedException - thrown if interrupted while awaiting termination of underlying resources
      Exception
    • blobWriteSession

      @BetaApi @TransportCompatibility(GRPC) default BlobWriteSession blobWriteSession(BlobInfo blobInfo, Storage.BlobWriteOption... options)
      Create a new BlobWriteSession for the specified blobInfo and options.

      The returned BlobWriteSession can be used to write an individual version, a new session must be created each time you want to create a new version.

      By default, any MD5 value in the provided blobInfo is ignored unless the option Storage.BlobWriteOption.md5Match() is included in options.

      By default, any CRC32c value in the provided blobInfo is ignored unless the option Storage.BlobWriteOption.crc32cMatch() is included in options.

      Example of creating an object using BlobWriteSession:

      
       String bucketName = "my-unique-bucket";
       String blobName = "my-blob-name";
       BlobId blobId = BlobId.of(bucketName, blobName);
       BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
       ReadableByteChannel readableByteChannel = ...;
       BlobWriteSession blobWriteSession = storage.blobWriteSession(blobInfo, BlobWriteOption.doesNotExist());
      
       // open the channel for writing
       try (WritableByteChannel writableByteChannel = blobWriteSession.open()) {
         // copy all bytes
         ByteStreams.copy(readableByteChannel, writableByteChannel);
       } catch (IOException e) {
         // handle IOException
       }
      
       // get the resulting object metadata
       ApiFuture<BlobInfo> resultFuture = blobWriteSession.getResult();
       BlobInfo gen1 = resultFuture.get();
       
      Parameters:
      blobInfo - blob to create
      options - blob write options
      Since:
      2.26.0 This new api is in preview and is subject to breaking changes.
      See Also: