-
Notifications
You must be signed in to change notification settings - Fork 70
/
Blob.java
933 lines (850 loc) · 30.8 KB
/
Blob.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
/*
* Copyright 2015 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.storage;
import static com.google.cloud.RetryHelper.runWithRetries;
import static com.google.cloud.storage.Blob.BlobSourceOption.toGetOptions;
import static com.google.cloud.storage.Blob.BlobSourceOption.toSourceOptions;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.Executors.callable;
import com.google.api.services.storage.model.StorageObject;
import com.google.auth.ServiceAccountSigner;
import com.google.auth.ServiceAccountSigner.SigningException;
import com.google.cloud.ReadChannel;
import com.google.cloud.RetryHelper;
import com.google.cloud.Tuple;
import com.google.cloud.WriteChannel;
import com.google.cloud.storage.Acl.Entity;
import com.google.cloud.storage.Storage.BlobTargetOption;
import com.google.cloud.storage.Storage.BlobWriteOption;
import com.google.cloud.storage.Storage.CopyRequest;
import com.google.cloud.storage.Storage.SignUrlOption;
import com.google.cloud.storage.spi.v1.StorageRpc;
import com.google.common.base.Function;
import com.google.common.io.BaseEncoding;
import com.google.common.io.CountingOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.Key;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* A Google cloud storage object.
*
* <p>Objects of this class are immutable. Operations that modify the blob like {@link #update} and
* {@link #copyTo} return a new object. To get a {@code Blob} object with the most recent
* information use {@link #reload}. {@code Blob} adds a layer of service-related functionality over
* {@link BlobInfo}.
*/
public class Blob extends BlobInfo {
private static final long serialVersionUID = -6806832496717441434L;
private final StorageOptions options;
private transient Storage storage;
static final Function<Tuple<Storage, StorageObject>, Blob> BLOB_FROM_PB_FUNCTION =
new Function<Tuple<Storage, StorageObject>, Blob>() {
@Override
public Blob apply(Tuple<Storage, StorageObject> pb) {
return Blob.fromPb(pb.x(), pb.y());
}
};
private static final int DEFAULT_CHUNK_SIZE = 2 * 1024 * 1024;
/** Class for specifying blob source options when {@code Blob} methods are used. */
public static class BlobSourceOption extends Option {
private static final long serialVersionUID = 214616862061934846L;
private BlobSourceOption(StorageRpc.Option rpcOption) {
super(rpcOption, null);
}
private BlobSourceOption(StorageRpc.Option rpcOption, Object value) {
super(rpcOption, value);
}
private Storage.BlobSourceOption toSourceOptions(BlobInfo blobInfo) {
switch (getRpcOption()) {
case IF_GENERATION_MATCH:
return Storage.BlobSourceOption.generationMatch(blobInfo.getGeneration());
case IF_GENERATION_NOT_MATCH:
return Storage.BlobSourceOption.generationNotMatch(blobInfo.getGeneration());
case IF_METAGENERATION_MATCH:
return Storage.BlobSourceOption.metagenerationMatch(blobInfo.getMetageneration());
case IF_METAGENERATION_NOT_MATCH:
return Storage.BlobSourceOption.metagenerationNotMatch(blobInfo.getMetageneration());
case CUSTOMER_SUPPLIED_KEY:
return Storage.BlobSourceOption.decryptionKey((String) getValue());
case USER_PROJECT:
return Storage.BlobSourceOption.userProject((String) getValue());
default:
throw new AssertionError("Unexpected enum value");
}
}
private Storage.BlobGetOption toGetOption(BlobInfo blobInfo) {
switch (getRpcOption()) {
case IF_GENERATION_MATCH:
return Storage.BlobGetOption.generationMatch(blobInfo.getGeneration());
case IF_GENERATION_NOT_MATCH:
return Storage.BlobGetOption.generationNotMatch(blobInfo.getGeneration());
case IF_METAGENERATION_MATCH:
return Storage.BlobGetOption.metagenerationMatch(blobInfo.getMetageneration());
case IF_METAGENERATION_NOT_MATCH:
return Storage.BlobGetOption.metagenerationNotMatch(blobInfo.getMetageneration());
case USER_PROJECT:
return Storage.BlobGetOption.userProject((String) getValue());
case CUSTOMER_SUPPLIED_KEY:
return Storage.BlobGetOption.decryptionKey((String) getValue());
default:
throw new AssertionError("Unexpected enum value");
}
}
/**
* Returns an option for blob's generation match. If this option is used the request will fail
* if generation does not match.
*/
public static BlobSourceOption generationMatch() {
return new BlobSourceOption(StorageRpc.Option.IF_GENERATION_MATCH);
}
/**
* Returns an option for blob's generation mismatch. If this option is used the request will
* fail if generation matches.
*/
public static BlobSourceOption generationNotMatch() {
return new BlobSourceOption(StorageRpc.Option.IF_GENERATION_NOT_MATCH);
}
/**
* Returns an option for blob's metageneration match. If this option is used the request will
* fail if metageneration does not match.
*/
public static BlobSourceOption metagenerationMatch() {
return new BlobSourceOption(StorageRpc.Option.IF_METAGENERATION_MATCH);
}
/**
* Returns an option for blob's metageneration mismatch. If this option is used the request will
* fail if metageneration matches.
*/
public static BlobSourceOption metagenerationNotMatch() {
return new BlobSourceOption(StorageRpc.Option.IF_METAGENERATION_NOT_MATCH);
}
/**
* Returns an option to set a customer-supplied AES256 key for server-side encryption of the
* blob.
*/
public static BlobSourceOption decryptionKey(Key key) {
String base64Key = BaseEncoding.base64().encode(key.getEncoded());
return new BlobSourceOption(StorageRpc.Option.CUSTOMER_SUPPLIED_KEY, base64Key);
}
/**
* Returns an option to set a customer-supplied AES256 key for server-side encryption of the
* blob.
*
* @param key the AES256 encoded in base64
*/
public static BlobSourceOption decryptionKey(String key) {
return new BlobSourceOption(StorageRpc.Option.CUSTOMER_SUPPLIED_KEY, key);
}
/**
* Returns an option for blob's billing user project. This option is used only if the blob's
* bucket has requester_pays flag enabled.
*/
public static BlobSourceOption userProject(String userProject) {
return new BlobSourceOption(StorageRpc.Option.USER_PROJECT, userProject);
}
static Storage.BlobSourceOption[] toSourceOptions(
BlobInfo blobInfo, BlobSourceOption... options) {
Storage.BlobSourceOption[] convertedOptions = new Storage.BlobSourceOption[options.length];
int index = 0;
for (BlobSourceOption option : options) {
convertedOptions[index++] = option.toSourceOptions(blobInfo);
}
return convertedOptions;
}
static Storage.BlobGetOption[] toGetOptions(BlobInfo blobInfo, BlobSourceOption... options) {
Storage.BlobGetOption[] convertedOptions = new Storage.BlobGetOption[options.length];
int index = 0;
for (BlobSourceOption option : options) {
convertedOptions[index++] = option.toGetOption(blobInfo);
}
return convertedOptions;
}
}
/**
* Downloads this blob to the given file path using specified blob read options.
*
* @param path destination
* @param options blob read options
* @throws StorageException upon failure
*/
public void downloadTo(Path path, BlobSourceOption... options) {
try (OutputStream outputStream = Files.newOutputStream(path)) {
downloadTo(outputStream, options);
} catch (IOException e) {
throw new StorageException(e);
}
}
/**
* Downloads this blob to the given output stream using specified blob read options.
*
* @param outputStream
* @param options
*/
public void downloadTo(OutputStream outputStream, BlobSourceOption... options) {
final CountingOutputStream countingOutputStream = new CountingOutputStream(outputStream);
final StorageRpc storageRpc = this.options.getStorageRpcV1();
final Map<StorageRpc.Option, ?> requestOptions = StorageImpl.optionMap(getBlobId(), options);
try {
runWithRetries(
callable(
new Runnable() {
@Override
public void run() {
storageRpc.read(
getBlobId().toPb(),
requestOptions,
countingOutputStream.getCount(),
countingOutputStream);
}
}),
this.options.getRetrySettings(),
StorageImpl.EXCEPTION_HANDLER,
this.options.getClock());
} catch (RetryHelper.RetryHelperException e) {
StorageException.translateAndThrow(e);
}
}
/**
* Downloads this blob to the given file path.
*
* <p>This method is replaced with {@link #downloadTo(Path, BlobSourceOption...)}, but is kept
* here for binary compatibility with the older versions of the client library.
*
* @param path destination
* @throws StorageException upon failure
*/
public void downloadTo(Path path) {
downloadTo(path, new BlobSourceOption[0]);
}
/** Builder for {@code Blob}. */
public static class Builder extends BlobInfo.Builder {
private final Storage storage;
private final BlobInfo.BuilderImpl infoBuilder;
Builder(Blob blob) {
this.storage = blob.getStorage();
this.infoBuilder = new BlobInfo.BuilderImpl(blob);
}
@Override
public Builder setBlobId(BlobId blobId) {
infoBuilder.setBlobId(blobId);
return this;
}
@Override
Builder setGeneratedId(String generatedId) {
infoBuilder.setGeneratedId(generatedId);
return this;
}
@Override
public Builder setContentType(String contentType) {
infoBuilder.setContentType(contentType);
return this;
}
@Override
public Builder setContentDisposition(String contentDisposition) {
infoBuilder.setContentDisposition(contentDisposition);
return this;
}
@Override
public Builder setContentLanguage(String contentLanguage) {
infoBuilder.setContentLanguage(contentLanguage);
return this;
}
@Override
public Builder setContentEncoding(String contentEncoding) {
infoBuilder.setContentEncoding(contentEncoding);
return this;
}
@Override
Builder setComponentCount(Integer componentCount) {
infoBuilder.setComponentCount(componentCount);
return this;
}
@Override
public Builder setCacheControl(String cacheControl) {
infoBuilder.setCacheControl(cacheControl);
return this;
}
@Override
public Builder setAcl(List<Acl> acl) {
infoBuilder.setAcl(acl);
return this;
}
@Override
Builder setOwner(Entity owner) {
infoBuilder.setOwner(owner);
return this;
}
@Override
Builder setSize(Long size) {
infoBuilder.setSize(size);
return this;
}
@Override
Builder setEtag(String etag) {
infoBuilder.setEtag(etag);
return this;
}
@Override
Builder setSelfLink(String selfLink) {
infoBuilder.setSelfLink(selfLink);
return this;
}
@Override
public Builder setMd5(String md5) {
infoBuilder.setMd5(md5);
return this;
}
@Override
public Builder setMd5FromHexString(String md5HexString) {
infoBuilder.setMd5FromHexString(md5HexString);
return this;
}
@Override
public Builder setCrc32c(String crc32c) {
infoBuilder.setCrc32c(crc32c);
return this;
}
@Override
public Builder setCrc32cFromHexString(String crc32cHexString) {
infoBuilder.setCrc32cFromHexString(crc32cHexString);
return this;
}
@Override
Builder setMediaLink(String mediaLink) {
infoBuilder.setMediaLink(mediaLink);
return this;
}
@Override
public Builder setMetadata(Map<String, String> metadata) {
infoBuilder.setMetadata(metadata);
return this;
}
@Override
public Builder setStorageClass(StorageClass storageClass) {
infoBuilder.setStorageClass(storageClass);
return this;
}
@Override
Builder setMetageneration(Long metageneration) {
infoBuilder.setMetageneration(metageneration);
return this;
}
@Override
Builder setDeleteTime(Long deleteTime) {
infoBuilder.setDeleteTime(deleteTime);
return this;
}
@Override
Builder setUpdateTime(Long updateTime) {
infoBuilder.setUpdateTime(updateTime);
return this;
}
@Override
Builder setCreateTime(Long createTime) {
infoBuilder.setCreateTime(createTime);
return this;
}
@Override
Builder setIsDirectory(boolean isDirectory) {
infoBuilder.setIsDirectory(isDirectory);
return this;
}
@Override
Builder setCustomerEncryption(CustomerEncryption customerEncryption) {
infoBuilder.setCustomerEncryption(customerEncryption);
return this;
}
@Override
Builder setKmsKeyName(String kmsKeyName) {
infoBuilder.setKmsKeyName(kmsKeyName);
return this;
}
@Override
public Builder setEventBasedHold(Boolean eventBasedHold) {
infoBuilder.setEventBasedHold(eventBasedHold);
return this;
}
@Override
public Builder setTemporaryHold(Boolean temporaryHold) {
infoBuilder.setTemporaryHold(temporaryHold);
return this;
}
@Override
Builder setRetentionExpirationTime(Long retentionExpirationTime) {
infoBuilder.setRetentionExpirationTime(retentionExpirationTime);
return this;
}
@Override
public Blob build() {
return new Blob(storage, infoBuilder);
}
}
Blob(Storage storage, BlobInfo.BuilderImpl infoBuilder) {
super(infoBuilder);
this.storage = checkNotNull(storage);
this.options = storage.getOptions();
}
/**
* Checks if this blob exists.
*
* <p>Example of checking if the blob exists.
*
* <pre>{@code
* boolean exists = blob.exists();
* if (exists) {
* // the blob exists
* } else {
* // the blob was not found
* }
* }</pre>
*
* @param options blob read options
* @return true if this blob exists, false otherwise
* @throws StorageException upon failure
*/
public boolean exists(BlobSourceOption... options) {
int length = options.length;
Storage.BlobGetOption[] getOptions = Arrays.copyOf(toGetOptions(this, options), length + 1);
getOptions[length] = Storage.BlobGetOption.fields();
return storage.get(getBlobId(), getOptions) != null;
}
/**
* Returns this blob's content.
*
* <p>Example of reading all bytes of the blob, if its generation matches the {@link
* Blob#getGeneration()} value, otherwise a {@link StorageException} is thrown.
*
* <pre>{@code
* byte[] content = blob.getContent(BlobSourceOption.generationMatch());
* }</pre>
*
* @param options blob read options
* @throws StorageException upon failure
*/
public byte[] getContent(BlobSourceOption... options) {
return storage.readAllBytes(getBlobId(), toSourceOptions(this, options));
}
/**
* Fetches current blob's latest information. Returns {@code null} if the blob does not exist.
*
* <p>Example of getting the blob's latest information, if its generation does not match the
* {@link Blob#getGeneration()} value, otherwise a {@link StorageException} is thrown.
*
* <pre>{@code
* Blob latestBlob = blob.reload(BlobSourceOption.generationNotMatch());
* if (latestBlob == null) {
* // the blob was not found
* }
* }</pre>
*
* @param options blob read options
* @return a {@code Blob} object with latest information or {@code null} if not found
* @throws StorageException upon failure
*/
public Blob reload(BlobSourceOption... options) {
return storage.get(getBlobId(), toGetOptions(this, options));
}
/**
* Updates the blob's information. Bucket or blob's name cannot be changed by this method. If you
* want to rename the blob or move it to a different bucket use the {@link #copyTo} and {@link
* #delete} operations. A new {@code Blob} object is returned. By default no checks are made on
* the metadata generation of the current blob. If you want to update the information only if the
* current blob metadata are at their latest version use the {@code metagenerationMatch} option:
* {@code newBlob.update(BlobTargetOption.metagenerationMatch())}.
*
* <p>Original metadata are merged with metadata in the provided {@code blobInfo}. If the original
* metadata already contains a key specified in the provided {@code blobInfo's} metadata map, it
* will be replaced by the new value. Removing metadata can be done by setting that metadata's
* value to {@code null}.
*
* <p>Example of adding new metadata values or updating existing ones.
*
* <pre>{@code
* String bucketName = "my_unique_bucket";
* String blobName = "my_blob_name";
* Map<String, String> newMetadata = new HashMap<>();
* newMetadata.put("keyToAddOrUpdate", "value");
* Blob blob = storage.update(BlobInfo.newBuilder(bucketName, blobName)
* .setMetadata(newMetadata)
* .build());
* }</pre>
*
* <p>Example of removing metadata values.
*
* <pre>{@code
* String bucketName = "my_unique_bucket";
* String blobName = "my_blob_name";
* Map<String, String> newMetadata = new HashMap<>();
* newMetadata.put("keyToRemove", null);
* Blob blob = storage.update(BlobInfo.newBuilder(bucketName, blobName)
* .setMetadata(newMetadata)
* .build());
* }</pre>
*
* @param options update options
* @return a {@code Blob} object with updated information
* @throws StorageException upon failure
*/
public Blob update(BlobTargetOption... options) {
return storage.update(this, options);
}
/**
* Deletes this blob.
*
* <p>Example of deleting the blob, if its generation matches the {@link Blob#getGeneration()}
* value, otherwise a {@link StorageException} is thrown.
*
* <pre>{@code
* boolean deleted = blob.delete(BlobSourceOption.generationMatch());
* if (deleted) {
* // the blob was deleted
* } else {
* // the blob was not found
* }
* }</pre>
*
* @param options blob delete options
* @return {@code true} if blob was deleted, {@code false} if it was not found
* @throws StorageException upon failure
*/
public boolean delete(BlobSourceOption... options) {
return storage.delete(getBlobId(), toSourceOptions(this, options));
}
/**
* Sends a copy request for the current blob to the target blob. Possibly also some of the
* metadata are copied (e.g. content-type).
*
* <p>Example of copying the blob to a different bucket with a different name.
*
* <pre>{@code
* String bucketName = "my_unique_bucket";
* String blobName = "copy_blob_name";
* CopyWriter copyWriter = blob.copyTo(BlobId.of(bucketName, blobName));
* Blob copiedBlob = copyWriter.getResult();
* }</pre>
*
* @param targetBlob target blob's id
* @param options source blob options
* @return a {@link CopyWriter} object that can be used to get information on the newly created
* blob or to complete the copy if more than one RPC request is needed
* @throws StorageException upon failure
*/
public CopyWriter copyTo(BlobId targetBlob, BlobSourceOption... options) {
CopyRequest copyRequest =
CopyRequest.newBuilder()
.setSource(getBucket(), getName())
.setSourceOptions(toSourceOptions(this, options))
.setTarget(targetBlob)
.build();
return storage.copy(copyRequest);
}
/**
* Sends a copy request for the current blob to the target bucket, preserving its name. Possibly
* copying also some of the metadata (e.g. content-type).
*
* <p>Example of copying the blob to a different bucket, keeping the original name.
*
* <pre>{@code
* String bucketName = "my_unique_bucket";
* CopyWriter copyWriter = blob.copyTo(bucketName);
* Blob copiedBlob = copyWriter.getResult();
* }</pre>
*
* @param targetBucket target bucket's name
* @param options source blob options
* @return a {@link CopyWriter} object that can be used to get information on the newly created
* blob or to complete the copy if more than one RPC request is needed
* @throws StorageException upon failure
*/
public CopyWriter copyTo(String targetBucket, BlobSourceOption... options) {
return copyTo(targetBucket, getName(), options);
}
/**
* Sends a copy request for the current blob to the target blob. Possibly also some of the
* metadata are copied (e.g. content-type).
*
* <p>Example of copying the blob to a different bucket with a different name.
*
* <pre>{@code
* String bucketName = "my_unique_bucket";
* String blobName = "copy_blob_name";
* CopyWriter copyWriter = blob.copyTo(bucketName, blobName);
* Blob copiedBlob = copyWriter.getResult();
* }</pre>
*
* <p>Example of moving a blob to a different bucket with a different name.
*
* <pre>{@code
* String destBucket = "my_unique_bucket";
* String destBlob = "move_blob_name";
* CopyWriter copyWriter = blob.copyTo(destBucket, destBlob);
* Blob copiedBlob = copyWriter.getResult();
* boolean deleted = blob.delete();
* }</pre>
*
* @param targetBucket target bucket's name
* @param targetBlob target blob's name
* @param options source blob options
* @return a {@link CopyWriter} object that can be used to get information on the newly created
* blob or to complete the copy if more than one RPC request is needed
* @throws StorageException upon failure
*/
public CopyWriter copyTo(String targetBucket, String targetBlob, BlobSourceOption... options) {
return copyTo(BlobId.of(targetBucket, targetBlob), options);
}
/**
* Returns a {@code ReadChannel} object for reading this blob's content.
*
* <p>Example of reading the blob's content through a reader.
*
* <pre>{@code
* try (ReadChannel reader = blob.reader()) {
* ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
* while (reader.read(bytes) > 0) {
* bytes.flip();
* // do something with bytes
* bytes.clear();
* }
* }
* }</pre>
*
* <p>Example of reading just a portion of the blob's content.
*
* <pre>{@code
* int start = 1;
* int end = 8;
* try (ReadChannel reader = blob.reader()) {
* reader.seek(start);
* ByteBuffer bytes = ByteBuffer.allocate(end - start);
* reader.read(bytes);
* return bytes.array();
* }
* }</pre>
*
* @param options blob read options
* @throws StorageException upon failure
*/
public ReadChannel reader(BlobSourceOption... options) {
return storage.reader(getBlobId(), toSourceOptions(this, options));
}
/**
* Returns a {@code WriteChannel} object for writing to this blob. By default any md5 and crc32c
* values in the current blob are ignored unless requested via the {@code
* BlobWriteOption.md5Match} and {@code BlobWriteOption.crc32cMatch} options.
*
* <p>Example of writing the blob's content through a writer.
*
* <pre>{@code
* byte[] content = "Hello, World!".getBytes(UTF_8);
* try (WriteChannel writer = blob.writer()) {
* try {
* writer.write(ByteBuffer.wrap(content, 0, content.length));
* } catch (Exception ex) {
* // handle exception
* }
* }
* }</pre>
*
* @param options target blob options
* @throws StorageException upon failure
*/
public WriteChannel writer(BlobWriteOption... options) {
return storage.writer(this, options);
}
/**
* Generates a signed URL for this blob. If you want to allow access for a fixed amount of time to
* this blob, you can use this method to generate a URL that is only valid within a certain time
* period. This is particularly useful if you don't want publicly accessible blobs, but also don't
* want to require users to explicitly log in. Signing a URL requires a service account signer. If
* an instance of {@link com.google.auth.ServiceAccountSigner} was passed to {@link
* StorageOptions}' builder via {@code setCredentials(Credentials)} or the default credentials are
* being used and the environment variable {@code GOOGLE_APPLICATION_CREDENTIALS} is set or your
* application is running in App Engine, then {@code signUrl} will use that credentials to sign
* the URL. If the credentials passed to {@link StorageOptions} do not implement {@link
* ServiceAccountSigner} (this is the case, for instance, for Compute Engine credentials and
* Google Cloud SDK credentials) then {@code signUrl} will throw an {@link IllegalStateException}
* unless an implementation of {@link ServiceAccountSigner} is passed using the {@link
* SignUrlOption#signWith(ServiceAccountSigner)} option.
*
* <p>A service account signer is looked for in the following order:
*
* <ol>
* <li>The signer passed with the option {@link SignUrlOption#signWith(ServiceAccountSigner)}
* <li>The credentials passed to {@link StorageOptions}
* <li>The default credentials, if no credentials were passed to {@link StorageOptions}
* </ol>
*
* <p>Example of creating a signed URL for the blob that is valid for 2 weeks, using the default
* credentials for signing the URL:
*
* <pre>{@code
* URL signedUrl = blob.signUrl(14, TimeUnit.DAYS);
* }</pre>
*
* <p>Example of creating a signed URL for the blob passing the {@link
* SignUrlOption#signWith(ServiceAccountSigner)} option, that will be used to sign the URL:
*
* <pre>{@code
* String keyPath = "/path/to/key.json";
* URL signedUrl = blob.signUrl(14, TimeUnit.DAYS, SignUrlOption.signWith(
* ServiceAccountCredentials.fromStream(new FileInputStream(keyPath))));
* }</pre>
*
* <p>Example of creating a signed URL for a blob generation:
*
* <pre>{@code
* URL signedUrl = blob.signUrl(1, TimeUnit.HOURS,
* SignUrlOption.withQueryParams(ImmutableMap.of("generation", "1576656755290328")));
* }</pre>
*
* @param duration time until the signed URL expires, expressed in {@code unit}. The finer
* granularity supported is 1 second, finer granularities will be truncated
* @param unit time unit of the {@code duration} parameter
* @param options optional URL signing options
* @return a signed URL for this blob and the specified options
* @throws IllegalStateException if {@link SignUrlOption#signWith(ServiceAccountSigner)} was not
* used and no implementation of {@link ServiceAccountSigner} was provided to {@link
* StorageOptions}
* @throws IllegalArgumentException if {@code SignUrlOption.withMd5()} option is used and {@code
* blobInfo.md5()} is {@code null}
* @throws IllegalArgumentException if {@code SignUrlOption.withContentType()} option is used and
* {@code blobInfo.contentType()} is {@code null}
* @throws SigningException if the attempt to sign the URL failed
* @see <a href="https://cloud.google.com/storage/docs/access-control#Signed-URLs">Signed-URLs</a>
*/
public URL signUrl(long duration, TimeUnit unit, SignUrlOption... options) {
return storage.signUrl(this, duration, unit, options);
}
/**
* Returns the ACL entry for the specified entity on this blob or {@code null} if not found.
*
* <p>Example of getting the ACL entry for an entity.
*
* <pre>{@code
* Acl acl = blob.getAcl(User.ofAllAuthenticatedUsers());
* }</pre>
*
* @throws StorageException upon failure
*/
public Acl getAcl(Entity entity) {
return storage.getAcl(getBlobId(), entity);
}
/**
* Deletes the ACL entry for the specified entity on this blob.
*
* <p>Example of deleting the ACL entry for an entity.
*
* <pre>{@code
* boolean deleted = blob.deleteAcl(User.ofAllAuthenticatedUsers());
* if (deleted) {
* // the acl entry was deleted
* } else {
* // the acl entry was not found
* }
* }</pre>
*
* @return {@code true} if the ACL was deleted, {@code false} if it was not found
* @throws StorageException upon failure
*/
public boolean deleteAcl(Entity entity) {
return storage.deleteAcl(getBlobId(), entity);
}
/**
* Creates a new ACL entry on this blob.
*
* <p>Example of creating a new ACL entry.
*
* <pre>{@code
* Acl acl = blob.createAcl(Acl.of(User.ofAllAuthenticatedUsers(), Acl.Role.READER));
* }</pre>
*
* @throws StorageException upon failure
*/
public Acl createAcl(Acl acl) {
return storage.createAcl(getBlobId(), acl);
}
/**
* Updates an ACL entry on this blob.
*
* <p>Example of updating a new ACL entry.
*
* <pre>{@code
* Acl acl = blob.updateAcl(Acl.of(User.ofAllAuthenticatedUsers(), Acl.Role.OWNER));
* }</pre>
*
* @throws StorageException upon failure
*/
public Acl updateAcl(Acl acl) {
return storage.updateAcl(getBlobId(), acl);
}
/**
* Lists the ACL entries for this blob.
*
* <p>Example of listing the ACL entries.
*
* <pre>{@code
* List<Acl> acls = blob.listAcls();
* for (Acl acl : acls) {
* // do something with ACL entry
* }
* }</pre>
*
* @throws StorageException upon failure
*/
public List<Acl> listAcls() {
return storage.listAcls(getBlobId());
}
/** Returns the blob's {@code Storage} object used to issue requests. */
public Storage getStorage() {
return storage;
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
@Override
public final boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || !obj.getClass().equals(Blob.class)) {
return false;
}
Blob other = (Blob) obj;
return Objects.equals(toPb(), other.toPb()) && Objects.equals(options, other.options);
}
@Override
public final int hashCode() {
return Objects.hash(super.hashCode(), options);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
this.storage = options.getService();
}
static Blob fromPb(Storage storage, StorageObject storageObject) {
BlobInfo info = BlobInfo.fromPb(storageObject);
return new Blob(storage, new BlobInfo.BuilderImpl(info));
}
}