Skip to content

Commit 1876a58

Browse files
feat: Add from and to storage url options for BlobId (#888)
* Add from and to storage url options for BlobId * Better name
1 parent 73e7cdf commit 1876a58

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

google-cloud-storage/src/main/java/com/google/cloud/storage/BlobId.java

+23
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import com.google.common.base.MoreObjects;
2323
import java.io.Serializable;
2424
import java.util.Objects;
25+
import java.util.regex.Pattern;
2526

2627
/**
2728
* Google Storage Object identifier. A {@code BlobId} object includes the name of the containing
@@ -56,6 +57,11 @@ public Long getGeneration() {
5657
return generation;
5758
}
5859

60+
/** Returns this blob's Storage url which can be used with gsutil */
61+
public String toGsUtilUri() {
62+
return "gs://" + bucket + "/" + name;
63+
}
64+
5965
@Override
6066
public String toString() {
6167
return MoreObjects.toStringHelper(this)
@@ -114,6 +120,23 @@ public static BlobId of(String bucket, String name, Long generation) {
114120
return new BlobId(checkNotNull(bucket), checkNotNull(name), generation);
115121
}
116122

123+
/**
124+
* Creates a {@code BlobId} object.
125+
*
126+
* @param gsUtilUri the Storage url to create the blob from
127+
*/
128+
public static BlobId fromGsUtilUri(String gsUtilUri) {
129+
if (!Pattern.matches("gs://.*/.*", gsUtilUri)) {
130+
throw new IllegalArgumentException(
131+
gsUtilUri + " is not a valid gsutil URI (i.e. \"gs://bucket/blob\")");
132+
}
133+
int blobNameStartIndex = gsUtilUri.indexOf('/', 5);
134+
String bucketName = gsUtilUri.substring(5, blobNameStartIndex);
135+
String blobName = gsUtilUri.substring(blobNameStartIndex + 1);
136+
137+
return BlobId.of(bucketName, blobName);
138+
}
139+
117140
static BlobId fromPb(StorageObject storageObject) {
118141
return BlobId.of(
119142
storageObject.getBucket(), storageObject.getName(), storageObject.getGeneration());

google-cloud-storage/src/test/java/com/google/cloud/storage/BlobIdTest.java

+8
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,14 @@ public void testOf() {
3131
assertEquals("n", blobId.getName());
3232
}
3333

34+
@Test
35+
public void testToFromGsUtilUri() {
36+
BlobId blobId = BlobId.fromGsUtilUri("gs://bucket/path/to/blob");
37+
assertEquals("bucket", blobId.getBucket());
38+
assertEquals("path/to/blob", blobId.getName());
39+
assertEquals("gs://bucket/path/to/blob", blobId.toGsUtilUri());
40+
}
41+
3442
@Test
3543
public void testEquals() {
3644
compareBlobIds(BLOB, BlobId.of("b", "n"));

0 commit comments

Comments
 (0)