Java Code Examples for com.google.cloud.storage.Storage

The following examples show how to use com.google.cloud.storage.Storage. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void genericTry(final List<List<SinkRecord>> recordBatches,
                        final Integer maxRecordsPerFile) {
    final Storage storage = LocalStorageHelper.getOptions().getService();
    final BucketAccessor testBucketAccessor = new BucketAccessor(storage, TEST_BUCKET, true);

    final Map<String, String> taskProps = basicTaskProps();
    if (maxRecordsPerFile != null) {
        taskProps.put(GcsSinkConfig.FILE_MAX_RECORDS, Integer.toString(maxRecordsPerFile));
    }
    final GcsSinkTask task = new GcsSinkTask(taskProps, storage);

    for (final List<SinkRecord> recordBatch : recordBatches) {
        task.put(recordBatch);
        task.flush(null);
    }

    checkExpectedFileNames(recordBatches, maxRecordsPerFile, testBucketAccessor);
    checkFileSizes(testBucketAccessor, maxRecordsPerFile);
    final int expectedRecordCount = recordBatches.stream().mapToInt(List::size).sum();
    checkTotalRecordCountAndNoMultipleWrites(expectedRecordCount, testBucketAccessor);
    checkTopicPartitionPartInFileNames(testBucketAccessor);
    checkOffsetOrderInFiles(testBucketAccessor);
}
 
Example 2
Source Project: nifi   Source File: PutGCSObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAclAttributeGroup() throws Exception {
    reset(storage, blob);
    final PutGCSObject processor = getProcessor();
    final TestRunner runner = buildNewRunner(processor);
    addRequiredPropertiesToRunner(runner);
    runner.assertValid();

    when(storage.create(any(BlobInfo.class), any(InputStream.class), any(Storage.BlobWriteOption.class)))
            .thenReturn(blob);

    final Acl.Group mockGroup = mock(Acl.Group.class);
    when(mockGroup.getEmail()).thenReturn(OWNER_GROUP_EMAIL);
    when(blob.getOwner()).thenReturn(mockGroup);

    runner.enqueue("test");
    runner.run();

    runner.assertAllFlowFilesTransferred(PutGCSObject.REL_SUCCESS);
    runner.assertTransferCount(PutGCSObject.REL_SUCCESS, 1);

    final MockFlowFile mockFlowFile = runner.getFlowFilesForRelationship(PutGCSObject.REL_SUCCESS).get(0);
    mockFlowFile.assertAttributeEquals(OWNER_ATTR, OWNER_GROUP_EMAIL);
    mockFlowFile.assertAttributeEquals(OWNER_TYPE_ATTR, "group");
}
 
Example 3
Source Project: nifi   Source File: AbstractGCSIT.java    License: Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void tearDown() {
    try {
        // Empty the bucket before deleting it.
        Iterable<Blob> blobIterable = storage.list(BUCKET, Storage.BlobListOption.versions(true)).iterateAll();

        for (final Blob blob : blobIterable) {
            storage.delete(blob.getBlobId());
        }

        storage.delete(BUCKET);
    } catch (final StorageException e) {
        fail("Unable to delete bucket " + BUCKET + ": " + e.getLocalizedMessage());
    }

    if (storage.get(BUCKET) != null) {
        fail("Incomplete teardown, subsequent tests might fail");
    }
}
 
Example 4
/**
 * Copy a blob for gcs to a destination bucket and a path (and delete the source blob if needed)
 * @param sourceBlobId sourceBlobId
 * @param destinationBucket destination bucket
 * @param destinationPath destination path
 * @param deleteSource delete source blob
 */
private void copy(BlobId sourceBlobId, String destinationBucket, String destinationPath, boolean deleteSource) {
  LOG.debug(
      "Copying object '{}' to Object '{}'",
      String.format(BLOB_PATH_TEMPLATE, sourceBlobId.getBucket(), sourceBlobId.getName()),
      String.format(BLOB_PATH_TEMPLATE, destinationBucket, destinationPath)
  );

  Storage.CopyRequest copyRequest = new Storage.CopyRequest.Builder()
      .setSource(sourceBlobId)
      .setTarget(BlobId.of(destinationBucket, destinationPath))
      .build();
  Blob destinationBlob = storage.copy(copyRequest).getResult();
  LOG.debug(
      "Copied object '{}' to Object '{}'",
      String.format(BLOB_PATH_TEMPLATE, sourceBlobId.getBucket(), sourceBlobId.getName()),
      String.format(BLOB_PATH_TEMPLATE, destinationBlob.getBlobId().getBucket(), destinationBlob.getBlobId().getName())
  );
  if (deleteSource) {
    delete(sourceBlobId);
  }
}
 
Example 5
Source Project: nifi   Source File: ListGCSBucketTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testYieldOnBadStateRestore() throws Exception {
    reset(storage, mockBlobPage);
    final ListGCSBucket processor = getProcessor();
    final TestRunner runner = buildNewRunner(processor);
    addRequiredPropertiesToRunner(runner);
    runner.assertValid();

    final Iterable<Blob> mockList = ImmutableList.of();

    when(mockBlobPage.getValues()).thenReturn(mockList);
    when(mockBlobPage.getNextPage()).thenReturn(null);
    when(storage.list(anyString(), any(Storage.BlobListOption[].class))).thenReturn(mockBlobPage);

    runner.getStateManager().setFailOnStateGet(Scope.CLUSTER, true);
    runner.enqueue("test");
    runner.run();

    runner.assertTransferCount(ListGCSBucket.REL_SUCCESS, 0);
    assertEquals(1, runner.getLogger().getErrorMessages().size());
}
 
Example 6
Source Project: google-cloud-java   Source File: StorageSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of how to set event-based hold for a blob */
public Blob setEventBasedHold(String bucketName, String blobName) throws StorageException {
  // [START storage_set_event_based_hold]
  // Instantiate a Google Cloud Storage client
  Storage storage = StorageOptions.getDefaultInstance().getService();

  // The name of a bucket, e.g. "my-bucket"
  // String bucketName = "my-bucket";

  // The name of a blob, e.g. "my-blob"
  // String blobName = "my-blob";

  BlobId blobId = BlobId.of(bucketName, blobName);
  Blob blob = storage.update(BlobInfo.newBuilder(blobId).setEventBasedHold(true).build());

  System.out.println("Event-based hold was set for " + blobName);
  // [END storage_set_event_based_hold]
  return blob;
}
 
Example 7
Source Project: google-cloud-java   Source File: StorageSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of setting a default KMS key on a bucket. */
public Bucket setDefaultKmsKey(String bucketName, String kmsKeyName) throws StorageException {
  // [START storage_set_bucket_default_kms_key]
  // Instantiate a Google Cloud Storage client
  Storage storage = StorageOptions.getDefaultInstance().getService();

  // The name of the existing bucket to set a default KMS key for, e.g. "my-bucket"
  // String bucketName = "my-bucket"

  // The name of the KMS-key to use as a default
  // Key names are provided in the following format:
  // 'projects/<PROJECT>/locations/<LOCATION>/keyRings/<RING_NAME>/cryptoKeys/<KEY_NAME>'
  // String kmsKeyName = ""

  BucketInfo bucketInfo =
      BucketInfo.newBuilder(bucketName).setDefaultKmsKeyName(kmsKeyName).build();

  Bucket bucket = storage.update(bucketInfo);

  System.out.println("Default KMS Key Name: " + bucket.getDefaultKmsKeyName());
  // [END storage_set_bucket_default_kms_key]
  return bucket;
}
 
Example 8
public static void enableLifecycleManagement(String projectId, String bucketName) {
  // The ID of your GCP project
  // String projectId = "your-project-id";

  // The ID of your GCS bucket
  // String bucketName = "your-unique-bucket-name";

  Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
  Bucket bucket = storage.get(bucketName);

  // See the LifecycleRule documentation for additional info on what you can do with lifecycle
  // management rules. This one deletes objects that are over 100 days old.
  // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/BucketInfo.LifecycleRule.html
  bucket
      .toBuilder()
      .setLifecycleRules(
          ImmutableList.of(
              new LifecycleRule(
                  LifecycleRule.LifecycleAction.newDeleteAction(),
                  LifecycleRule.LifecycleCondition.newBuilder().setAge(100).build())))
      .build()
      .update();

  System.out.println("Lifecycle management was enabled and configured for bucket " + bucketName);
}
 
Example 9
Source Project: google-cloud-java   Source File: StorageSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of how to disable default event-based hold for a bucket */
public Bucket disableDefaultEventBasedHold(String bucketName) throws StorageException {
  // [START storage_disable_default_event_based_hold]
  // Instantiate a Google Cloud Storage client
  Storage storage = StorageOptions.getDefaultInstance().getService();

  // The name of a bucket, e.g. "my-bucket"
  // String bucketName = "my-bucket";

  Bucket bucket =
      storage.update(BucketInfo.newBuilder(bucketName).setDefaultEventBasedHold(false).build());

  System.out.println("Default event-based hold was disabled for " + bucketName);
  // [END storage_disable_default_event_based_hold]
  return bucket;
}
 
Example 10
Source Project: google-cloud-java   Source File: StorageSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of how to enable uniform bucket-level access for a bucket */
public Bucket enableUniformBucketLevelAccess(String bucketName) throws StorageException {
  // [START storage_enable_uniform_bucket_level_access]
  // Instantiate a Google Cloud Storage client
  Storage storage = StorageOptions.getDefaultInstance().getService();

  // The name of a bucket, e.g. "my-bucket"
  // String bucketName = "my-bucket";

  BucketInfo.IamConfiguration iamConfiguration =
      BucketInfo.IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build();
  Bucket bucket =
      storage.update(
          BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

  System.out.println("Uniform bucket-level access was enabled for " + bucketName);
  // [END storage_enable_uniform_bucket_level_access]
  return bucket;
}
 
Example 11
public static void changeDefaultStorageClass(String projectId, String bucketName) {
  // The ID of your GCP project
  // String projectId = "your-project-id";

  // The ID of your GCS bucket
  // String bucketName = "your-unique-bucket-name";

  // See the StorageClass documentation for other valid storage classes:
  // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
  StorageClass storageClass = StorageClass.COLDLINE;

  Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
  Bucket bucket = storage.get(bucketName);
  bucket = bucket.toBuilder().setStorageClass(storageClass).build().update();

  System.out.println(
      "Default storage class for bucket "
          + bucketName
          + " has been set to "
          + bucket.getStorageClass());
}
 
Example 12
Source Project: google-cloud-java   Source File: DownloadEncryptedObject.java    License: Apache License 2.0 6 votes vote down vote up
public static void downloadEncryptedObject(
    String projectId,
    String bucketName,
    String objectName,
    Path destFilePath,
    String decryptionKey)
    throws IOException {

  // The ID of your GCP project
  // String projectId = "your-project-id";

  // The ID of your GCS bucket
  // String bucketName = "your-unique-bucket-name";

  // The ID of your GCS object
  // String objectName = "your-object-name";

  // The path to which the file should be downloaded
  // Path destFilePath = Paths.get("/local/path/to/file.txt");

  // The Base64 encoded decryption key, which should be the same key originally used to encrypt
  // the object
  // String decryptionKey = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=";

  Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

  Blob blob = storage.get(bucketName, objectName);
  blob.downloadTo(destFilePath, Blob.BlobSourceOption.decryptionKey(decryptionKey));

  System.out.println(
      "Downloaded object "
          + objectName
          + " from bucket name "
          + bucketName
          + " to "
          + destFilePath
          + " using customer-supplied encryption key");
}
 
Example 13
Source Project: nifi   Source File: ListGCSBucketTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testListOptionsVersions() throws Exception {
    reset(storage, mockBlobPage);
    final ListGCSBucket processor = getProcessor();
    final TestRunner runner = buildNewRunner(processor);
    addRequiredPropertiesToRunner(runner);

    runner.setProperty(ListGCSBucket.USE_GENERATIONS, String.valueOf(USE_GENERATIONS));
    runner.assertValid();

    final Iterable<Blob> mockList = ImmutableList.of();

    when(mockBlobPage.getValues()).thenReturn(mockList);
    when(mockBlobPage.getNextPage()).thenReturn(null);
    when(storage.list(anyString(), argumentCaptor.capture())).thenReturn(mockBlobPage);

    runner.enqueue("test");
    runner.run();

    Storage.BlobListOption option = argumentCaptor.getValue();
    assertEquals(Storage.BlobListOption.versions(true), option);
}
 
Example 14
Source Project: localization_nifi   Source File: FetchGCSObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testStorageExceptionOnFetch() throws Exception {
    reset(storage);
    final TestRunner runner = buildNewRunner(getProcessor());
    addRequiredPropertiesToRunner(runner);
    runner.assertValid();

    when(storage.get(any(BlobId.class))).thenThrow(new StorageException(400, "test-exception"));
    when(storage.reader(any(BlobId.class), any(Storage.BlobSourceOption.class))).thenReturn(new MockReadChannel(CONTENT));

    runner.enqueue("");

    runner.run();

    runner.assertAllFlowFilesTransferred(FetchGCSObject.REL_FAILURE);
    runner.assertTransferCount(FetchGCSObject.REL_FAILURE, 1);
}
 
Example 15
Source Project: localization_nifi   Source File: AbstractGCSIT.java    License: Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void tearDown() {
    try {
        // Empty the bucket before deleting it.
        Iterator<Blob> blobIterator = storage.list(BUCKET, Storage.BlobListOption.versions(true)).iterateAll();

        while(blobIterator.hasNext()) {
            Blob blob = blobIterator.next();
            storage.delete(blob.getBlobId());
        }

        storage.delete(BUCKET);
    } catch (final StorageException e) {
        fail("Unable to delete bucket " + BUCKET + ": " + e.getLocalizedMessage());
    }

    if (storage.get(BUCKET) != null) {
        fail("Incomplete teardown, subsequent tests might fail");
    }
}
 
Example 16
Source Project: java-docs-samples   Source File: QuickStartIT.java    License: Apache License 2.0 6 votes vote down vote up
private static final void deleteObjects() {
  Storage storage = StorageOptions.getDefaultInstance().getService();
  for (BlobInfo info :
      storage
          .list(
              bucketName,
              BlobListOption.versions(true),
              BlobListOption.currentDirectory(),
              BlobListOption.prefix(path + "/"))
          .getValues()) {
    storage.delete(info.getBlobId());
  }
}
 
Example 17
Source Project: google-cloud-java   Source File: StorageSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of deleting an existing inactive HMAC key. * */
public void deleteHmacKey(String accessId, String projectId) throws StorageException {
  // [START storage_delete_hmac_key]
  // Instantiate a Google Cloud Storage client
  Storage storage = StorageOptions.getDefaultInstance().getService();

  // The access ID of the HMAC key, e.g. "GOOG0234230X00"
  // String accessId = "GOOG0234230X00";
  //
  // The ID of the project to which the service account belongs.
  // String projectId = "project-id";
  HmacKeyMetadata metadata =
      storage.getHmacKey(accessId, Storage.GetHmacKeyOption.projectId(projectId));
  storage.deleteHmacKey(metadata);

  System.out.println(
      "The key is deleted, though it will still appear in getHmacKeys() results given showDeletedKey is true.");
  // [END storage_delete_hmac_key]
}
 
Example 18
@Bean
public Storage gcsClient() {
	Storage gcs = mock(Storage.class);

	willAnswer((invocationOnMock) ->
		new PageImpl<>(null, null,
				Stream.of(
						createBlob("gcsbucket", "gamma"),
						createBlob("gcsbucket", "beta"),
						createBlob("gcsbucket", "alpha/alpha"))
						.collect(Collectors.toList())))
			.given(gcs).list(eq("gcsbucket"));

	willAnswer((invocationOnMock) -> mock(ReadChannel.class))
			.given(gcs).reader(eq("gcsbucket"), eq("alpha/alpha"));
	willAnswer((invocationOnMock) -> mock(ReadChannel.class))
			.given(gcs).reader(eq("gcsbucket"), eq("beta"));
	willAnswer((invocationOnMock) -> mock(ReadChannel.class))
			.given(gcs).reader(eq("gcsbucket"), eq("gamma"));

	return gcs;
}
 
Example 19
Source Project: google-cloud-java   Source File: StorageExample.java    License: Apache License 2.0 6 votes vote down vote up
private void run(Storage storage, Path uploadFrom, BlobInfo blobInfo) throws IOException {
  if (Files.size(uploadFrom) > 1_000_000) {
    // When content is not available or large (1MB or more) it is recommended
    // to write it in chunks via the blob's channel writer.
    try (WriteChannel writer = storage.writer(blobInfo)) {
      byte[] buffer = new byte[1024];
      try (InputStream input = Files.newInputStream(uploadFrom)) {
        int limit;
        while ((limit = input.read(buffer)) >= 0) {
          try {
            writer.write(ByteBuffer.wrap(buffer, 0, limit));
          } catch (Exception ex) {
            ex.printStackTrace();
          }
        }
      }
    }
  } else {
    byte[] bytes = Files.readAllBytes(uploadFrom);
    // create the blob in one request.
    storage.create(blobInfo, bytes);
  }
  System.out.println("Blob was created");
}
 
Example 20
Source Project: nifi   Source File: PutGCSObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAclAttributeProject() throws Exception {
    reset(storage, blob);
    final PutGCSObject processor = getProcessor();
    final TestRunner runner = buildNewRunner(processor);
    addRequiredPropertiesToRunner(runner);
    runner.assertValid();

    when(storage.create(any(BlobInfo.class), any(InputStream.class), any(Storage.BlobWriteOption.class)))
            .thenReturn(blob);

    final Acl.Project mockProject = mock(Acl.Project.class);
    when(mockProject.getProjectId()).thenReturn(OWNER_PROJECT_ID);
    when(blob.getOwner()).thenReturn(mockProject);

    runner.enqueue("test");
    runner.run();

    runner.assertAllFlowFilesTransferred(PutGCSObject.REL_SUCCESS);
    runner.assertTransferCount(PutGCSObject.REL_SUCCESS, 1);

    final MockFlowFile mockFlowFile = runner.getFlowFilesForRelationship(PutGCSObject.REL_SUCCESS).get(0);
    mockFlowFile.assertAttributeEquals(OWNER_ATTR, OWNER_PROJECT_ID);
    mockFlowFile.assertAttributeEquals(OWNER_TYPE_ATTR, "project");
}
 
Example 21
Source Project: metastore   Source File: GoogleCloudStorage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ByteString read() {
  BlobId blobId = BlobId.of(bucket, fileName);
  if (storage.get(blobId) != null && storage.get(blobId).exists()) {
    byte[] buffer = storage.readAllBytes(blobId, Storage.BlobSourceOption.userProject(project));
    return ByteString.copyFrom(buffer);
  } else {
    return null;
  }
}
 
Example 22
private static void deleteDirectory(Storage storage, Page<Blob> blobs) {
  for (Blob blob : blobs.iterateAll()) {
    System.out.println(blob.getBlobId());
    if (!blob.delete()) {
      Page<Blob> subBlobs =
          storage.list(
              PROJECT_ID,
              Storage.BlobListOption.currentDirectory(),
              Storage.BlobListOption.prefix(blob.getName()));

      deleteDirectory(storage, subBlobs);
    }
  }
}
 
Example 23
private static void deleteDirectory(Storage storage, Page<Blob> blobs) {
  for (Blob blob : blobs.iterateAll()) {
    System.out.println(blob.getBlobId());
    if (!blob.delete()) {
      Page<Blob> subBlobs =
          storage.list(
              PROJECT_ID,
              Storage.BlobListOption.currentDirectory(),
              Storage.BlobListOption.prefix(blob.getName()));

      deleteDirectory(storage, subBlobs);
    }
  }
}
 
Example 24
Source Project: beast   Source File: BeastFactory.java    License: Apache License 2.0 5 votes vote down vote up
private BQErrorHandler createOOBErrorHandler() {
    final Storage gcsStore = getGCStorageInstance();
    ErrorWriter errorWriter = new DefaultLogWriter();
    if (appConfig.isGCSErrorSinkEnabled()) {
        final String bucketName = appConfig.getGcsBucket();
        final String basePathPrefix = appConfig.getGcsPathPrefix();
        errorWriter = new GCSErrorWriter(gcsStore, bucketName, basePathPrefix);
    }
    return new OOBErrorHandler(errorWriter);
}
 
Example 25
private static final void cleanUpBucket() {
  Storage storage = StorageOptions.getDefaultInstance().getService();
  Page<Blob> blobs =
      storage.list(
          PROJECT_ID,
          Storage.BlobListOption.currentDirectory(),
          Storage.BlobListOption.prefix(PREFIX));

  deleteDirectory(storage, blobs);
}
 
Example 26
Source Project: spring-cloud-gcp   Source File: GoogleStorageTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void signedUrlFunctionCalled() throws IOException {
	String location = "gs://test-spring/t1/test.png";
	Storage storage = mock(Storage.class);
	Blob blob = mock(Blob.class);
	when(blob.getBucket()).thenReturn("fakeBucket");
	when(blob.getName()).thenReturn("fakeObject");
	GoogleStorageResource resource = new GoogleStorageResource(storage, location);
	when(storage.get(any(BlobId.class))).thenReturn(blob);
	Storage.SignUrlOption option = Storage.SignUrlOption.httpMethod(HttpMethod.PUT);
	resource.createSignedUrl(TimeUnit.DAYS, 1L, option);
	verify(storage, times(1)).signUrl(any(), eq(1L), eq(TimeUnit.DAYS), eq(option));
}
 
Example 27
Storage create(final BlobStoreConfiguration configuration) throws Exception {
  StorageOptions.Builder builder = StorageOptions.newBuilder().setTransportOptions(transportOptions());

  String credentialFile = configuration.attributes(CONFIG_KEY).get(CREDENTIAL_FILE_KEY, String.class);
  if (StringUtils.hasText(credentialFile)) {
    ServiceAccountCredentials credentials = ServiceAccountCredentials.fromStream(new FileInputStream(credentialFile));
    logger.debug("loaded {} from {} for Google storage client", credentials, credentialFile);
    builder.setCredentials(credentials);
    builder.setProjectId(getProjectId(credentialFile));
  }

  return builder.build().getService();
}
 
Example 28
Source Project: spring-cloud-gcp   Source File: GoogleStorageTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetInputStreamOnNullBlob() throws Exception {
	this.expectedEx.expect(FileNotFoundException.class);
	this.expectedEx.expectMessage("The blob was not found: gs://test-spring/test");
	String location = "gs://test-spring/test";
	Storage storage = mock(Storage.class);
	when(storage.get(BlobId.of("test-spring", "test"))).thenReturn(null);

	GoogleStorageResource resource = new GoogleStorageResource(storage, location,
			false);
	resource.getInputStream();
}
 
Example 29
Source Project: java-docs-samples   Source File: AuthExample.java    License: Apache License 2.0 5 votes vote down vote up
static void authImplicit() {
  // If you don't specify credentials when constructing the client, the client library will
  // look for credentials via the environment variable GOOGLE_APPLICATION_CREDENTIALS.
  Storage storage = StorageOptions.getDefaultInstance().getService();

  System.out.println("Buckets:");
  Page<Bucket> buckets = storage.list();
  for (Bucket bucket : buckets.iterateAll()) {
    System.out.println(bucket.toString());
  }
}
 
Example 30
public static BlobId uploadConfig(String contents, String gcsPath, String fileName) {
  GcsPath path = GcsPath.fromUri(URI.create(gcsPath));
  Storage storage = StorageOptions.getDefaultInstance().getService();
  BlobId blobId = BlobId.of(path.getBucket(), fileName);
  BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("application/json").build();
  Blob blob = storage.create(blobInfo, contents.getBytes(UTF_8));
  return blob.getBlobId();
}