|
| 1 | +/* |
| 2 | + * Copyright 2022 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.storage.object; |
| 18 | + |
| 19 | +// [START storage_batch_request] |
| 20 | +import com.google.api.gax.paging.Page; |
| 21 | +import com.google.cloud.storage.Blob; |
| 22 | +import com.google.cloud.storage.Storage; |
| 23 | +import com.google.cloud.storage.StorageBatch; |
| 24 | +import com.google.cloud.storage.StorageOptions; |
| 25 | +import java.util.HashMap; |
| 26 | +import java.util.Map; |
| 27 | + |
| 28 | +public class BatchSetObjectMetadata { |
| 29 | + public static void batchSetObjectMetadata( |
| 30 | + String projectId, String bucketName, String directoryPrefix) { |
| 31 | + // The ID of your GCP project |
| 32 | + // String projectId = "your-project-id"; |
| 33 | + |
| 34 | + // The ID of your GCS bucket |
| 35 | + // String bucketName = "your-unique-bucket-name"; |
| 36 | + |
| 37 | + // The directory prefix. All objects in the bucket with this prefix will have their metadata |
| 38 | + // updated |
| 39 | + // String directoryPrefix = "yourDirectory/"; |
| 40 | + |
| 41 | + Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService(); |
| 42 | + Map<String, String> newMetadata = new HashMap<>(); |
| 43 | + newMetadata.put("keyToAddOrUpdate", "value"); |
| 44 | + Page<Blob> blobs = |
| 45 | + storage.list( |
| 46 | + bucketName, |
| 47 | + Storage.BlobListOption.prefix(directoryPrefix), |
| 48 | + Storage.BlobListOption.currentDirectory()); |
| 49 | + StorageBatch batchRequest = storage.batch(); |
| 50 | + |
| 51 | + // Add all blobs with the given prefix to the batch request |
| 52 | + for (Blob blob : blobs.iterateAll()) { |
| 53 | + batchRequest.update(blob.toBuilder().setMetadata(newMetadata).build()); |
| 54 | + } |
| 55 | + |
| 56 | + // Execute the batch request |
| 57 | + batchRequest.submit(); |
| 58 | + |
| 59 | + System.out.println( |
| 60 | + "All blobs in bucket " |
| 61 | + + bucketName |
| 62 | + + " with prefix '" |
| 63 | + + directoryPrefix |
| 64 | + + "' had their metadata updated."); |
| 65 | + } |
| 66 | +} |
| 67 | +// [END storage_batch_request] |
0 commit comments