/
Bucket.java
1252 lines (1138 loc) · 43.6 KB
/
Bucket.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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.storage.Bucket.BucketSourceOption.toGetOptions;
import static com.google.cloud.storage.Bucket.BucketSourceOption.toSourceOptions;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.gax.paging.Page;
import com.google.cloud.Tuple;
import com.google.cloud.storage.Acl.Entity;
import com.google.cloud.storage.Storage.BlobGetOption;
import com.google.cloud.storage.Storage.BlobListOption;
import com.google.cloud.storage.Storage.BucketTargetOption;
import com.google.cloud.storage.spi.v1.StorageRpc;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.BaseEncoding;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.security.Key;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* A Google cloud storage bucket.
*
* <p>Objects of this class are immutable. Operations that modify the bucket like {@link #update}
* return a new object. To get a {@code Bucket} object with the most recent information use {@link
* #reload}. {@code Bucket} adds a layer of service-related functionality over {@link BucketInfo}.
*/
public class Bucket extends BucketInfo {
private static final long serialVersionUID = 8574601739542252586L;
private final StorageOptions options;
private transient Storage storage;
/** Class for specifying bucket source options when {@code Bucket} methods are used. */
public static class BucketSourceOption extends Option {
private static final long serialVersionUID = 6928872234155522371L;
private BucketSourceOption(StorageRpc.Option rpcOption) {
super(rpcOption, null);
}
private BucketSourceOption(StorageRpc.Option rpcOption, Object value) {
super(rpcOption, value);
}
private Storage.BucketSourceOption toSourceOption(BucketInfo bucketInfo) {
switch (getRpcOption()) {
case IF_METAGENERATION_MATCH:
return Storage.BucketSourceOption.metagenerationMatch(bucketInfo.getMetageneration());
case IF_METAGENERATION_NOT_MATCH:
return Storage.BucketSourceOption.metagenerationNotMatch(bucketInfo.getMetageneration());
default:
throw new AssertionError("Unexpected enum value");
}
}
private Storage.BucketGetOption toGetOption(BucketInfo bucketInfo) {
switch (getRpcOption()) {
case IF_METAGENERATION_MATCH:
return Storage.BucketGetOption.metagenerationMatch(bucketInfo.getMetageneration());
case IF_METAGENERATION_NOT_MATCH:
return Storage.BucketGetOption.metagenerationNotMatch(bucketInfo.getMetageneration());
default:
throw new AssertionError("Unexpected enum value");
}
}
/**
* Returns an option for bucket's metageneration match. If this option is used the request will
* fail if metageneration does not match.
*/
public static BucketSourceOption metagenerationMatch() {
return new BucketSourceOption(StorageRpc.Option.IF_METAGENERATION_MATCH);
}
/**
* Returns an option for bucket's metageneration mismatch. If this option is used the request
* will fail if metageneration matches.
*/
public static BucketSourceOption metagenerationNotMatch() {
return new BucketSourceOption(StorageRpc.Option.IF_METAGENERATION_NOT_MATCH);
}
/**
* Returns an option for blob's billing user project. This option is only used by the buckets
* with 'requester_pays' flag.
*/
public static BucketSourceOption userProject(String userProject) {
return new BucketSourceOption(StorageRpc.Option.USER_PROJECT, userProject);
}
static Storage.BucketSourceOption[] toSourceOptions(
BucketInfo bucketInfo, BucketSourceOption... options) {
Storage.BucketSourceOption[] convertedOptions =
new Storage.BucketSourceOption[options.length];
int index = 0;
for (BucketSourceOption option : options) {
convertedOptions[index++] = option.toSourceOption(bucketInfo);
}
return convertedOptions;
}
static Storage.BucketGetOption[] toGetOptions(
BucketInfo bucketInfo, BucketSourceOption... options) {
Storage.BucketGetOption[] convertedOptions = new Storage.BucketGetOption[options.length];
int index = 0;
for (BucketSourceOption option : options) {
convertedOptions[index++] = option.toGetOption(bucketInfo);
}
return convertedOptions;
}
}
/** Class for specifying blob target options when {@code Bucket} methods are used. */
public static class BlobTargetOption extends Option {
private static final Function<BlobTargetOption, StorageRpc.Option> TO_ENUM =
new Function<BlobTargetOption, StorageRpc.Option>() {
@Override
public StorageRpc.Option apply(BlobTargetOption blobTargetOption) {
return blobTargetOption.getRpcOption();
}
};
private static final long serialVersionUID = 8345296337342509425L;
private BlobTargetOption(StorageRpc.Option rpcOption, Object value) {
super(rpcOption, value);
}
private Tuple<BlobInfo, Storage.BlobTargetOption> toTargetOption(BlobInfo blobInfo) {
BlobId blobId = blobInfo.getBlobId();
switch (getRpcOption()) {
case PREDEFINED_ACL:
return Tuple.of(
blobInfo, Storage.BlobTargetOption.predefinedAcl((Storage.PredefinedAcl) getValue()));
case IF_GENERATION_MATCH:
blobId = BlobId.of(blobId.getBucket(), blobId.getName(), (Long) getValue());
return Tuple.of(
blobInfo.toBuilder().setBlobId(blobId).build(),
Storage.BlobTargetOption.generationMatch());
case IF_GENERATION_NOT_MATCH:
blobId = BlobId.of(blobId.getBucket(), blobId.getName(), (Long) getValue());
return Tuple.of(
blobInfo.toBuilder().setBlobId(blobId).build(),
Storage.BlobTargetOption.generationNotMatch());
case IF_METAGENERATION_MATCH:
return Tuple.of(
blobInfo.toBuilder().setMetageneration((Long) getValue()).build(),
Storage.BlobTargetOption.metagenerationMatch());
case IF_METAGENERATION_NOT_MATCH:
return Tuple.of(
blobInfo.toBuilder().setMetageneration((Long) getValue()).build(),
Storage.BlobTargetOption.metagenerationNotMatch());
case CUSTOMER_SUPPLIED_KEY:
return Tuple.of(blobInfo, Storage.BlobTargetOption.encryptionKey((String) getValue()));
case KMS_KEY_NAME:
return Tuple.of(blobInfo, Storage.BlobTargetOption.kmsKeyName((String) getValue()));
case USER_PROJECT:
return Tuple.of(blobInfo, Storage.BlobTargetOption.userProject((String) getValue()));
default:
throw new AssertionError("Unexpected enum value");
}
}
/** Returns an option for specifying blob's predefined ACL configuration. */
public static BlobTargetOption predefinedAcl(Storage.PredefinedAcl acl) {
return new BlobTargetOption(StorageRpc.Option.PREDEFINED_ACL, acl);
}
/**
* Returns an option that causes an operation to succeed only if the target blob does not exist.
* This option can not be provided together with {@link #generationMatch(long)} or {@link
* #generationNotMatch(long)}.
*/
public static BlobTargetOption doesNotExist() {
return new BlobTargetOption(StorageRpc.Option.IF_GENERATION_MATCH, 0L);
}
/**
* Returns an option for blob's data generation match. If this option is used the request will
* fail if generation does not match the provided value. This option can not be provided
* together with {@link #generationNotMatch(long)} or {@link #doesNotExist()}.
*/
public static BlobTargetOption generationMatch(long generation) {
return new BlobTargetOption(StorageRpc.Option.IF_GENERATION_MATCH, generation);
}
/**
* Returns an option for blob's data generation mismatch. If this option is used the request
* will fail if blob's generation matches the provided value. This option can not be provided
* together with {@link #generationMatch(long)} or {@link #doesNotExist()}.
*/
public static BlobTargetOption generationNotMatch(long generation) {
return new BlobTargetOption(StorageRpc.Option.IF_GENERATION_NOT_MATCH, generation);
}
/**
* Returns an option for blob's metageneration match. If this option is used the request will
* fail if metageneration does not match the provided value. This option can not be provided
* together with {@link #metagenerationNotMatch(long)}.
*/
public static BlobTargetOption metagenerationMatch(long metageneration) {
return new BlobTargetOption(StorageRpc.Option.IF_METAGENERATION_MATCH, metageneration);
}
/**
* Returns an option for blob's metageneration mismatch. If this option is used the request will
* fail if metageneration matches the provided value. This option can not be provided together
* with {@link #metagenerationMatch(long)}.
*/
public static BlobTargetOption metagenerationNotMatch(long metageneration) {
return new BlobTargetOption(StorageRpc.Option.IF_METAGENERATION_NOT_MATCH, metageneration);
}
/**
* Returns an option to set a customer-supplied AES256 key for server-side encryption of the
* blob.
*/
public static BlobTargetOption encryptionKey(Key key) {
String base64Key = BaseEncoding.base64().encode(key.getEncoded());
return new BlobTargetOption(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 BlobTargetOption encryptionKey(String key) {
return new BlobTargetOption(StorageRpc.Option.CUSTOMER_SUPPLIED_KEY, key);
}
/**
* Returns an option to set a customer-managed KMS key for server-side encryption of the blob.
*
* @param kmsKeyName the KMS key resource id
*/
public static BlobTargetOption kmsKeyName(String kmsKeyName) {
return new BlobTargetOption(StorageRpc.Option.KMS_KEY_NAME, kmsKeyName);
}
/**
* Returns an option for blob's billing user project. This option is only used by the buckets
* with 'requester_pays' flag.
*/
public static BlobTargetOption userProject(String userProject) {
return new BlobTargetOption(StorageRpc.Option.USER_PROJECT, userProject);
}
static Tuple<BlobInfo, Storage.BlobTargetOption[]> toTargetOptions(
BlobInfo info, BlobTargetOption... options) {
Set<StorageRpc.Option> optionSet =
Sets.immutableEnumSet(Lists.transform(Arrays.asList(options), TO_ENUM));
checkArgument(
!(optionSet.contains(StorageRpc.Option.IF_METAGENERATION_NOT_MATCH)
&& optionSet.contains(StorageRpc.Option.IF_METAGENERATION_MATCH)),
"metagenerationMatch and metagenerationNotMatch options can not be both provided");
checkArgument(
!(optionSet.contains(StorageRpc.Option.IF_GENERATION_NOT_MATCH)
&& optionSet.contains(StorageRpc.Option.IF_GENERATION_MATCH)),
"Only one option of generationMatch, doesNotExist or generationNotMatch can be provided");
Storage.BlobTargetOption[] convertedOptions = new Storage.BlobTargetOption[options.length];
BlobInfo targetInfo = info;
int index = 0;
for (BlobTargetOption option : options) {
Tuple<BlobInfo, Storage.BlobTargetOption> target = option.toTargetOption(targetInfo);
targetInfo = target.x();
convertedOptions[index++] = target.y();
}
return Tuple.of(targetInfo, convertedOptions);
}
}
/** Class for specifying blob write options when {@code Bucket} methods are used. */
public static class BlobWriteOption implements Serializable {
private static final Function<BlobWriteOption, Storage.BlobWriteOption.Option> TO_ENUM =
new Function<BlobWriteOption, Storage.BlobWriteOption.Option>() {
@Override
public Storage.BlobWriteOption.Option apply(BlobWriteOption blobWriteOption) {
return blobWriteOption.option;
}
};
private static final long serialVersionUID = 4722190734541993114L;
private final Storage.BlobWriteOption.Option option;
private final Object value;
private Tuple<BlobInfo, Storage.BlobWriteOption> toWriteOption(BlobInfo blobInfo) {
BlobId blobId = blobInfo.getBlobId();
switch (option) {
case PREDEFINED_ACL:
return Tuple.of(
blobInfo, Storage.BlobWriteOption.predefinedAcl((Storage.PredefinedAcl) value));
case IF_GENERATION_MATCH:
blobId = BlobId.of(blobId.getBucket(), blobId.getName(), (Long) value);
return Tuple.of(
blobInfo.toBuilder().setBlobId(blobId).build(),
Storage.BlobWriteOption.generationMatch());
case IF_GENERATION_NOT_MATCH:
blobId = BlobId.of(blobId.getBucket(), blobId.getName(), (Long) value);
return Tuple.of(
blobInfo.toBuilder().setBlobId(blobId).build(),
Storage.BlobWriteOption.generationNotMatch());
case IF_METAGENERATION_MATCH:
return Tuple.of(
blobInfo.toBuilder().setMetageneration((Long) value).build(),
Storage.BlobWriteOption.metagenerationMatch());
case IF_METAGENERATION_NOT_MATCH:
return Tuple.of(
blobInfo.toBuilder().setMetageneration((Long) value).build(),
Storage.BlobWriteOption.metagenerationNotMatch());
case IF_MD5_MATCH:
return Tuple.of(
blobInfo.toBuilder().setMd5((String) value).build(),
Storage.BlobWriteOption.md5Match());
case IF_CRC32C_MATCH:
return Tuple.of(
blobInfo.toBuilder().setCrc32c((String) value).build(),
Storage.BlobWriteOption.crc32cMatch());
case CUSTOMER_SUPPLIED_KEY:
return Tuple.of(blobInfo, Storage.BlobWriteOption.encryptionKey((String) value));
case KMS_KEY_NAME:
return Tuple.of(blobInfo, Storage.BlobWriteOption.kmsKeyName((String) value));
case USER_PROJECT:
return Tuple.of(blobInfo, Storage.BlobWriteOption.userProject((String) value));
default:
throw new AssertionError("Unexpected enum value");
}
}
private BlobWriteOption(Storage.BlobWriteOption.Option option, Object value) {
this.option = option;
this.value = value;
}
@Override
public int hashCode() {
return Objects.hash(option, value);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof BlobWriteOption)) {
return false;
}
final BlobWriteOption other = (BlobWriteOption) obj;
return this.option == other.option && Objects.equals(this.value, other.value);
}
/** Returns an option for specifying blob's predefined ACL configuration. */
public static BlobWriteOption predefinedAcl(Storage.PredefinedAcl acl) {
return new BlobWriteOption(Storage.BlobWriteOption.Option.PREDEFINED_ACL, acl);
}
/**
* Returns an option that causes an operation to succeed only if the target blob does not exist.
* This option can not be provided together with {@link #generationMatch(long)} or {@link
* #generationNotMatch(long)}.
*/
public static BlobWriteOption doesNotExist() {
return new BlobWriteOption(Storage.BlobWriteOption.Option.IF_GENERATION_MATCH, 0L);
}
/**
* Returns an option for blob's data generation match. If this option is used the request will
* fail if generation does not match the provided value. This option can not be provided
* together with {@link #generationNotMatch(long)} or {@link #doesNotExist()}.
*/
public static BlobWriteOption generationMatch(long generation) {
return new BlobWriteOption(Storage.BlobWriteOption.Option.IF_GENERATION_MATCH, generation);
}
/**
* Returns an option for blob's data generation mismatch. If this option is used the request
* will fail if generation matches the provided value. This option can not be provided together
* with {@link #generationMatch(long)} or {@link #doesNotExist()}.
*/
public static BlobWriteOption generationNotMatch(long generation) {
return new BlobWriteOption(
Storage.BlobWriteOption.Option.IF_GENERATION_NOT_MATCH, generation);
}
/**
* Returns an option for blob's metageneration match. If this option is used the request will
* fail if metageneration does not match the provided value. This option can not be provided
* together with {@link #metagenerationNotMatch(long)}.
*/
public static BlobWriteOption metagenerationMatch(long metageneration) {
return new BlobWriteOption(
Storage.BlobWriteOption.Option.IF_METAGENERATION_MATCH, metageneration);
}
/**
* Returns an option for blob's metageneration mismatch. If this option is used the request will
* fail if metageneration matches the provided value. This option can not be provided together
* with {@link #metagenerationMatch(long)}.
*/
public static BlobWriteOption metagenerationNotMatch(long metageneration) {
return new BlobWriteOption(
Storage.BlobWriteOption.Option.IF_METAGENERATION_NOT_MATCH, metageneration);
}
/**
* Returns an option for blob's data MD5 hash match. If this option is used the request will
* fail if blobs' data MD5 hash does not match the provided value.
*/
public static BlobWriteOption md5Match(String md5) {
return new BlobWriteOption(Storage.BlobWriteOption.Option.IF_MD5_MATCH, md5);
}
/**
* Returns an option for blob's data CRC32C checksum match. If this option is used the request
* will fail if blobs' data CRC32C checksum does not match the provided value.
*/
public static BlobWriteOption crc32cMatch(String crc32c) {
return new BlobWriteOption(Storage.BlobWriteOption.Option.IF_CRC32C_MATCH, crc32c);
}
/**
* Returns an option to set a customer-supplied AES256 key for server-side encryption of the
* blob.
*/
public static BlobWriteOption encryptionKey(Key key) {
String base64Key = BaseEncoding.base64().encode(key.getEncoded());
return new BlobWriteOption(Storage.BlobWriteOption.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 BlobWriteOption encryptionKey(String key) {
return new BlobWriteOption(Storage.BlobWriteOption.Option.CUSTOMER_SUPPLIED_KEY, key);
}
/**
* Returns an option for blob's billing user project. This option is only used by the buckets
* with 'requester_pays' flag.
*/
public static BlobWriteOption userProject(String userProject) {
return new BlobWriteOption(Storage.BlobWriteOption.Option.USER_PROJECT, userProject);
}
static Tuple<BlobInfo, Storage.BlobWriteOption[]> toWriteOptions(
BlobInfo info, BlobWriteOption... options) {
Set<Storage.BlobWriteOption.Option> optionSet =
Sets.immutableEnumSet(Lists.transform(Arrays.asList(options), TO_ENUM));
checkArgument(
!(optionSet.contains(Storage.BlobWriteOption.Option.IF_METAGENERATION_NOT_MATCH)
&& optionSet.contains(Storage.BlobWriteOption.Option.IF_METAGENERATION_MATCH)),
"metagenerationMatch and metagenerationNotMatch options can not be both provided");
checkArgument(
!(optionSet.contains(Storage.BlobWriteOption.Option.IF_GENERATION_NOT_MATCH)
&& optionSet.contains(Storage.BlobWriteOption.Option.IF_GENERATION_MATCH)),
"Only one option of generationMatch, doesNotExist or generationNotMatch can be provided");
Storage.BlobWriteOption[] convertedOptions = new Storage.BlobWriteOption[options.length];
BlobInfo writeInfo = info;
int index = 0;
for (BlobWriteOption option : options) {
Tuple<BlobInfo, Storage.BlobWriteOption> write = option.toWriteOption(writeInfo);
writeInfo = write.x();
convertedOptions[index++] = write.y();
}
return Tuple.of(writeInfo, convertedOptions);
}
}
/** Builder for {@code Bucket}. */
public static class Builder extends BucketInfo.Builder {
private final Storage storage;
private final BucketInfo.BuilderImpl infoBuilder;
Builder(Bucket bucket) {
this.storage = bucket.storage;
this.infoBuilder = new BucketInfo.BuilderImpl(bucket);
}
@Override
public Builder setName(String name) {
infoBuilder.setName(name);
return this;
}
@Override
Builder setGeneratedId(String generatedId) {
infoBuilder.setGeneratedId(generatedId);
return this;
}
@Override
Builder setOwner(Entity owner) {
infoBuilder.setOwner(owner);
return this;
}
@Override
Builder setSelfLink(String selfLink) {
infoBuilder.setSelfLink(selfLink);
return this;
}
@Override
public Builder setVersioningEnabled(Boolean enable) {
infoBuilder.setVersioningEnabled(enable);
return this;
}
@Override
public Builder setRequesterPays(Boolean requesterPays) {
infoBuilder.setRequesterPays(requesterPays);
return this;
}
@Override
public Builder setIndexPage(String indexPage) {
infoBuilder.setIndexPage(indexPage);
return this;
}
@Override
public Builder setNotFoundPage(String notFoundPage) {
infoBuilder.setNotFoundPage(notFoundPage);
return this;
}
@Override
@Deprecated
public Builder setDeleteRules(Iterable<? extends DeleteRule> rules) {
infoBuilder.setDeleteRules(rules);
return this;
}
@Override
public Builder setLifecycleRules(Iterable<? extends LifecycleRule> rules) {
infoBuilder.setLifecycleRules(rules);
return this;
}
@Override
public Builder deleteLifecycleRules() {
infoBuilder.deleteLifecycleRules();
return this;
}
@Override
public Builder setRpo(Rpo rpo) {
infoBuilder.setRpo(rpo);
return this;
}
@Override
public Builder setStorageClass(StorageClass storageClass) {
infoBuilder.setStorageClass(storageClass);
return this;
}
@Override
public Builder setLocation(String location) {
infoBuilder.setLocation(location);
return this;
}
@Override
Builder setEtag(String etag) {
infoBuilder.setEtag(etag);
return this;
}
@Override
Builder setCreateTime(Long createTime) {
infoBuilder.setCreateTime(createTime);
return this;
}
@Override
Builder setUpdateTime(Long updateTime) {
infoBuilder.setUpdateTime(updateTime);
return this;
}
@Override
Builder setMetageneration(Long metageneration) {
infoBuilder.setMetageneration(metageneration);
return this;
}
@Override
public Builder setCors(Iterable<Cors> cors) {
infoBuilder.setCors(cors);
return this;
}
@Override
public Builder setAcl(Iterable<Acl> acl) {
infoBuilder.setAcl(acl);
return this;
}
@Override
public Builder setDefaultAcl(Iterable<Acl> acl) {
infoBuilder.setDefaultAcl(acl);
return this;
}
@Override
public Builder setLabels(Map<String, String> labels) {
infoBuilder.setLabels(labels);
return this;
}
@Override
public Builder setDefaultKmsKeyName(String defaultKmsKeyName) {
infoBuilder.setDefaultKmsKeyName(defaultKmsKeyName);
return this;
}
@Override
public Builder setDefaultEventBasedHold(Boolean defaultEventBasedHold) {
infoBuilder.setDefaultEventBasedHold(defaultEventBasedHold);
return this;
}
@Override
Builder setRetentionEffectiveTime(Long retentionEffectiveTime) {
infoBuilder.setRetentionEffectiveTime(retentionEffectiveTime);
return this;
}
@Override
Builder setRetentionPolicyIsLocked(Boolean retentionIsLocked) {
infoBuilder.setRetentionPolicyIsLocked(retentionIsLocked);
return this;
}
@Override
public Builder setRetentionPeriod(Long retentionPeriod) {
infoBuilder.setRetentionPeriod(retentionPeriod);
return this;
}
@Override
public Builder setIamConfiguration(IamConfiguration iamConfiguration) {
infoBuilder.setIamConfiguration(iamConfiguration);
return this;
}
@Override
public Builder setLogging(Logging logging) {
infoBuilder.setLogging(logging);
return this;
}
@Override
Builder setLocationType(String locationType) {
infoBuilder.setLocationType(locationType);
return this;
}
@Override
public Bucket build() {
return new Bucket(storage, infoBuilder);
}
}
Bucket(Storage storage, BucketInfo.BuilderImpl infoBuilder) {
super(infoBuilder);
this.storage = checkNotNull(storage);
this.options = storage.getOptions();
}
/**
* Checks if this bucket exists.
*
* <p>Example of checking if the bucket exists.
*
* <pre>{@code
* boolean exists = bucket.exists();
* if (exists) {
* // the bucket exists
* } else {
* // the bucket was not found
* }
* }</pre>
*
* @return true if this bucket exists, false otherwise
* @throws StorageException upon failure
*/
public boolean exists(BucketSourceOption... options) {
int length = options.length;
Storage.BucketGetOption[] getOptions = Arrays.copyOf(toGetOptions(this, options), length + 1);
getOptions[length] = Storage.BucketGetOption.fields();
return storage.get(getName(), getOptions) != null;
}
/**
* Fetches current bucket's latest information. Returns {@code null} if the bucket does not exist.
*
* <p>Example of getting the bucket's latest information, if its generation does not match the
* {@link Bucket#getMetageneration()} value, otherwise a {@link StorageException} is thrown.
*
* <pre>{@code
* Bucket latestBucket = bucket.reload(BucketSourceOption.metagenerationMatch());
* if (latestBucket == null) {
* // the bucket was not found
* }
* }</pre>
*
* @param options bucket read options
* @return a {@code Bucket} object with latest information or {@code null} if not found
* @throws StorageException upon failure
*/
public Bucket reload(BucketSourceOption... options) {
return storage.get(getName(), toGetOptions(this, options));
}
/**
* Updates the bucket's information. Bucket's name cannot be changed. A new {@code Bucket} object
* is returned. By default no checks are made on the metadata generation of the current bucket. If
* you want to update the information only if the current bucket metadata are at their latest
* version use the {@code metagenerationMatch} option: {@code
* bucket.update(BucketTargetOption.metagenerationMatch())}
*
* <p>Example of updating the bucket's information.
*
* <pre>{@code
* Bucket updatedBucket = bucket.toBuilder().setVersioningEnabled(true).build().update();
* }</pre>
*
* @param options update options
* @return a {@code Bucket} object with updated information
* @throws StorageException upon failure
*/
public Bucket update(BucketTargetOption... options) {
return storage.update(this, options);
}
/**
* Deletes this bucket.
*
* <p>Example of deleting the bucket, if its metageneration matches the {@link
* Bucket#getMetageneration()} value, otherwise a {@link StorageException} is thrown.
*
* <pre>{@code
* boolean deleted = bucket.delete(BucketSourceOption.metagenerationMatch());
* if (deleted) {
* // the bucket was deleted
* } else {
* // the bucket was not found
* }
* }</pre>
*
* @param options bucket delete options
* @return {@code true} if bucket was deleted, {@code false} if it was not found
* @throws StorageException upon failure
*/
public boolean delete(BucketSourceOption... options) {
return storage.delete(getName(), toSourceOptions(this, options));
}
/**
* Returns the paginated list of {@code Blob} in this bucket.
*
* <p>Example of listing the blobs in the bucket.
*
* <pre>{@code
* Page<Blob> blobs = bucket.list();
* Iterator<Blob> blobIterator = blobs.iterateAll();
* while (blobIterator.hasNext()) {
* Blob blob = blobIterator.next();
* // do something with the blob
* }
* }</pre>
*
* @param options options for listing blobs
* @throws StorageException upon failure
*/
public Page<Blob> list(BlobListOption... options) {
return storage.list(getName(), options);
}
/**
* Returns the requested blob in this bucket or {@code null} if not found.
*
* <p>Example of getting a blob in the bucket, only if its metageneration matches a value,
* otherwise a {@link StorageException} is thrown.
*
* <pre>{@code
* String blobName = "my_blob_name";
* long generation = 42;
* Blob blob = bucket.get(blobName, BlobGetOption.generationMatch(generation));
* }</pre>
*
* @param blob name of the requested blob
* @param options blob search options
* @throws StorageException upon failure
*/
public Blob get(String blob, BlobGetOption... options) {
return storage.get(BlobId.of(getName(), blob), options);
}
/**
* Returns a list of requested blobs in this bucket. Blobs that do not exist are null.
*
* <p>Example of getting some blobs in the bucket, using a batch request.
*
* <pre>{@code
* String blobName1 = "my_blob_name1";
* String blobName2 = "my_blob_name2";
* List<Blob> blobs = bucket.get(blobName1, blobName2);
* for (Blob blob : blobs) {
* if (blob == null) {
* // the blob was not found
* }
* }
* }</pre>
*
* @param blobName1 first blob to get
* @param blobName2 second blob to get
* @param blobNames other blobs to get
* @return an immutable list of {@code Blob} objects
* @throws StorageException upon failure
*/
public List<Blob> get(String blobName1, String blobName2, String... blobNames) {
List<BlobId> blobIds = Lists.newArrayListWithCapacity(blobNames.length + 2);
blobIds.add(BlobId.of(getName(), blobName1));
blobIds.add(BlobId.of(getName(), blobName2));
for (String blobName : blobNames) {
blobIds.add(BlobId.of(getName(), blobName));
}
return storage.get(blobIds);
}
/**
* Returns a list of requested blobs in this bucket. Blobs that do not exist are null.
*
* <p>Example of getting some blobs in the bucket, using a batch request.
*
* <pre>{@code
* String blobName1 = "my_blob_name1";
* String blobName2 = "my_blob_name2";
* List<String> blobNames = new LinkedList<>();
* blobNames.add(blobName1);
* blobNames.add(blobName2);
* List<Blob> blobs = bucket.get(blobNames);
* for (Blob blob : blobs) {
* if (blob == null) {
* // the blob was not found
* }
* }
* }</pre>
*
* @param blobNames blobs to get
* @return an immutable list of {@code Blob} objects
* @throws StorageException upon failure
*/
public List<Blob> get(Iterable<String> blobNames) {
ImmutableList.Builder<BlobId> builder = ImmutableList.builder();
for (String blobName : blobNames) {
builder.add(BlobId.of(getName(), blobName));
}
return storage.get(builder.build());
}
/**
* Creates a new blob in this bucket. Direct upload is used to upload {@code content}. For large
* content, {@link Blob#writer(com.google.cloud.storage.Storage.BlobWriteOption...)} is
* recommended as it uses resumable upload. MD5 and CRC32C hashes of {@code content} are computed
* and used for validating transferred data.
*
* <p>Example of creating a blob in the bucket from a byte array with a content type.
*
* <pre>{@code
* String blobName = "my_blob_name";
* Blob blob = bucket.create(blobName, "Hello, World!".getBytes(UTF_8), "text/plain");
* }</pre>
*
* @param blob a blob name
* @param content the blob content
* @param contentType the blob content type
* @param options options for blob creation
* @return a complete blob information
* @throws StorageException upon failure
*/
public Blob create(String blob, byte[] content, String contentType, BlobTargetOption... options) {
BlobInfo blobInfo =
BlobInfo.newBuilder(BlobId.of(getName(), blob)).setContentType(contentType).build();
Tuple<BlobInfo, Storage.BlobTargetOption[]> target =
BlobTargetOption.toTargetOptions(blobInfo, options);
return storage.create(target.x(), content, target.y());
}
/**
* Creates a new blob in this bucket. Direct upload is used to upload {@code content}. For large
* content, {@link Blob#writer(com.google.cloud.storage.Storage.BlobWriteOption...)} is
* recommended as it uses resumable upload.
*
* <p>Example of creating a blob in the bucket from an input stream with a content type.
*
* <pre>{@code
* String blobName = "my_blob_name";
* InputStream content = new ByteArrayInputStream("Hello, World!".getBytes(UTF_8));
* Blob blob = bucket.create(blobName, content, "text/plain");
* }</pre>
*
* @param blob a blob name
* @param content the blob content as a stream
* @param contentType the blob content type
* @param options options for blob creation
* @return a complete blob information
* @throws StorageException upon failure
*/
public Blob create(
String blob, InputStream content, String contentType, BlobWriteOption... options) {
BlobInfo blobInfo =
BlobInfo.newBuilder(BlobId.of(getName(), blob)).setContentType(contentType).build();
Tuple<BlobInfo, Storage.BlobWriteOption[]> write =
BlobWriteOption.toWriteOptions(blobInfo, options);
return storage.create(write.x(), content, write.y());
}
/**
* Creates a new blob in this bucket. Direct upload is used to upload {@code content}. For large
* content, {@link Blob#writer(com.google.cloud.storage.Storage.BlobWriteOption...)} is
* recommended as it uses resumable upload. MD5 and CRC32C hashes of {@code content} are computed
* and used for validating transferred data.
*
* <p>Example of creating a blob in the bucket from a byte array.
*
* <pre>{@code
* String blobName = "my_blob_name";
* Blob blob = bucket.create(blobName, "Hello, World!".getBytes(UTF_8));
* }</pre>
*
* @param blob a blob name
* @param content the blob content
* @param options options for blob creation
* @return a complete blob information
* @throws StorageException upon failure
*/
public Blob create(String blob, byte[] content, BlobTargetOption... options) {
BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(getName(), blob)).build();
Tuple<BlobInfo, Storage.BlobTargetOption[]> target =
BlobTargetOption.toTargetOptions(blobInfo, options);
return storage.create(target.x(), content, target.y());
}
/**
* Creates a new blob in this bucket. Direct upload is used to upload {@code content}. For large
* content, {@link Blob#writer(com.google.cloud.storage.Storage.BlobWriteOption...)} is
* recommended as it uses resumable upload.
*
* <p>Example of creating a blob in the bucket from an input stream.
*
* <pre>{@code
* String blobName = "my_blob_name";
* InputStream content = new ByteArrayInputStream("Hello, World!".getBytes(UTF_8));
* Blob blob = bucket.create(blobName, content);
* }</pre>
*
* @param blob a blob name
* @param content the blob content as a stream
* @param options options for blob creation
* @return a complete blob information
* @throws StorageException upon failure
*/