Skip to content

Commit

Permalink
feat: Add from and to storage url options for BlobId (#888)
Browse files Browse the repository at this point in the history
* Add from and to storage url options for BlobId

* Better name
  • Loading branch information
JesseLovelace authored Jun 24, 2021
1 parent 73e7cdf commit 1876a58
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.google.common.base.MoreObjects;
import java.io.Serializable;
import java.util.Objects;
import java.util.regex.Pattern;

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

/** Returns this blob's Storage url which can be used with gsutil */
public String toGsUtilUri() {
return "gs://" + bucket + "/" + name;
}

@Override
public String toString() {
return MoreObjects.toStringHelper(this)
Expand Down Expand Up @@ -114,6 +120,23 @@ public static BlobId of(String bucket, String name, Long generation) {
return new BlobId(checkNotNull(bucket), checkNotNull(name), generation);
}

/**
* Creates a {@code BlobId} object.
*
* @param gsUtilUri the Storage url to create the blob from
*/
public static BlobId fromGsUtilUri(String gsUtilUri) {
if (!Pattern.matches("gs://.*/.*", gsUtilUri)) {
throw new IllegalArgumentException(
gsUtilUri + " is not a valid gsutil URI (i.e. \"gs://bucket/blob\")");
}
int blobNameStartIndex = gsUtilUri.indexOf('/', 5);
String bucketName = gsUtilUri.substring(5, blobNameStartIndex);
String blobName = gsUtilUri.substring(blobNameStartIndex + 1);

return BlobId.of(bucketName, blobName);
}

static BlobId fromPb(StorageObject storageObject) {
return BlobId.of(
storageObject.getBucket(), storageObject.getName(), storageObject.getGeneration());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ public void testOf() {
assertEquals("n", blobId.getName());
}

@Test
public void testToFromGsUtilUri() {
BlobId blobId = BlobId.fromGsUtilUri("gs://bucket/path/to/blob");
assertEquals("bucket", blobId.getBucket());
assertEquals("path/to/blob", blobId.getName());
assertEquals("gs://bucket/path/to/blob", blobId.toGsUtilUri());
}

@Test
public void testEquals() {
compareBlobIds(BLOB, BlobId.of("b", "n"));
Expand Down

0 comments on commit 1876a58

Please sign in to comment.