|
21 | 21 | import com.google.common.base.MoreObjects;
|
22 | 22 | import java.io.Serializable;
|
23 | 23 | import java.util.Objects;
|
| 24 | +import java.util.regex.Matcher; |
24 | 25 | import java.util.regex.Pattern;
|
25 | 26 |
|
26 | 27 | /**
|
|
31 | 32 | public final class BlobId implements Serializable {
|
32 | 33 |
|
33 | 34 | private static final long serialVersionUID = 8201580858265557469L;
|
| 35 | + private static final Pattern gsUtilUriPattern = Pattern.compile("^gs://(.+?)/(.+?)(?:#(\\d+))?$"); |
34 | 36 | private final String bucket;
|
35 | 37 | private final String name;
|
36 | 38 | private final Long generation;
|
@@ -58,7 +60,7 @@ public Long getGeneration() {
|
58 | 60 |
|
59 | 61 | /** Returns this blob's Storage url which can be used with gsutil */
|
60 | 62 | public String toGsUtilUri() {
|
61 |
| - return "gs://" + bucket + "/" + name; |
| 63 | + return "gs://" + bucket + "/" + name + (generation == null ? "" : ("#" + generation)); |
62 | 64 | }
|
63 | 65 |
|
64 | 66 | @Override
|
@@ -117,14 +119,18 @@ public static BlobId of(String bucket, String name, Long generation) {
|
117 | 119 | * @param gsUtilUri the Storage url to create the blob from
|
118 | 120 | */
|
119 | 121 | public static BlobId fromGsUtilUri(String gsUtilUri) {
|
120 |
| - if (!Pattern.matches("gs://.*/.*", gsUtilUri)) { |
| 122 | + Matcher m = gsUtilUriPattern.matcher(gsUtilUri); |
| 123 | + if (!m.matches()) { |
121 | 124 | throw new IllegalArgumentException(
|
122 |
| - gsUtilUri + " is not a valid gsutil URI (i.e. \"gs://bucket/blob\")"); |
| 125 | + gsUtilUri |
| 126 | + + " is not a valid gsutil URI (i.e. \"gs://bucket/blob\" or \"gs://bucket/blob#generation\")"); |
123 | 127 | }
|
124 |
| - int blobNameStartIndex = gsUtilUri.indexOf('/', 5); |
125 |
| - String bucketName = gsUtilUri.substring(5, blobNameStartIndex); |
126 |
| - String blobName = gsUtilUri.substring(blobNameStartIndex + 1); |
127 | 128 |
|
128 |
| - return BlobId.of(bucketName, blobName); |
| 129 | + String bucket = m.group(1); |
| 130 | + String name = m.group(2); |
| 131 | + String generationGroup = m.group(3); |
| 132 | + Long generation = generationGroup == null ? null : Long.parseLong(generationGroup); |
| 133 | + |
| 134 | + return BlobId.of(bucket, name, generation); |
129 | 135 | }
|
130 | 136 | }
|
0 commit comments