forked from googleapis/google-cloud-java
/
StorageImpl.java
918 lines (838 loc) · 34.6 KB
/
StorageImpl.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
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.spi.StorageRpc.Option.DELIMITER;
import static com.google.cloud.storage.spi.StorageRpc.Option.IF_GENERATION_MATCH;
import static com.google.cloud.storage.spi.StorageRpc.Option.IF_GENERATION_NOT_MATCH;
import static com.google.cloud.storage.spi.StorageRpc.Option.IF_METAGENERATION_MATCH;
import static com.google.cloud.storage.spi.StorageRpc.Option.IF_METAGENERATION_NOT_MATCH;
import static com.google.cloud.storage.spi.StorageRpc.Option.IF_SOURCE_GENERATION_MATCH;
import static com.google.cloud.storage.spi.StorageRpc.Option.IF_SOURCE_GENERATION_NOT_MATCH;
import static com.google.cloud.storage.spi.StorageRpc.Option.IF_SOURCE_METAGENERATION_MATCH;
import static com.google.cloud.storage.spi.StorageRpc.Option.IF_SOURCE_METAGENERATION_NOT_MATCH;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.api.services.storage.model.BucketAccessControl;
import com.google.api.services.storage.model.ObjectAccessControl;
import com.google.api.services.storage.model.StorageObject;
import com.google.cloud.BaseService;
import com.google.cloud.BatchResult;
import com.google.cloud.Page;
import com.google.cloud.PageImpl;
import com.google.cloud.PageImpl.NextPageFetcher;
import com.google.cloud.ReadChannel;
import com.google.cloud.RetryHelper.RetryHelperException;
import com.google.cloud.ServiceAccountSigner;
import com.google.cloud.storage.Acl.Entity;
import com.google.cloud.storage.spi.StorageRpc;
import com.google.cloud.storage.spi.StorageRpc.RewriteResponse;
import com.google.cloud.storage.spi.StorageRpc.Tuple;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import com.google.common.primitives.Ints;
import com.google.common.net.UrlEscapers;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
final class StorageImpl extends BaseService<StorageOptions> implements Storage {
private static final byte[] EMPTY_BYTE_ARRAY = {};
private static final String EMPTY_BYTE_ARRAY_MD5 = "1B2M2Y8AsgTpgAmY7PhCfg==";
private static final String EMPTY_BYTE_ARRAY_CRC32C = "AAAAAA==";
private static final String PATH_DELIMITER = "/";
private static final Function<Tuple<Storage, Boolean>, Boolean> DELETE_FUNCTION =
new Function<Tuple<Storage, Boolean>, Boolean>() {
@Override
public Boolean apply(Tuple<Storage, Boolean> tuple) {
return tuple.y();
}
};
private final StorageRpc storageRpc;
StorageImpl(StorageOptions options) {
super(options);
storageRpc = options.rpc();
}
@Override
public Bucket create(BucketInfo bucketInfo, BucketTargetOption... options) {
final com.google.api.services.storage.model.Bucket bucketPb = bucketInfo.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(bucketInfo, options);
try {
return Bucket.fromPb(this, runWithRetries(
new Callable<com.google.api.services.storage.model.Bucket>() {
@Override
public com.google.api.services.storage.model.Bucket call() {
return storageRpc.create(bucketPb, optionsMap);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob create(BlobInfo blobInfo, BlobTargetOption... options) {
BlobInfo updatedInfo = blobInfo.toBuilder()
.md5(EMPTY_BYTE_ARRAY_MD5)
.crc32c(EMPTY_BYTE_ARRAY_CRC32C)
.build();
return create(updatedInfo, new ByteArrayInputStream(EMPTY_BYTE_ARRAY), options);
}
@Override
public Blob create(BlobInfo blobInfo, byte[] content, BlobTargetOption... options) {
content = firstNonNull(content, EMPTY_BYTE_ARRAY);
BlobInfo updatedInfo = blobInfo.toBuilder()
.md5(BaseEncoding.base64().encode(Hashing.md5().hashBytes(content).asBytes()))
.crc32c(BaseEncoding.base64().encode(
Ints.toByteArray(Hashing.crc32c().hashBytes(content).asInt())))
.build();
return create(updatedInfo, new ByteArrayInputStream(content), options);
}
@Override
public Blob create(BlobInfo blobInfo, InputStream content, BlobWriteOption... options) {
Tuple<BlobInfo, BlobTargetOption[]> targetOptions = BlobTargetOption.convert(blobInfo, options);
return create(targetOptions.x(), content, targetOptions.y());
}
private Blob create(BlobInfo info, final InputStream content, BlobTargetOption... options) {
final StorageObject blobPb = info.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(info, options);
try {
return Blob.fromPb(this, runWithRetries(new Callable<StorageObject>() {
@Override
public StorageObject call() {
return storageRpc.create(blobPb,
firstNonNull(content, new ByteArrayInputStream(EMPTY_BYTE_ARRAY)), optionsMap);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Bucket get(String bucket, BucketGetOption... options) {
final com.google.api.services.storage.model.Bucket bucketPb = BucketInfo.of(bucket).toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(options);
try {
com.google.api.services.storage.model.Bucket answer = runWithRetries(
new Callable<com.google.api.services.storage.model.Bucket>() {
@Override
public com.google.api.services.storage.model.Bucket call() {
return storageRpc.get(bucketPb, optionsMap);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
return answer == null ? null : Bucket.fromPb(this, answer);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob get(String bucket, String blob, BlobGetOption... options) {
return get(BlobId.of(bucket, blob), options);
}
@Override
public Blob get(BlobId blob, BlobGetOption... options) {
final StorageObject storedObject = blob.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blob, options);
try {
StorageObject storageObject = runWithRetries(new Callable<StorageObject>() {
@Override
public StorageObject call() {
return storageRpc.get(storedObject, optionsMap);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
return storageObject == null ? null : Blob.fromPb(this, storageObject);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob get(BlobId blob) {
return get(blob, new BlobGetOption[0]);
}
private static class BucketPageFetcher implements NextPageFetcher<Bucket> {
private static final long serialVersionUID = 5850406828803613729L;
private final Map<StorageRpc.Option, ?> requestOptions;
private final StorageOptions serviceOptions;
BucketPageFetcher(
StorageOptions serviceOptions, String cursor,
Map<StorageRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(StorageRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
}
@Override
public Page<Bucket> nextPage() {
return listBuckets(serviceOptions, requestOptions);
}
}
private static class BlobPageFetcher implements NextPageFetcher<Blob> {
private static final long serialVersionUID = 81807334445874098L;
private final Map<StorageRpc.Option, ?> requestOptions;
private final StorageOptions serviceOptions;
private final String bucket;
BlobPageFetcher(String bucket, StorageOptions serviceOptions, String cursor,
Map<StorageRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(StorageRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
this.bucket = bucket;
}
@Override
public Page<Blob> nextPage() {
return listBlobs(bucket, serviceOptions, requestOptions);
}
}
@Override
public Page<Bucket> list(BucketListOption... options) {
return listBuckets(options(), optionMap(options));
}
@Override
public Page<Blob> list(final String bucket, BlobListOption... options) {
return listBlobs(bucket, options(), optionMap(options));
}
private static Page<Bucket> listBuckets(final StorageOptions serviceOptions,
final Map<StorageRpc.Option, ?> optionsMap) {
try {
Tuple<String, Iterable<com.google.api.services.storage.model.Bucket>> result = runWithRetries(
new Callable<Tuple<String, Iterable<com.google.api.services.storage.model.Bucket>>>() {
@Override
public Tuple<String, Iterable<com.google.api.services.storage.model.Bucket>> call() {
return serviceOptions.rpc().list(optionsMap);
}
}, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock());
String cursor = result.x();
Iterable<Bucket> buckets =
result.y() == null ? ImmutableList.<Bucket>of() : Iterables.transform(result.y(),
new Function<com.google.api.services.storage.model.Bucket, Bucket>() {
@Override
public Bucket apply(com.google.api.services.storage.model.Bucket bucketPb) {
return Bucket.fromPb(serviceOptions.service(), bucketPb);
}
});
return new PageImpl<>(
new BucketPageFetcher(serviceOptions, cursor, optionsMap), cursor,
buckets);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
private static Page<Blob> listBlobs(final String bucket,
final StorageOptions serviceOptions, final Map<StorageRpc.Option, ?> optionsMap) {
try {
Tuple<String, Iterable<StorageObject>> result = runWithRetries(
new Callable<Tuple<String, Iterable<StorageObject>>>() {
@Override
public Tuple<String, Iterable<StorageObject>> call() {
return serviceOptions.rpc().list(bucket, optionsMap);
}
}, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock());
String cursor = result.x();
Iterable<Blob> blobs =
result.y() == null
? ImmutableList.<Blob>of()
: Iterables.transform(result.y(), new Function<StorageObject, Blob>() {
@Override
public Blob apply(StorageObject storageObject) {
return Blob.fromPb(serviceOptions.service(), storageObject);
}
});
return new PageImpl<>(
new BlobPageFetcher(bucket, serviceOptions, cursor, optionsMap),
cursor,
blobs);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Bucket update(BucketInfo bucketInfo, BucketTargetOption... options) {
final com.google.api.services.storage.model.Bucket bucketPb = bucketInfo.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(bucketInfo, options);
try {
return Bucket.fromPb(this, runWithRetries(
new Callable<com.google.api.services.storage.model.Bucket>() {
@Override
public com.google.api.services.storage.model.Bucket call() {
return storageRpc.patch(bucketPb, optionsMap);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob update(BlobInfo blobInfo, BlobTargetOption... options) {
final StorageObject storageObject = blobInfo.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blobInfo, options);
try {
return Blob.fromPb(this, runWithRetries(new Callable<StorageObject>() {
@Override
public StorageObject call() {
return storageRpc.patch(storageObject, optionsMap);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Blob update(BlobInfo blobInfo) {
return update(blobInfo, new BlobTargetOption[0]);
}
@Override
public boolean delete(String bucket, BucketSourceOption... options) {
final com.google.api.services.storage.model.Bucket bucketPb = BucketInfo.of(bucket).toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(options);
try {
return runWithRetries(new Callable<Boolean>() {
@Override
public Boolean call() {
return storageRpc.delete(bucketPb, optionsMap);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public boolean delete(String bucket, String blob, BlobSourceOption... options) {
return delete(BlobId.of(bucket, blob), options);
}
@Override
public boolean delete(BlobId blob, BlobSourceOption... options) {
final StorageObject storageObject = blob.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blob, options);
try {
return runWithRetries(new Callable<Boolean>() {
@Override
public Boolean call() {
return storageRpc.delete(storageObject, optionsMap);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public boolean delete(BlobId blob) {
return delete(blob, new BlobSourceOption[0]);
}
@Override
public Blob compose(final ComposeRequest composeRequest) {
final List<StorageObject> sources =
Lists.newArrayListWithCapacity(composeRequest.sourceBlobs().size());
for (ComposeRequest.SourceBlob sourceBlob : composeRequest.sourceBlobs()) {
sources.add(BlobInfo.builder(
BlobId.of(composeRequest.target().bucket(), sourceBlob.name(), sourceBlob.generation()))
.build().toPb());
}
final StorageObject target = composeRequest.target().toPb();
final Map<StorageRpc.Option, ?> targetOptions = optionMap(composeRequest.target().generation(),
composeRequest.target().metageneration(), composeRequest.targetOptions());
try {
return Blob.fromPb(this, runWithRetries(new Callable<StorageObject>() {
@Override
public StorageObject call() {
return storageRpc.compose(sources, target, targetOptions);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public CopyWriter copy(final CopyRequest copyRequest) {
final StorageObject source = copyRequest.source().toPb();
final Map<StorageRpc.Option, ?> sourceOptions =
optionMap(copyRequest.source().generation(), null, copyRequest.sourceOptions(), true);
final StorageObject targetObject = copyRequest.target().toPb();
final Map<StorageRpc.Option, ?> targetOptions = optionMap(copyRequest.target().generation(),
copyRequest.target().metageneration(), copyRequest.targetOptions());
try {
RewriteResponse rewriteResponse = runWithRetries(new Callable<RewriteResponse>() {
@Override
public RewriteResponse call() {
return storageRpc.openRewrite(new StorageRpc.RewriteRequest(source, sourceOptions,
copyRequest.overrideInfo(), targetObject, targetOptions,
copyRequest.megabytesCopiedPerChunk()));
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
return new CopyWriter(options(), rewriteResponse);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public byte[] readAllBytes(String bucket, String blob, BlobSourceOption... options) {
return readAllBytes(BlobId.of(bucket, blob), options);
}
@Override
public byte[] readAllBytes(BlobId blob, BlobSourceOption... options) {
final StorageObject storageObject = blob.toPb();
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blob, options);
try {
return runWithRetries(new Callable<byte[]>() {
@Override
public byte[] call() {
return storageRpc.load(storageObject, optionsMap);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public StorageBatch batch() {
return new StorageBatch(this.options());
}
@Override
public ReadChannel reader(String bucket, String blob, BlobSourceOption... options) {
Map<StorageRpc.Option, ?> optionsMap = optionMap(options);
return new BlobReadChannel(options(), BlobId.of(bucket, blob), optionsMap);
}
@Override
public ReadChannel reader(BlobId blob, BlobSourceOption... options) {
Map<StorageRpc.Option, ?> optionsMap = optionMap(blob, options);
return new BlobReadChannel(options(), blob, optionsMap);
}
@Override
public BlobWriteChannel writer(BlobInfo blobInfo, BlobWriteOption... options) {
Tuple<BlobInfo, BlobTargetOption[]> targetOptions = BlobTargetOption.convert(blobInfo, options);
return writer(targetOptions.x(), targetOptions.y());
}
private BlobWriteChannel writer(BlobInfo blobInfo, BlobTargetOption... options) {
final Map<StorageRpc.Option, ?> optionsMap = optionMap(blobInfo, options);
return new BlobWriteChannel(options(), blobInfo, optionsMap);
}
@Override
public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOption... options) {
EnumMap<SignUrlOption.Option, Object> optionMap = Maps.newEnumMap(SignUrlOption.Option.class);
for (SignUrlOption option : options) {
optionMap.put(option.option(), option.value());
}
ServiceAccountSigner authCredentials =
(ServiceAccountSigner) optionMap.get(SignUrlOption.Option.SERVICE_ACCOUNT_CRED);
if (authCredentials == null) {
checkState(this.options().authCredentials() instanceof ServiceAccountSigner,
"Signing key was not provided and could not be derived");
authCredentials = (ServiceAccountSigner) this.options().authCredentials();
}
// construct signature - see https://cloud.google.com/storage/docs/access-control#Signed-URLs
StringBuilder stBuilder = new StringBuilder();
if (optionMap.containsKey(SignUrlOption.Option.HTTP_METHOD)) {
stBuilder.append(optionMap.get(SignUrlOption.Option.HTTP_METHOD));
} else {
stBuilder.append(HttpMethod.GET);
}
stBuilder.append('\n');
if (firstNonNull((Boolean) optionMap.get(SignUrlOption.Option.MD5), false)) {
checkArgument(blobInfo.md5() != null, "Blob is missing a value for md5");
stBuilder.append(blobInfo.md5());
}
stBuilder.append('\n');
if (firstNonNull((Boolean) optionMap.get(SignUrlOption.Option.CONTENT_TYPE), false)) {
checkArgument(blobInfo.contentType() != null, "Blob is missing a value for content-type");
stBuilder.append(blobInfo.contentType());
}
stBuilder.append('\n');
long expiration = TimeUnit.SECONDS.convert(
options().clock().millis() + unit.toMillis(duration), TimeUnit.MILLISECONDS);
stBuilder.append(expiration).append('\n');
StringBuilder path = new StringBuilder();
if (!blobInfo.bucket().startsWith("/")) {
path.append('/');
}
path.append(blobInfo.bucket());
if (!blobInfo.bucket().endsWith("/")) {
path.append('/');
}
if (blobInfo.name().startsWith("/")) {
path.setLength(path.length() - 1);
}
path.append(UrlEscapers.urlPathSegmentEscaper().escape(blobInfo.name()));
stBuilder.append(path);
try {
byte[] signatureBytes = authCredentials.sign(stBuilder.toString().getBytes(UTF_8));
stBuilder = new StringBuilder("https://storage.googleapis.com").append(path);
String signature =
URLEncoder.encode(BaseEncoding.base64().encode(signatureBytes), UTF_8.name());
stBuilder.append("?GoogleAccessId=").append(authCredentials.account());
stBuilder.append("&Expires=").append(expiration);
stBuilder.append("&Signature=").append(signature);
return new URL(stBuilder.toString());
} catch (MalformedURLException | UnsupportedEncodingException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public List<Blob> get(BlobId... blobIds) {
return get(Arrays.asList(blobIds));
}
@Override
public List<Blob> get(Iterable<BlobId> blobIds) {
StorageBatch batch = batch();
final List<Blob> results = Lists.newArrayList();
for (BlobId blob : blobIds) {
batch.get(blob).notify(new BatchResult.Callback<Blob, StorageException>() {
@Override
public void success(Blob result) {
results.add(result);
}
@Override
public void error(StorageException exception) {
results.add(null);
}
});
}
batch.submit();
return Collections.unmodifiableList(results);
}
@Override
public List<Blob> update(BlobInfo... blobInfos) {
return update(Arrays.asList(blobInfos));
}
@Override
public List<Blob> update(Iterable<BlobInfo> blobInfos) {
StorageBatch batch = batch();
final List<Blob> results = Lists.newArrayList();
for (BlobInfo blobInfo : blobInfos) {
batch.update(blobInfo).notify(new BatchResult.Callback<Blob, StorageException>() {
@Override
public void success(Blob result) {
results.add(result);
}
@Override
public void error(StorageException exception) {
results.add(null);
}
});
}
batch.submit();
return Collections.unmodifiableList(results);
}
@Override
public List<Boolean> delete(BlobId... blobIds) {
return delete(Arrays.asList(blobIds));
}
@Override
public List<Boolean> delete(Iterable<BlobId> blobIds) {
StorageBatch batch = batch();
final List<Boolean> results = Lists.newArrayList();
for (BlobId blob : blobIds) {
batch.delete(blob).notify(new BatchResult.Callback<Boolean, StorageException>() {
@Override
public void success(Boolean result) {
results.add(result);
}
@Override
public void error(StorageException exception) {
results.add(Boolean.FALSE);
}
});
}
batch.submit();
return Collections.unmodifiableList(results);
}
@Override
public Acl getAcl(final String bucket, final Entity entity) {
try {
BucketAccessControl answer = runWithRetries(new Callable<BucketAccessControl>() {
@Override
public BucketAccessControl call() {
return storageRpc.getAcl(bucket, entity.toPb());
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
return answer == null ? null : Acl.fromPb(answer);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public boolean deleteAcl(final String bucket, final Entity entity) {
try {
return runWithRetries(new Callable<Boolean>() {
@Override
public Boolean call() {
return storageRpc.deleteAcl(bucket, entity.toPb());
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Acl createAcl(String bucket, Acl acl) {
final BucketAccessControl aclPb = acl.toBucketPb().setBucket(bucket);
try {
return Acl.fromPb(runWithRetries(new Callable<BucketAccessControl>() {
@Override
public BucketAccessControl call() {
return storageRpc.createAcl(aclPb);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Acl updateAcl(String bucket, Acl acl) {
final BucketAccessControl aclPb = acl.toBucketPb().setBucket(bucket);
try {
return Acl.fromPb(runWithRetries(new Callable<BucketAccessControl>() {
@Override
public BucketAccessControl call() {
return storageRpc.patchAcl(aclPb);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public List<Acl> listAcls(final String bucket) {
try {
List<BucketAccessControl> answer = runWithRetries(new Callable<List<BucketAccessControl>>() {
@Override
public List<BucketAccessControl> call() {
return storageRpc.listAcls(bucket);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
return Lists.transform(answer, Acl.FROM_BUCKET_PB_FUNCTION);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Acl getDefaultAcl(final String bucket, final Entity entity) {
try {
ObjectAccessControl answer = runWithRetries(new Callable<ObjectAccessControl>() {
@Override
public ObjectAccessControl call() {
return storageRpc.getDefaultAcl(bucket, entity.toPb());
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
return answer == null ? null : Acl.fromPb(answer);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public boolean deleteDefaultAcl(final String bucket, final Entity entity) {
try {
return runWithRetries(new Callable<Boolean>() {
@Override
public Boolean call() {
return storageRpc.deleteDefaultAcl(bucket, entity.toPb());
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Acl createDefaultAcl(String bucket, Acl acl) {
final ObjectAccessControl aclPb = acl.toObjectPb().setBucket(bucket);
try {
return Acl.fromPb(runWithRetries(new Callable<ObjectAccessControl>() {
@Override
public ObjectAccessControl call() {
return storageRpc.createDefaultAcl(aclPb);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Acl updateDefaultAcl(String bucket, Acl acl) {
final ObjectAccessControl aclPb = acl.toObjectPb().setBucket(bucket);
try {
return Acl.fromPb(runWithRetries(new Callable<ObjectAccessControl>() {
@Override
public ObjectAccessControl call() {
return storageRpc.patchDefaultAcl(aclPb);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public List<Acl> listDefaultAcls(final String bucket) {
try {
List<ObjectAccessControl> answer = runWithRetries(new Callable<List<ObjectAccessControl>>() {
@Override
public List<ObjectAccessControl> call() {
return storageRpc.listDefaultAcls(bucket);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
return Lists.transform(answer, Acl.FROM_OBJECT_PB_FUNCTION);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Acl getAcl(final BlobId blob, final Entity entity) {
try {
ObjectAccessControl answer = runWithRetries(new Callable<ObjectAccessControl>() {
@Override
public ObjectAccessControl call() {
return storageRpc.getAcl(blob.bucket(), blob.name(), blob.generation(), entity.toPb());
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
return answer == null ? null : Acl.fromPb(answer);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public boolean deleteAcl(final BlobId blob, final Entity entity) {
try {
return runWithRetries(new Callable<Boolean>() {
@Override
public Boolean call() {
return storageRpc.deleteAcl(blob.bucket(), blob.name(), blob.generation(), entity.toPb());
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Acl createAcl(final BlobId blob, final Acl acl) {
final ObjectAccessControl aclPb = acl.toObjectPb()
.setBucket(blob.bucket())
.setObject(blob.name())
.setGeneration(blob.generation());
try {
return Acl.fromPb(runWithRetries(new Callable<ObjectAccessControl>() {
@Override
public ObjectAccessControl call() {
return storageRpc.createAcl(aclPb);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public Acl updateAcl(BlobId blob, Acl acl) {
final ObjectAccessControl aclPb = acl.toObjectPb()
.setBucket(blob.bucket())
.setObject(blob.name())
.setGeneration(blob.generation());
try {
return Acl.fromPb(runWithRetries(new Callable<ObjectAccessControl>() {
@Override
public ObjectAccessControl call() {
return storageRpc.patchAcl(aclPb);
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock()));
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
@Override
public List<Acl> listAcls(final BlobId blob) {
try {
List<ObjectAccessControl> answer = runWithRetries(new Callable<List<ObjectAccessControl>>() {
@Override
public List<ObjectAccessControl> call() {
return storageRpc.listAcls(blob.bucket(), blob.name(), blob.generation());
}
}, options().retryParams(), EXCEPTION_HANDLER, options().clock());
return Lists.transform(answer, Acl.FROM_OBJECT_PB_FUNCTION);
} catch (RetryHelperException e) {
throw StorageException.translateAndThrow(e);
}
}
private static <T> void addToOptionMap(StorageRpc.Option option, T defaultValue,
Map<StorageRpc.Option, Object> map) {
addToOptionMap(option, option, defaultValue, map);
}
private static <T> void addToOptionMap(StorageRpc.Option getOption, StorageRpc.Option putOption,
T defaultValue, Map<StorageRpc.Option, Object> map) {
if (map.containsKey(getOption)) {
@SuppressWarnings("unchecked")
T value = (T) map.remove(getOption);
checkArgument(value != null || defaultValue != null,
"Option " + getOption.value() + " is missing a value");
value = firstNonNull(value, defaultValue);
map.put(putOption, value);
}
}
private static Map<StorageRpc.Option, ?> optionMap(Long generation, Long metaGeneration,
Iterable<? extends Option> options) {
return optionMap(generation, metaGeneration, options, false);
}
private static Map<StorageRpc.Option, ?> optionMap(Long generation, Long metaGeneration,
Iterable<? extends Option> options, boolean useAsSource) {
Map<StorageRpc.Option, Object> temp = Maps.newEnumMap(StorageRpc.Option.class);
for (Option option : options) {
Object prev = temp.put(option.rpcOption(), option.value());
checkArgument(prev == null, "Duplicate option %s", option);
}
Boolean value = (Boolean) temp.remove(DELIMITER);
if (Boolean.TRUE.equals(value)) {
temp.put(DELIMITER, PATH_DELIMITER);
}
if (useAsSource) {
addToOptionMap(IF_GENERATION_MATCH, IF_SOURCE_GENERATION_MATCH, generation, temp);
addToOptionMap(IF_GENERATION_NOT_MATCH, IF_SOURCE_GENERATION_NOT_MATCH, generation, temp);
addToOptionMap(IF_METAGENERATION_MATCH, IF_SOURCE_METAGENERATION_MATCH, metaGeneration, temp);
addToOptionMap(IF_METAGENERATION_NOT_MATCH,
IF_SOURCE_METAGENERATION_NOT_MATCH, metaGeneration, temp);
} else {
addToOptionMap(IF_GENERATION_MATCH, generation, temp);
addToOptionMap(IF_GENERATION_NOT_MATCH, generation, temp);
addToOptionMap(IF_METAGENERATION_MATCH, metaGeneration, temp);
addToOptionMap(IF_METAGENERATION_NOT_MATCH, metaGeneration, temp);
}
return ImmutableMap.copyOf(temp);
}
private static Map<StorageRpc.Option, ?> optionMap(Option... options) {
return optionMap(null, null, Arrays.asList(options));
}
private static Map<StorageRpc.Option, ?> optionMap(Long generation, Long metaGeneration,
Option... options) {
return optionMap(generation, metaGeneration, Arrays.asList(options));
}
private static Map<StorageRpc.Option, ?> optionMap(BucketInfo bucketInfo, Option... options) {
return optionMap(null, bucketInfo.metageneration(), options);
}
static Map<StorageRpc.Option, ?> optionMap(BlobInfo blobInfo, Option... options) {
return optionMap(blobInfo.generation(), blobInfo.metageneration(), options);
}
static Map<StorageRpc.Option, ?> optionMap(BlobId blobId, Option... options) {
return optionMap(blobId.generation(), null, options);
}
}