-
Notifications
You must be signed in to change notification settings - Fork 68
/
ApiaryConversions.java
981 lines (890 loc) · 41.8 KB
/
ApiaryConversions.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
/*
* Copyright 2022 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.Utils.dateTimeCodec;
import static com.google.cloud.storage.Utils.durationSecondsCodec;
import static com.google.cloud.storage.Utils.ifNonNull;
import static com.google.cloud.storage.Utils.lift;
import static com.google.cloud.storage.Utils.nullableDateTimeCodec;
import static com.google.cloud.storage.Utils.projectNameCodec;
import static com.google.common.base.MoreObjects.firstNonNull;
import com.google.api.client.util.Data;
import com.google.api.client.util.DateTime;
import com.google.api.core.InternalApi;
import com.google.api.services.storage.model.Bucket;
import com.google.api.services.storage.model.Bucket.Billing;
import com.google.api.services.storage.model.Bucket.Encryption;
import com.google.api.services.storage.model.Bucket.IamConfiguration.UniformBucketLevelAccess;
import com.google.api.services.storage.model.Bucket.Lifecycle;
import com.google.api.services.storage.model.Bucket.Lifecycle.Rule;
import com.google.api.services.storage.model.Bucket.Lifecycle.Rule.Action;
import com.google.api.services.storage.model.Bucket.Lifecycle.Rule.Condition;
import com.google.api.services.storage.model.Bucket.RetentionPolicy;
import com.google.api.services.storage.model.Bucket.Versioning;
import com.google.api.services.storage.model.Bucket.Website;
import com.google.api.services.storage.model.BucketAccessControl;
import com.google.api.services.storage.model.ObjectAccessControl;
import com.google.api.services.storage.model.Policy.Bindings;
import com.google.api.services.storage.model.StorageObject;
import com.google.api.services.storage.model.StorageObject.Owner;
import com.google.cloud.Binding;
import com.google.cloud.Policy;
import com.google.cloud.storage.Acl.Domain;
import com.google.cloud.storage.Acl.Entity;
import com.google.cloud.storage.Acl.Group;
import com.google.cloud.storage.Acl.Project;
import com.google.cloud.storage.Acl.RawEntity;
import com.google.cloud.storage.Acl.Role;
import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.BlobInfo.CustomerEncryption;
import com.google.cloud.storage.BucketInfo.Autoclass;
import com.google.cloud.storage.BucketInfo.CustomPlacementConfig;
import com.google.cloud.storage.BucketInfo.IamConfiguration;
import com.google.cloud.storage.BucketInfo.LifecycleRule;
import com.google.cloud.storage.BucketInfo.LifecycleRule.AbortIncompleteMPUAction;
import com.google.cloud.storage.BucketInfo.LifecycleRule.DeleteLifecycleAction;
import com.google.cloud.storage.BucketInfo.LifecycleRule.LifecycleAction;
import com.google.cloud.storage.BucketInfo.LifecycleRule.LifecycleCondition;
import com.google.cloud.storage.BucketInfo.LifecycleRule.SetStorageClassLifecycleAction;
import com.google.cloud.storage.BucketInfo.Logging;
import com.google.cloud.storage.BucketInfo.PublicAccessPrevention;
import com.google.cloud.storage.Conversions.Codec;
import com.google.cloud.storage.Cors.Origin;
import com.google.cloud.storage.HmacKey.HmacKeyMetadata;
import com.google.cloud.storage.HmacKey.HmacKeyState;
import com.google.cloud.storage.NotificationInfo.EventType;
import com.google.cloud.storage.NotificationInfo.PayloadFormat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
@InternalApi
final class ApiaryConversions {
static final ApiaryConversions INSTANCE = new ApiaryConversions();
// gRPC has a Bucket.project property that apiary doesn't have yet.
// when converting from gRPC to apiary or vice-versa we want to preserve this property. Until
// such a time as the apiary model has a project field, we manually apply it with this name.
private static final String PROJECT_ID_FIELD_NAME = "x_project";
// gRPC has a NotificationConfig.name property which contains the bucket the config is associated
// with which that apiary doesn't have yet.
// when converting from gRPC to apiary or vice-versa we want to preserve this property. Until
// such a time as the apiary model has a bucket field, we manually apply it with this name.
private static final String NOTIFICATION_BUCKET_FIELD_NAME = "x_bucket";
private final Codec<Entity, String> entityCodec =
Codec.of(this::entityEncode, this::entityDecode);
private final Codec<Acl, ObjectAccessControl> objectAclCodec =
Codec.of(this::objectAclEncode, this::objectAclDecode);
private final Codec<Acl, BucketAccessControl> bucketAclCodec =
Codec.of(this::bucketAclEncode, this::bucketAclDecode);
private final Codec<HmacKeyMetadata, com.google.api.services.storage.model.HmacKeyMetadata>
hmacKeyMetadataCodec = Codec.of(this::hmacKeyMetadataEncode, this::hmacKeyMetadataDecode);
private final Codec<HmacKey, com.google.api.services.storage.model.HmacKey> hmacKeyCodec =
Codec.of(this::hmacKeyEncode, this::hmacKeyDecode);
private final Codec<ServiceAccount, com.google.api.services.storage.model.ServiceAccount>
serviceAccountCodec = Codec.of(this::serviceAccountEncode, this::serviceAccountDecode);
private final Codec<Cors, Bucket.Cors> corsCodec = Codec.of(this::corsEncode, this::corsDecode);
private final Codec<Logging, Bucket.Logging> loggingCodec =
Codec.of(this::loggingEncode, this::loggingDecode);
private final Codec<IamConfiguration, Bucket.IamConfiguration> iamConfigurationCodec =
Codec.of(this::iamConfigEncode, this::iamConfigDecode);
private final Codec<Autoclass, Bucket.Autoclass> autoclassCodec =
Codec.of(this::autoclassEncode, this::autoclassDecode);
private final Codec<LifecycleRule, Rule> lifecycleRuleCodec =
Codec.of(this::lifecycleRuleEncode, this::lifecycleRuleDecode);
private final Codec<LifecycleCondition, Condition> lifecycleConditionCodec =
Codec.of(this::ruleConditionEncode, this::ruleConditionDecode);
private final Codec<BucketInfo, Bucket> bucketInfoCodec =
Codec.of(this::bucketInfoEncode, this::bucketInfoDecode);
private final Codec<CustomerEncryption, StorageObject.CustomerEncryption>
customerEncryptionCodec =
Codec.of(this::customerEncryptionEncode, this::customerEncryptionDecode);
private final Codec<BlobId, StorageObject> blobIdCodec =
Codec.of(this::blobIdEncode, this::blobIdDecode);
private final Codec<BlobInfo, StorageObject> blobInfoCodec =
Codec.of(this::blobInfoEncode, this::blobInfoDecode);
private final Codec<NotificationInfo, com.google.api.services.storage.model.Notification>
notificationInfoCodec = Codec.of(this::notificationEncode, this::notificationDecode);
private final Codec<CustomPlacementConfig, Bucket.CustomPlacementConfig>
customPlacementConfigCodec =
Codec.of(this::customPlacementConfigEncode, this::customPlacementConfigDecode);
private final Codec<Policy, com.google.api.services.storage.model.Policy> policyCodec =
Codec.of(this::policyEncode, this::policyDecode);
private final Codec<Binding, com.google.api.services.storage.model.Policy.Bindings> bindingCodec =
Codec.of(this::bindingEncode, this::bindingDecode);
private final Codec<com.google.cloud.Condition, com.google.api.services.storage.model.Expr>
iamConditionCodec = Codec.of(this::conditionEncode, this::conditionDecode);
private ApiaryConversions() {}
Codec<Entity, String> entity() {
return entityCodec;
}
Codec<Acl, ObjectAccessControl> objectAcl() {
return objectAclCodec;
}
Codec<Acl, BucketAccessControl> bucketAcl() {
return bucketAclCodec;
}
Codec<HmacKeyMetadata, com.google.api.services.storage.model.HmacKeyMetadata> hmacKeyMetadata() {
return hmacKeyMetadataCodec;
}
Codec<HmacKey, com.google.api.services.storage.model.HmacKey> hmacKey() {
return hmacKeyCodec;
}
Codec<ServiceAccount, com.google.api.services.storage.model.ServiceAccount> serviceAccount() {
return serviceAccountCodec;
}
Codec<Cors, Bucket.Cors> cors() {
return corsCodec;
}
Codec<Logging, Bucket.Logging> logging() {
return loggingCodec;
}
Codec<IamConfiguration, Bucket.IamConfiguration> iamConfiguration() {
return iamConfigurationCodec;
}
Codec<LifecycleRule, Rule> lifecycleRule() {
return lifecycleRuleCodec;
}
Codec<BucketInfo, com.google.api.services.storage.model.Bucket> bucketInfo() {
return bucketInfoCodec;
}
Codec<CustomerEncryption, StorageObject.CustomerEncryption> customerEncryption() {
return customerEncryptionCodec;
}
Codec<BlobId, StorageObject> blobId() {
return blobIdCodec;
}
Codec<BlobInfo, StorageObject> blobInfo() {
return blobInfoCodec;
}
Codec<NotificationInfo, com.google.api.services.storage.model.Notification> notificationInfo() {
return notificationInfoCodec;
}
Codec<LifecycleCondition, Rule.Condition> lifecycleCondition() {
return lifecycleConditionCodec;
}
Codec<CustomPlacementConfig, Bucket.CustomPlacementConfig> customPlacementConfig() {
return customPlacementConfigCodec;
}
Codec<Policy, com.google.api.services.storage.model.Policy> policyCodec() {
return policyCodec;
}
private StorageObject blobInfoEncode(BlobInfo from) {
StorageObject to = blobIdEncode(from.getBlobId());
ifNonNull(from.getAcl(), toListOf(objectAcl()::encode), to::setAcl);
ifNonNull(from.getDeleteTimeOffsetDateTime(), dateTimeCodec::encode, to::setTimeDeleted);
ifNonNull(from.getUpdateTimeOffsetDateTime(), dateTimeCodec::encode, to::setUpdated);
ifNonNull(from.getCreateTimeOffsetDateTime(), dateTimeCodec::encode, to::setTimeCreated);
ifNonNull(from.getCustomTimeOffsetDateTime(), dateTimeCodec::encode, to::setCustomTime);
ifNonNull(from.getSize(), BigInteger::valueOf, to::setSize);
ifNonNull(
from.getOwner(),
lift(this::entityEncode).andThen(o -> new Owner().setEntity(o)),
to::setOwner);
ifNonNull(from.getStorageClass(), StorageClass::toString, to::setStorageClass);
ifNonNull(
from.getTimeStorageClassUpdatedOffsetDateTime(),
dateTimeCodec::encode,
to::setTimeStorageClassUpdated);
ifNonNull(
from.getCustomerEncryption(), this::customerEncryptionEncode, to::setCustomerEncryption);
ifNonNull(
from.getRetentionExpirationTimeOffsetDateTime(),
dateTimeCodec::encode,
to::setRetentionExpirationTime);
to.setKmsKeyName(from.getKmsKeyName());
to.setEventBasedHold(from.getEventBasedHold());
to.setTemporaryHold(from.getTemporaryHold());
// Do not use, #getMetadata(), it can not return null, which is important to our logic here
Map<String, String> pbMetadata = from.metadata;
if (pbMetadata != null && !Data.isNull(pbMetadata)) {
pbMetadata = Maps.newHashMapWithExpectedSize(from.getMetadata().size());
for (Map.Entry<String, String> entry : from.getMetadata().entrySet()) {
pbMetadata.put(entry.getKey(), firstNonNull(entry.getValue(), Data.nullOf(String.class)));
}
}
to.setMetadata(pbMetadata);
to.setCacheControl(from.getCacheControl());
to.setContentEncoding(from.getContentEncoding());
to.setCrc32c(from.getCrc32c());
to.setContentType(from.getContentType());
to.setMd5Hash(from.getMd5());
to.setMediaLink(from.getMediaLink());
to.setMetageneration(from.getMetageneration());
to.setContentDisposition(from.getContentDisposition());
to.setComponentCount(from.getComponentCount());
to.setContentLanguage(from.getContentLanguage());
to.setEtag(from.getEtag());
to.setId(from.getGeneratedId());
to.setSelfLink(from.getSelfLink());
return to;
}
private BlobInfo blobInfoDecode(StorageObject from) {
BlobInfo.Builder to = BlobInfo.newBuilder(blobIdDecode(from));
ifNonNull(from.getCacheControl(), to::setCacheControl);
ifNonNull(from.getContentEncoding(), to::setContentEncoding);
ifNonNull(from.getCrc32c(), to::setCrc32c);
ifNonNull(from.getContentType(), to::setContentType);
ifNonNull(from.getMd5Hash(), to::setMd5);
ifNonNull(from.getMediaLink(), to::setMediaLink);
ifNonNull(from.getMetageneration(), to::setMetageneration);
ifNonNull(from.getContentDisposition(), to::setContentDisposition);
ifNonNull(from.getComponentCount(), to::setComponentCount);
ifNonNull(from.getContentLanguage(), to::setContentLanguage);
ifNonNull(from.getEtag(), to::setEtag);
ifNonNull(from.getId(), to::setGeneratedId);
ifNonNull(from.getSelfLink(), to::setSelfLink);
ifNonNull(from.getMetadata(), to::setMetadata);
ifNonNull(from.getTimeDeleted(), dateTimeCodec::decode, to::setDeleteTimeOffsetDateTime);
ifNonNull(from.getUpdated(), dateTimeCodec::decode, to::setUpdateTimeOffsetDateTime);
ifNonNull(from.getTimeCreated(), dateTimeCodec::decode, to::setCreateTimeOffsetDateTime);
ifNonNull(from.getCustomTime(), dateTimeCodec::decode, to::setCustomTimeOffsetDateTime);
ifNonNull(from.getSize(), BigInteger::longValue, to::setSize);
ifNonNull(from.getOwner(), lift(Owner::getEntity).andThen(this::entityDecode), to::setOwner);
ifNonNull(from.getAcl(), toListOf(objectAcl()::decode), to::setAcl);
if (from.containsKey("isDirectory")) {
to.setIsDirectory(Boolean.TRUE);
}
ifNonNull(
from.getCustomerEncryption(), this::customerEncryptionDecode, to::setCustomerEncryption);
ifNonNull(from.getStorageClass(), StorageClass::valueOf, to::setStorageClass);
ifNonNull(
from.getTimeStorageClassUpdated(),
dateTimeCodec::decode,
to::setTimeStorageClassUpdatedOffsetDateTime);
ifNonNull(from.getKmsKeyName(), to::setKmsKeyName);
ifNonNull(from.getEventBasedHold(), to::setEventBasedHold);
ifNonNull(from.getTemporaryHold(), to::setTemporaryHold);
ifNonNull(
from.getRetentionExpirationTime(),
dateTimeCodec::decode,
to::setRetentionExpirationTimeOffsetDateTime);
return to.build();
}
private StorageObject blobIdEncode(BlobId from) {
StorageObject to = new StorageObject();
to.setBucket(from.getBucket());
to.setName(from.getName());
to.setGeneration(from.getGeneration());
return to;
}
private BlobId blobIdDecode(StorageObject from) {
return BlobId.of(from.getBucket(), from.getName(), from.getGeneration());
}
private StorageObject.CustomerEncryption customerEncryptionEncode(CustomerEncryption from) {
return new StorageObject.CustomerEncryption()
.setEncryptionAlgorithm(from.getEncryptionAlgorithm())
.setKeySha256(from.getKeySha256());
}
private CustomerEncryption customerEncryptionDecode(StorageObject.CustomerEncryption from) {
return new CustomerEncryption(from.getEncryptionAlgorithm(), from.getKeySha256());
}
private Bucket bucketInfoEncode(BucketInfo from) {
Bucket to = new Bucket();
ifNonNull(from.getProject(), projectNameCodec::encode, p -> to.set(PROJECT_ID_FIELD_NAME, p));
ifNonNull(from.getAcl(), toListOf(bucketAcl()::encode), to::setAcl);
ifNonNull(from.getCors(), toListOf(cors()::encode), to::setCors);
ifNonNull(from.getCreateTimeOffsetDateTime(), dateTimeCodec::encode, to::setTimeCreated);
ifNonNull(from.getDefaultAcl(), toListOf(objectAcl()::encode), to::setDefaultObjectAcl);
ifNonNull(from.getLocation(), to::setLocation);
ifNonNull(from.getLocationType(), to::setLocationType);
ifNonNull(from.getMetageneration(), to::setMetageneration);
ifNonNull(
from.getOwner(),
lift(this::entityEncode).andThen(o -> new Bucket.Owner().setEntity(o)),
to::setOwner);
ifNonNull(from.getRpo(), Rpo::toString, to::setRpo);
ifNonNull(from.getStorageClass(), StorageClass::toString, to::setStorageClass);
ifNonNull(from.getUpdateTimeOffsetDateTime(), dateTimeCodec::encode, to::setUpdated);
ifNonNull(from.versioningEnabled(), b -> new Versioning().setEnabled(b), to::setVersioning);
to.setEtag(from.getEtag());
to.setId(from.getGeneratedId());
to.setName(from.getName());
to.setSelfLink(from.getSelfLink());
ifNonNull(from.requesterPays(), b -> new Bucket.Billing().setRequesterPays(b), to::setBilling);
if (from.getIndexPage() != null || from.getNotFoundPage() != null) {
Website website = new Website();
website.setMainPageSuffix(from.getIndexPage());
website.setNotFoundPage(from.getNotFoundPage());
to.setWebsite(website);
}
// Do not use, #getLifecycleRules, it can not return null, which is important to our logic here
List<? extends LifecycleRule> lifecycleRules = from.lifecycleRules;
if (lifecycleRules != null) {
Lifecycle lifecycle = new Lifecycle();
if (lifecycleRules.isEmpty()) {
lifecycle.setRule(Collections.emptyList());
} else {
List<Rule> rules = new ArrayList<>();
ifNonNull(lifecycleRules, r -> r.stream().map(lifecycleRule()::encode).forEach(rules::add));
if (!rules.isEmpty()) {
lifecycle.setRule(ImmutableList.copyOf(rules));
}
}
to.setLifecycle(lifecycle);
}
ifNonNull(from.getDefaultEventBasedHold(), to::setDefaultEventBasedHold);
ifNonNull(
from.getDefaultKmsKeyName(),
k -> new Encryption().setDefaultKmsKeyName(k),
to::setEncryption);
Map<String, String> pbLabels = from.getLabels();
if (pbLabels != null && !Data.isNull(pbLabels)) {
pbLabels = Maps.newHashMapWithExpectedSize(from.getLabels().size());
for (Map.Entry<String, String> entry : from.getLabels().entrySet()) {
pbLabels.put(entry.getKey(), firstNonNull(entry.getValue(), Data.nullOf(String.class)));
}
}
to.setLabels(pbLabels);
maybeEncodeRetentionPolicy(from, to);
ifNonNull(from.getIamConfiguration(), this::iamConfigEncode, to::setIamConfiguration);
ifNonNull(from.getAutoclass(), this::autoclassEncode, to::setAutoclass);
ifNonNull(from.getLogging(), this::loggingEncode, to::setLogging);
ifNonNull(
from.getCustomPlacementConfig(),
this::customPlacementConfigEncode,
to::setCustomPlacementConfig);
return to;
}
@SuppressWarnings("deprecation")
private BucketInfo bucketInfoDecode(com.google.api.services.storage.model.Bucket from) {
BucketInfo.Builder to = new BucketInfo.BuilderImpl(from.getName());
ifNonNull(
from.get(PROJECT_ID_FIELD_NAME),
lift(String.class::cast).andThen(projectNameCodec::decode),
to::setProject);
ifNonNull(from.getAcl(), toListOf(bucketAcl()::decode), to::setAcl);
ifNonNull(from.getCors(), toListOf(cors()::decode), to::setCors);
ifNonNull(from.getDefaultObjectAcl(), toListOf(objectAcl()::decode), to::setDefaultAcl);
ifNonNull(from.getEtag(), to::setEtag);
ifNonNull(from.getId(), to::setGeneratedId);
ifNonNull(from.getLocation(), to::setLocation);
ifNonNull(from.getLocationType(), to::setLocationType);
ifNonNull(from.getMetageneration(), to::setMetageneration);
ifNonNull(
from.getOwner(), lift(Bucket.Owner::getEntity).andThen(this::entityDecode), to::setOwner);
ifNonNull(from.getRpo(), Rpo::valueOf, to::setRpo);
ifNonNull(from.getSelfLink(), to::setSelfLink);
ifNonNull(from.getStorageClass(), StorageClass::valueOf, to::setStorageClass);
ifNonNull(from.getTimeCreated(), dateTimeCodec::decode, to::setCreateTimeOffsetDateTime);
ifNonNull(from.getUpdated(), dateTimeCodec::decode, to::setUpdateTimeOffsetDateTime);
ifNonNull(from.getVersioning(), Versioning::getEnabled, to::setVersioningEnabled);
ifNonNull(from.getWebsite(), Website::getMainPageSuffix, to::setIndexPage);
ifNonNull(from.getWebsite(), Website::getNotFoundPage, to::setNotFoundPage);
ifNonNull(
from.getLifecycle(),
lift(Lifecycle::getRule).andThen(toListOf(lifecycleRule()::decode)),
to::setLifecycleRules);
ifNonNull(from.getDefaultEventBasedHold(), to::setDefaultEventBasedHold);
ifNonNull(from.getLabels(), ApiaryConversions::replaceDataNullValuesWithNull, to::setLabels);
ifNonNull(from.getBilling(), Billing::getRequesterPays, to::setRequesterPays);
Encryption encryption = from.getEncryption();
if (encryption != null
&& encryption.getDefaultKmsKeyName() != null
&& !encryption.getDefaultKmsKeyName().isEmpty()) {
to.setDefaultKmsKeyName(encryption.getDefaultKmsKeyName());
}
maybeDecodeRetentionPolicy(from, to);
ifNonNull(from.getIamConfiguration(), this::iamConfigDecode, to::setIamConfiguration);
ifNonNull(from.getAutoclass(), this::autoclassDecode, to::setAutoclass);
ifNonNull(from.getLogging(), this::loggingDecode, to::setLogging);
ifNonNull(
from.getCustomPlacementConfig(),
this::customPlacementConfigDecode,
to::setCustomPlacementConfig);
return to.build();
}
private Bucket.IamConfiguration iamConfigEncode(IamConfiguration from) {
Bucket.IamConfiguration to = new Bucket.IamConfiguration();
to.setUniformBucketLevelAccess(ublaEncode(from));
ifNonNull(
from.getPublicAccessPrevention(),
PublicAccessPrevention::getValue,
to::setPublicAccessPrevention);
return to;
}
private IamConfiguration iamConfigDecode(Bucket.IamConfiguration from) {
Bucket.IamConfiguration.UniformBucketLevelAccess ubla = from.getUniformBucketLevelAccess();
IamConfiguration.Builder to =
IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(ubla.getEnabled());
ifNonNull(
ubla.getLockedTime(),
dateTimeCodec::decode,
to::setUniformBucketLevelAccessLockedTimeOffsetDateTime);
ifNonNull(
from.getPublicAccessPrevention(),
PublicAccessPrevention::parse,
to::setPublicAccessPrevention);
return to.build();
}
private Bucket.Autoclass autoclassEncode(Autoclass from) {
Bucket.Autoclass to = new Bucket.Autoclass();
ifNonNull(from.getEnabled(), to::setEnabled);
ifNonNull(from.getToggleTime(), dateTimeCodec::encode, to::setToggleTime);
ifNonNull(from.getTerminalStorageClass(), StorageClass::toString, to::setTerminalStorageClass);
ifNonNull(
from.getTerminalStorageClassUpdateTime(),
dateTimeCodec::encode,
to::setTerminalStorageClassUpdateTime);
return to;
}
private Autoclass autoclassDecode(Bucket.Autoclass from) {
Autoclass.Builder to = Autoclass.newBuilder();
to.setEnabled(from.getEnabled());
ifNonNull(from.getToggleTime(), dateTimeCodec::decode, to::setToggleTime);
ifNonNull(from.getTerminalStorageClass(), StorageClass::valueOf, to::setTerminalStorageClass);
ifNonNull(
from.getTerminalStorageClassUpdateTime(),
dateTimeCodec::decode,
to::setTerminalStorageClassUpdateTime);
return to.build();
}
private UniformBucketLevelAccess ublaEncode(IamConfiguration from) {
UniformBucketLevelAccess to = new UniformBucketLevelAccess();
to.setEnabled(from.isUniformBucketLevelAccessEnabled());
ifNonNull(
from.getUniformBucketLevelAccessLockedTimeOffsetDateTime(),
dateTimeCodec::encode,
to::setLockedTime);
return to;
}
private Rule lifecycleRuleEncode(LifecycleRule from) {
Rule to = new Rule();
to.setAction(ruleActionEncode(from.getAction()));
to.setCondition(ruleConditionEncode(from.getCondition()));
return to;
}
private Condition ruleConditionEncode(LifecycleCondition from) {
Function<OffsetDateTime, DateTime> truncatingDateFunction =
lift(dateTimeCodec::encode)
// truncate the date time to the date, and strip any tz drift
.andThen(dt -> new DateTime(true, dt.getValue(), 0));
Condition to =
new Condition()
.setAge(from.getAge())
.setIsLive(from.getIsLive())
.setNumNewerVersions(from.getNumberOfNewerVersions())
.setDaysSinceNoncurrentTime(from.getDaysSinceNoncurrentTime())
.setDaysSinceCustomTime(from.getDaysSinceCustomTime());
ifNonNull(from.getCreatedBeforeOffsetDateTime(), truncatingDateFunction, to::setCreatedBefore);
ifNonNull(
from.getNoncurrentTimeBeforeOffsetDateTime(),
truncatingDateFunction,
to::setNoncurrentTimeBefore);
ifNonNull(
from.getCustomTimeBeforeOffsetDateTime(), truncatingDateFunction, to::setCustomTimeBefore);
ifNonNull(
from.getMatchesStorageClass(), toListOf(Object::toString), to::setMatchesStorageClass);
ifNonNull(from.getMatchesPrefix(), to::setMatchesPrefix);
ifNonNull(from.getMatchesSuffix(), to::setMatchesSuffix);
return to;
}
private LifecycleCondition ruleConditionDecode(Condition condition) {
if (condition == null) {
return LifecycleCondition.newBuilder().build();
}
LifecycleCondition.Builder conditionBuilder =
LifecycleCondition.newBuilder()
.setAge(condition.getAge())
.setCreatedBeforeOffsetDateTime(
nullableDateTimeCodec.decode(condition.getCreatedBefore()))
.setIsLive(condition.getIsLive())
.setNumberOfNewerVersions(condition.getNumNewerVersions())
.setDaysSinceNoncurrentTime(condition.getDaysSinceNoncurrentTime())
.setNoncurrentTimeBeforeOffsetDateTime(
nullableDateTimeCodec.decode(condition.getNoncurrentTimeBefore()))
.setCustomTimeBeforeOffsetDateTime(
nullableDateTimeCodec.decode(condition.getCustomTimeBefore()))
.setDaysSinceCustomTime(condition.getDaysSinceCustomTime());
ifNonNull(
condition.getMatchesStorageClass(),
toListOf(StorageClass::valueOf),
conditionBuilder::setMatchesStorageClass);
ifNonNull(condition.getMatchesPrefix(), conditionBuilder::setMatchesPrefix);
ifNonNull(condition.getMatchesSuffix(), conditionBuilder::setMatchesSuffix);
return conditionBuilder.build();
}
private Action ruleActionEncode(LifecycleAction from) {
Action to = new Action().setType(from.getActionType());
if (from.getActionType().equals(SetStorageClassLifecycleAction.TYPE)) {
to.setStorageClass(((SetStorageClassLifecycleAction) from).getStorageClass().toString());
}
return to;
}
private LifecycleRule lifecycleRuleDecode(Rule from) {
LifecycleAction lifecycleAction;
Rule.Action action = from.getAction();
switch (action.getType()) {
case DeleteLifecycleAction.TYPE:
lifecycleAction = LifecycleAction.newDeleteAction();
break;
case SetStorageClassLifecycleAction.TYPE:
lifecycleAction =
LifecycleAction.newSetStorageClassAction(
StorageClass.valueOf(action.getStorageClass()));
break;
case AbortIncompleteMPUAction.TYPE:
lifecycleAction = LifecycleAction.newAbortIncompleteMPUploadAction();
break;
default:
BucketInfo.log.warning(
"The lifecycle action "
+ action.getType()
+ " is not supported by this version of the library. "
+ "Attempting to update with this rule may cause errors. Please "
+ "update to the latest version of google-cloud-storage.");
lifecycleAction = LifecycleAction.newLifecycleAction("Unknown action");
}
LifecycleCondition lifecycleCondition = ruleConditionDecode(from.getCondition());
return new LifecycleRule(lifecycleAction, lifecycleCondition);
}
private Bucket.Logging loggingEncode(Logging from) {
Bucket.Logging to;
if (from.getLogBucket() != null || from.getLogObjectPrefix() != null) {
to = new Bucket.Logging();
ifNonNull(from.getLogBucket(), to::setLogBucket);
ifNonNull(from.getLogObjectPrefix(), to::setLogObjectPrefix);
} else {
to = Data.nullOf(Bucket.Logging.class);
}
return to;
}
private Logging loggingDecode(Bucket.Logging from) {
return Logging.newBuilder()
.setLogBucket(from.getLogBucket())
.setLogObjectPrefix(from.getLogObjectPrefix())
.build();
}
private Bucket.Cors corsEncode(Cors from) {
Bucket.Cors to = new Bucket.Cors();
to.setMaxAgeSeconds(from.getMaxAgeSeconds());
to.setResponseHeader(from.getResponseHeaders());
ifNonNull(from.getMethods(), toListOf(Object::toString), to::setMethod);
ifNonNull(from.getOrigins(), toListOf(Object::toString), to::setOrigin);
return to;
}
private Cors corsDecode(Bucket.Cors from) {
Cors.Builder to = Cors.newBuilder().setMaxAgeSeconds(from.getMaxAgeSeconds());
ifNonNull(
from.getMethod(),
m ->
m.stream()
.map(String::toUpperCase)
.map(HttpMethod::valueOf)
.collect(ImmutableList.toImmutableList()),
to::setMethods);
ifNonNull(from.getOrigin(), toListOf(Origin::of), to::setOrigins);
to.setResponseHeaders(from.getResponseHeader());
return to.build();
}
private com.google.api.services.storage.model.ServiceAccount serviceAccountEncode(
ServiceAccount from) {
return new com.google.api.services.storage.model.ServiceAccount()
.setEmailAddress(from.getEmail());
}
private ServiceAccount serviceAccountDecode(
com.google.api.services.storage.model.ServiceAccount from) {
return ServiceAccount.of(from.getEmailAddress());
}
private com.google.api.services.storage.model.HmacKey hmacKeyEncode(HmacKey from) {
com.google.api.services.storage.model.HmacKey to =
new com.google.api.services.storage.model.HmacKey();
to.setSecret(from.getSecretKey());
ifNonNull(from.getMetadata(), this::hmacKeyMetadataEncode, to::setMetadata);
return to;
}
private HmacKey hmacKeyDecode(com.google.api.services.storage.model.HmacKey from) {
return HmacKey.newBuilder(from.getSecret())
.setMetadata(hmacKeyMetadataDecode(from.getMetadata()))
.build();
}
private com.google.api.services.storage.model.HmacKeyMetadata hmacKeyMetadataEncode(
HmacKeyMetadata from) {
com.google.api.services.storage.model.HmacKeyMetadata to =
new com.google.api.services.storage.model.HmacKeyMetadata();
to.setAccessId(from.getAccessId());
to.setEtag(from.getEtag());
to.setId(from.getId());
to.setProjectId(from.getProjectId());
ifNonNull(from.getServiceAccount(), ServiceAccount::getEmail, to::setServiceAccountEmail);
ifNonNull(from.getState(), Enum::name, to::setState);
ifNonNull(from.getCreateTimeOffsetDateTime(), dateTimeCodec::encode, to::setTimeCreated);
ifNonNull(from.getUpdateTimeOffsetDateTime(), dateTimeCodec::encode, to::setUpdated);
return to;
}
private HmacKeyMetadata hmacKeyMetadataDecode(
com.google.api.services.storage.model.HmacKeyMetadata from) {
return HmacKeyMetadata.newBuilder(ServiceAccount.of(from.getServiceAccountEmail()))
.setAccessId(from.getAccessId())
.setCreateTimeOffsetDateTime(dateTimeCodec.decode(from.getTimeCreated()))
.setEtag(from.getEtag())
.setId(from.getId())
.setProjectId(from.getProjectId())
.setState(HmacKeyState.valueOf(from.getState()))
.setUpdateTimeOffsetDateTime(dateTimeCodec.decode(from.getUpdated()))
.build();
}
private String entityEncode(Entity from) {
if (from instanceof RawEntity) {
return from.getValue();
} else if (from instanceof User) {
switch (from.getValue()) {
case User.ALL_AUTHENTICATED_USERS:
return User.ALL_AUTHENTICATED_USERS;
case User.ALL_USERS:
return User.ALL_USERS;
default:
break;
}
}
// intentionally not an else so that if the default is hit above it will fall through to here
return from.getType().name().toLowerCase() + "-" + from.getValue();
}
private Entity entityDecode(String from) {
if (from.startsWith("user-")) {
return new User(from.substring(5));
}
if (from.equals(User.ALL_USERS)) {
return User.ofAllUsers();
}
if (from.equals(User.ALL_AUTHENTICATED_USERS)) {
return User.ofAllAuthenticatedUsers();
}
if (from.startsWith("group-")) {
return new Group(from.substring(6));
}
if (from.startsWith("domain-")) {
return new Domain(from.substring(7));
}
if (from.startsWith("project-")) {
int idx = from.indexOf('-', 8);
String team = from.substring(8, idx);
String projectId = from.substring(idx + 1);
return new Project(Project.ProjectRole.valueOf(team.toUpperCase()), projectId);
}
return new RawEntity(from);
}
private Acl objectAclDecode(ObjectAccessControl from) {
Role role = Role.valueOf(from.getRole());
Entity entity = entityDecode(from.getEntity());
return Acl.newBuilder(entity, role).setEtag(from.getEtag()).setId(from.getId()).build();
}
private Acl bucketAclDecode(BucketAccessControl from) {
Role role = Role.valueOf(from.getRole());
Entity entity = entityDecode(from.getEntity());
return Acl.newBuilder(entity, role).setEtag(from.getEtag()).setId(from.getId()).build();
}
private BucketAccessControl bucketAclEncode(Acl from) {
return new BucketAccessControl()
.setEntity(from.getEntity().toString())
.setRole(from.getRole().toString())
.setId(from.getId())
.setEtag(from.getEtag());
}
private ObjectAccessControl objectAclEncode(Acl from) {
return new ObjectAccessControl()
.setEntity(entityEncode(from.getEntity()))
.setRole(from.getRole().name())
.setId(from.getId())
.setEtag(from.getEtag());
}
private com.google.api.services.storage.model.Notification notificationEncode(
NotificationInfo from) {
com.google.api.services.storage.model.Notification to =
new com.google.api.services.storage.model.Notification();
to.setEtag(from.getEtag());
to.setSelfLink(from.getSelfLink());
to.setTopic(from.getTopic());
ifNonNull(from.getBucket(), b -> to.set(NOTIFICATION_BUCKET_FIELD_NAME, b));
ifNonNull(from.getNotificationId(), to::setId);
ifNonNull(from.getCustomAttributes(), to::setCustomAttributes);
ifNonNull(from.getObjectNamePrefix(), to::setObjectNamePrefix);
List<EventType> eventTypes = from.getEventTypes();
if (eventTypes != null && eventTypes.size() > 0) {
List<String> eventTypesPb = new ArrayList<>();
for (EventType eventType : eventTypes) {
eventTypesPb.add(eventType.toString());
}
to.setEventTypes(eventTypesPb);
}
PayloadFormat payloadFormat = from.getPayloadFormat();
if (payloadFormat != null) {
to.setPayloadFormat(payloadFormat.toString());
} else {
to.setPayloadFormat(PayloadFormat.NONE.toString());
}
return to;
}
private NotificationInfo notificationDecode(
com.google.api.services.storage.model.Notification from) {
NotificationInfo.Builder builder = new NotificationInfo.BuilderImpl(from.getTopic());
ifNonNull(from.get(NOTIFICATION_BUCKET_FIELD_NAME), String.class::cast, builder::setBucket);
ifNonNull(from.getId(), builder::setNotificationId);
ifNonNull(from.getEtag(), builder::setEtag);
ifNonNull(from.getCustomAttributes(), builder::setCustomAttributes);
ifNonNull(from.getSelfLink(), builder::setSelfLink);
ifNonNull(from.getObjectNamePrefix(), builder::setObjectNamePrefix);
ifNonNull(from.getPayloadFormat(), PayloadFormat::valueOf, builder::setPayloadFormat);
if (from.getEventTypes() != null) {
List<String> eventTypesPb = from.getEventTypes();
EventType[] eventTypes = new EventType[eventTypesPb.size()];
for (int index = 0; index < eventTypesPb.size(); index++) {
eventTypes[index] = EventType.valueOf(eventTypesPb.get(index));
}
builder.setEventTypes(eventTypes);
}
return builder.build();
}
private com.google.api.services.storage.model.Policy policyEncode(Policy from) {
com.google.api.services.storage.model.Policy to =
new com.google.api.services.storage.model.Policy();
ifNonNull(from.getEtag(), to::setEtag);
ifNonNull(from.getVersion(), to::setVersion);
if (from.getBindingsList() != null) {
ImmutableList<com.google.api.services.storage.model.Policy.Bindings> bindings =
from.getBindingsList().stream()
.map(bindingCodec::encode)
.collect(ImmutableList.toImmutableList());
to.setBindings(bindings);
}
return to;
}
private Policy policyDecode(com.google.api.services.storage.model.Policy from) {
Policy.Builder to = Policy.newBuilder();
String etag = from.getEtag();
if (etag != null && !etag.isEmpty()) {
to.setEtag(etag);
}
to.setVersion(from.getVersion());
List<Bindings> bindings = from.getBindings();
if (bindings != null && !bindings.isEmpty()) {
to.setBindings(
bindings.stream().map(bindingCodec::decode).collect(ImmutableList.toImmutableList()));
}
return to.build();
}
private com.google.api.services.storage.model.Policy.Bindings bindingEncode(Binding from) {
com.google.api.services.storage.model.Policy.Bindings to =
new com.google.api.services.storage.model.Policy.Bindings();
ifNonNull(from.getRole(), to::setRole);
ifNonNull(from.getMembers(), to::setMembers);
ifNonNull(from.getCondition(), iamConditionCodec::encode, to::setCondition);
return to;
}
private Binding bindingDecode(com.google.api.services.storage.model.Policy.Bindings from) {
Binding.Builder to = Binding.newBuilder();
ifNonNull(from.getRole(), to::setRole);
ifNonNull(from.getMembers(), to::setMembers);
ifNonNull(from.getCondition(), iamConditionCodec::decode, to::setCondition);
return to.build();
}
private com.google.api.services.storage.model.Expr conditionEncode(
com.google.cloud.Condition from) {
com.google.api.services.storage.model.Expr to =
new com.google.api.services.storage.model.Expr();
ifNonNull(from.getExpression(), to::setExpression);
ifNonNull(from.getTitle(), to::setTitle);
ifNonNull(from.getDescription(), to::setDescription);
// apiary doesn't have a "location" field like grpc does
return to;
}
private com.google.cloud.Condition conditionDecode(
com.google.api.services.storage.model.Expr from) {
com.google.cloud.Condition.Builder to = com.google.cloud.Condition.newBuilder();
ifNonNull(from.getExpression(), to::setExpression);
ifNonNull(from.getTitle(), to::setTitle);
ifNonNull(from.getDescription(), to::setDescription);
return to.build();
}
private Bucket.CustomPlacementConfig customPlacementConfigEncode(CustomPlacementConfig from) {
Bucket.CustomPlacementConfig to = null;
if (from.getDataLocations() != null) {
to = new Bucket.CustomPlacementConfig();
to.setDataLocations(from.getDataLocations());
}
return to;
}
private CustomPlacementConfig customPlacementConfigDecode(Bucket.CustomPlacementConfig from) {
return CustomPlacementConfig.newBuilder().setDataLocations(from.getDataLocations()).build();
}
private static void maybeEncodeRetentionPolicy(BucketInfo from, Bucket to) {
if (from.getRetentionPeriodDuration() != null
|| from.retentionPolicyIsLocked() != null
|| from.getRetentionEffectiveTimeOffsetDateTime() != null) {
RetentionPolicy retentionPolicy = new RetentionPolicy();
ifNonNull(
from.getRetentionPeriodDuration(),
durationSecondsCodec::encode,
retentionPolicy::setRetentionPeriod);
ifNonNull(from.retentionPolicyIsLocked(), retentionPolicy::setIsLocked);
ifNonNull(
from.getRetentionEffectiveTimeOffsetDateTime(),
dateTimeCodec::encode,
retentionPolicy::setEffectiveTime);
to.setRetentionPolicy(retentionPolicy);
} else {
to.setRetentionPolicy(Data.nullOf(Bucket.RetentionPolicy.class));
}
}
private static void maybeDecodeRetentionPolicy(Bucket from, BucketInfo.Builder to) {
RetentionPolicy retentionPolicy = from.getRetentionPolicy();
if (retentionPolicy != null && retentionPolicy.getEffectiveTime() != null) {
to.setRetentionEffectiveTimeOffsetDateTime(
dateTimeCodec.decode(retentionPolicy.getEffectiveTime()));
}
if (retentionPolicy != null) {
ifNonNull(retentionPolicy.getIsLocked(), to::setRetentionPolicyIsLocked);
ifNonNull(
retentionPolicy.getRetentionPeriod(),
durationSecondsCodec::decode,
to::setRetentionPeriodDuration);
}
}
private static Map<String, String> replaceDataNullValuesWithNull(Map<String, String> labels) {
boolean anyDataNull = labels.values().stream().anyMatch(Data::isNull);
if (anyDataNull) {
// If we received any Data null values, replace them with null before setting.
// Explicitly use a HashMap as it allows null values.
Map<String, String> tmp = Maps.newHashMapWithExpectedSize(labels.size());
for (Entry<String, String> e : labels.entrySet()) {
String k = e.getKey();
String v = e.getValue();
tmp.put(k, Data.isNull(v) ? null : v);
}
return Collections.unmodifiableMap(tmp);
} else {
return labels;
}
}
/**
* Several properties are translating lists of one type to another. This convenience method allows
* specifying a mapping function and composing as part of an {@code #isNonNull} definition.
*
* <p>Apiary specific utility method to convert from one list to another for specific Function
*/
private static <T1, T2> Function<List<T1>, List<T2>> toListOf(Function<T1, T2> f) {
// various data level methods in the apiary model are hostile to ImmutableList, as it does not
// provide a public default no args constructor. Instead, apiary uses ArrayList for all internal
// representations of JSON Arrays.
return l -> l.stream().map(f).collect(Collectors.toList());
}
}