forked from minio/minio-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FunctionalTest.java
4087 lines (3653 loc) · 144 KB
/
FunctionalTest.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
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2015-2020 MinIO, Inc.
*
* 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.
*/
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import com.google.common.io.BaseEncoding;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.minio.BucketExistsArgs;
import io.minio.CloseableIterator;
import io.minio.ComposeObjectArgs;
import io.minio.ComposeSource;
import io.minio.CopyObjectArgs;
import io.minio.CopySource;
import io.minio.DeleteBucketEncryptionArgs;
import io.minio.DeleteBucketLifeCycleArgs;
import io.minio.DeleteBucketNotificationArgs;
import io.minio.DeleteBucketPolicyArgs;
import io.minio.DeleteBucketTagsArgs;
import io.minio.DeleteDefaultRetentionArgs;
import io.minio.DeleteObjectTagsArgs;
import io.minio.Directive;
import io.minio.DisableObjectLegalHoldArgs;
import io.minio.DisableVersioningArgs;
import io.minio.DownloadObjectArgs;
import io.minio.EnableObjectLegalHoldArgs;
import io.minio.EnableVersioningArgs;
import io.minio.ErrorCode;
import io.minio.GetBucketEncryptionArgs;
import io.minio.GetBucketLifeCycleArgs;
import io.minio.GetBucketNotificationArgs;
import io.minio.GetBucketPolicyArgs;
import io.minio.GetBucketTagsArgs;
import io.minio.GetDefaultRetentionArgs;
import io.minio.GetObjectArgs;
import io.minio.GetObjectRetentionArgs;
import io.minio.GetObjectTagsArgs;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.IsObjectLegalHoldEnabledArgs;
import io.minio.IsVersioningEnabledArgs;
import io.minio.ListIncompleteUploadsArgs;
import io.minio.ListObjectsArgs;
import io.minio.ListenBucketNotificationArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.ObjectWriteResponse;
import io.minio.PostPolicy;
import io.minio.PutObjectArgs;
import io.minio.RemoveBucketArgs;
import io.minio.RemoveIncompleteUploadArgs;
import io.minio.RemoveObjectArgs;
import io.minio.RemoveObjectsArgs;
import io.minio.Result;
import io.minio.SelectObjectContentArgs;
import io.minio.SelectResponseStream;
import io.minio.ServerSideEncryption;
import io.minio.ServerSideEncryptionCustomerKey;
import io.minio.SetBucketEncryptionArgs;
import io.minio.SetBucketLifeCycleArgs;
import io.minio.SetBucketNotificationArgs;
import io.minio.SetBucketPolicyArgs;
import io.minio.SetBucketTagsArgs;
import io.minio.SetDefaultRetentionArgs;
import io.minio.SetObjectRetentionArgs;
import io.minio.SetObjectTagsArgs;
import io.minio.StatObjectArgs;
import io.minio.Time;
import io.minio.UploadObjectArgs;
import io.minio.Xml;
import io.minio.errors.ErrorResponseException;
import io.minio.errors.InsufficientDataException;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteObject;
import io.minio.messages.ErrorResponse;
import io.minio.messages.Event;
import io.minio.messages.EventType;
import io.minio.messages.FileHeaderInfo;
import io.minio.messages.InputSerialization;
import io.minio.messages.NotificationConfiguration;
import io.minio.messages.NotificationRecords;
import io.minio.messages.ObjectLockConfiguration;
import io.minio.messages.OutputSerialization;
import io.minio.messages.QueueConfiguration;
import io.minio.messages.QuoteFields;
import io.minio.messages.Retention;
import io.minio.messages.RetentionDuration;
import io.minio.messages.RetentionDurationDays;
import io.minio.messages.RetentionDurationYears;
import io.minio.messages.RetentionMode;
import io.minio.messages.SseAlgorithm;
import io.minio.messages.SseConfiguration;
import io.minio.messages.SseConfigurationRule;
import io.minio.messages.Stats;
import io.minio.messages.Tags;
import io.minio.messages.Upload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import okhttp3.HttpUrl;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;
@SuppressFBWarnings(
value = "REC",
justification = "Allow catching super class Exception since it's tests")
public class FunctionalTest {
private static final String OS = System.getProperty("os.name").toLowerCase(Locale.US);
private static final String MINIO_BINARY;
private static final String PASS = "PASS";
private static final String FAILED = "FAIL";
private static final String IGNORED = "NA";
private static final int KB = 1024;
private static final int MB = 1024 * 1024;
private static final Random random = new Random(new SecureRandom().nextLong());
private static final String customContentType = "application/javascript";
private static final String nullContentType = null;
private static String bucketName = getRandomName();
private static boolean mintEnv = false;
private static boolean isQuickTest = false;
private static Path dataFile1Kb;
private static Path dataFile6Mb;
private static String endpoint;
private static String accessKey;
private static String secretKey;
private static String region;
private static boolean isSecureEndpoint = false;
private static String sqsArn = null;
private static MinioClient client = null;
private static ServerSideEncryptionCustomerKey ssec = null;
private static ServerSideEncryption sseS3 = ServerSideEncryption.atRest();
private static ServerSideEncryption sseKms = null;
static {
String binaryName = "minio";
if (OS.contains("windows")) {
binaryName = "minio.exe";
}
MINIO_BINARY = binaryName;
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
ssec = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/** Do no-op. */
public static void ignore(Object... args) {}
/** Create given sized file and returns its name. */
public static String createFile(int size) throws IOException {
String filename = getRandomName();
try (OutputStream os = Files.newOutputStream(Paths.get(filename), CREATE, APPEND)) {
int totalBytesWritten = 0;
int bytesToWrite = 0;
byte[] buf = new byte[1 * MB];
while (totalBytesWritten < size) {
random.nextBytes(buf);
bytesToWrite = size - totalBytesWritten;
if (bytesToWrite > buf.length) {
bytesToWrite = buf.length;
}
os.write(buf, 0, bytesToWrite);
totalBytesWritten += bytesToWrite;
}
}
return filename;
}
/** Create 1 KB temporary file. */
public static String createFile1Kb() throws IOException {
if (mintEnv) {
String filename = getRandomName();
Files.createSymbolicLink(Paths.get(filename).toAbsolutePath(), dataFile1Kb);
return filename;
}
return createFile(1 * KB);
}
/** Create 6 MB temporary file. */
public static String createFile6Mb() throws IOException {
if (mintEnv) {
String filename = getRandomName();
Files.createSymbolicLink(Paths.get(filename).toAbsolutePath(), dataFile6Mb);
return filename;
}
return createFile(6 * MB);
}
/** Generate random name. */
public static String getRandomName() {
return "minio-java-test-" + new BigInteger(32, random).toString(32);
}
/** Returns byte array contains all data in given InputStream. */
public static byte[] readAllBytes(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
}
/** Prints a success log entry in JSON format. */
public static void mintSuccessLog(String function, String args, long startTime) {
if (mintEnv) {
System.out.println(
new MintLogger(
function, args, System.currentTimeMillis() - startTime, PASS, null, null, null));
}
}
/** Prints a failure log entry in JSON format. */
public static void mintFailedLog(
String function, String args, long startTime, String message, String error) {
if (mintEnv) {
System.out.println(
new MintLogger(
function,
args,
System.currentTimeMillis() - startTime,
FAILED,
null,
message,
error));
}
}
/** Prints a ignore log entry in JSON format. */
public static void mintIgnoredLog(String function, String args, long startTime) {
if (mintEnv) {
System.out.println(
new MintLogger(
function, args, System.currentTimeMillis() - startTime, IGNORED, null, null, null));
}
}
/** Read object content of the given url. */
public static byte[] readObject(String urlString) throws Exception {
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.url(HttpUrl.parse(urlString)).method("GET", null).build();
OkHttpClient transport =
new OkHttpClient()
.newBuilder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
Response response = transport.newCall(request).execute();
try {
if (response.isSuccessful()) {
return response.body().bytes();
}
String errorXml = new String(response.body().bytes(), StandardCharsets.UTF_8);
throw new Exception(
"failed to create object. Response: " + response + ", Response body: " + errorXml);
} finally {
response.close();
}
}
/** Write data to given object url. */
public static void writeObject(String urlString, byte[] dataBytes) throws Exception {
Request.Builder requestBuilder = new Request.Builder();
// Set header 'x-amz-acl' to 'bucket-owner-full-control', so objects created
// anonymously, can be downloaded by bucket owner in AWS S3.
Request request =
requestBuilder
.url(HttpUrl.parse(urlString))
.method("PUT", RequestBody.create(null, dataBytes))
.addHeader("x-amz-acl", "bucket-owner-full-control")
.build();
OkHttpClient transport =
new OkHttpClient()
.newBuilder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
Response response = transport.newCall(request).execute();
try {
if (!response.isSuccessful()) {
String errorXml = new String(response.body().bytes(), StandardCharsets.UTF_8);
throw new Exception(
"failed to create object. Response: " + response + ", Response body: " + errorXml);
}
} finally {
response.close();
}
}
public static String getSha256Sum(InputStream stream, int len) throws Exception {
MessageDigest sha256Digest = MessageDigest.getInstance("SHA-256");
// 16KiB buffer for optimization
byte[] buf = new byte[16384];
int bytesToRead = buf.length;
int bytesRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < len) {
if ((len - totalBytesRead) < bytesToRead) {
bytesToRead = len - totalBytesRead;
}
bytesRead = stream.read(buf, 0, bytesToRead);
if (bytesRead < 0) {
// reached EOF
throw new Exception("data length mismatch. expected: " + len + ", got: " + totalBytesRead);
}
if (bytesRead > 0) {
sha256Digest.update(buf, 0, bytesRead);
totalBytesRead += bytesRead;
}
}
return BaseEncoding.base16().encode(sha256Digest.digest()).toLowerCase(Locale.US);
}
public static void skipStream(InputStream stream, int len) throws Exception {
// 16KiB buffer for optimization
byte[] buf = new byte[16384];
int bytesToRead = buf.length;
int bytesRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < len) {
if ((len - totalBytesRead) < bytesToRead) {
bytesToRead = len - totalBytesRead;
}
bytesRead = stream.read(buf, 0, bytesToRead);
if (bytesRead < 0) {
// reached EOF
throw new Exception("insufficient data. expected: " + len + ", got: " + totalBytesRead);
}
if (bytesRead > 0) {
totalBytesRead += bytesRead;
}
}
}
private static void handleException(String methodName, String args, long startTime, Exception e)
throws Exception {
if (e instanceof ErrorResponseException) {
if (((ErrorResponseException) e).errorResponse().errorCode() == ErrorCode.NOT_IMPLEMENTED) {
mintIgnoredLog(methodName, args, startTime);
return;
}
}
if (mintEnv) {
mintFailedLog(
methodName,
args,
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
} else {
System.out.println("<FAILED> " + methodName + " " + ((args == null) ? "" : args));
}
throw e;
}
/** Test: makeBucket(MakeBucketArgs args). */
public static void makeBucket_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: makeBucket(MakeBucketArgs args)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(MakeBucketArgs.builder().bucket(name).build());
client.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
mintSuccessLog("makeBucket(MakeBucketArgs args)", null, startTime);
} catch (Exception e) {
mintFailedLog(
"makeBucket(MakeBucketArgs args)",
null,
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/** Test: makeBucket(MakeBucketArgs args). */
public static void makeBucket_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: with region and object lock : makeBucket(MakeBucketArgs args)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(
MakeBucketArgs.builder().bucket(name).region("eu-west-1").objectLock(true).build());
client.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
mintSuccessLog(
"makeBucket(MakeBucketArgs args)", "region: eu-west-1, objectLock: true", startTime);
} catch (Exception e) {
ErrorResponse errorResponse = null;
if (e instanceof ErrorResponseException) {
ErrorResponseException exp = (ErrorResponseException) e;
errorResponse = exp.errorResponse();
}
// Ignore NotImplemented error
if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) {
mintIgnoredLog(
"makeBucket(MakeBucketArgs args)", "region: eu-west-1, objectLock: true", startTime);
} else {
mintFailedLog(
"makeBucket(MakeBucketArgs args)",
"region: eu-west-1, objectLock: true",
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
}
/** Test: makeBucket(MakeBucketArgs args). */
public static void makeBucket_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: with region: makeBucket(MakeBucketArgs args)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(MakeBucketArgs.builder().bucket(name).region("eu-west-1").build());
client.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
mintSuccessLog("makeBucket(MakeBucketArgs args) ", "region: eu-west-1", startTime);
} catch (Exception e) {
mintFailedLog(
"makeBucket(MakeBucketArgs args) ",
"region: eu-west-1",
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/** Test: makeBucket(MakeBucketArgs args) where bucketName has periods in its name. */
public static void makeBucket_test4() throws Exception {
if (!mintEnv) {
System.out.println(
"Test: with bucket name having periods in its name: makeBucket(MakeBucketArgs args)");
}
long startTime = System.currentTimeMillis();
String name = getRandomName() + ".withperiod";
try {
client.makeBucket(MakeBucketArgs.builder().bucket(name).region("eu-central-1").build());
client.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
mintSuccessLog(
"makeBucket(MakeBucketArgs args) bucketname having periods in its name",
"name: " + name + ", region: eu-central-1",
startTime);
} catch (Exception e) {
mintFailedLog(
"makeBucket(MakeBucketArgs args) bucketname having periods in its name",
"name: " + name + ", region: eu-central-1",
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/** Test: enableVersioning(EnableVersioningArgs args). */
public static void enableVersioning_test() throws Exception {
String methodName = "enableVersioning(EnableVersioningArgs args)";
if (!mintEnv) {
System.out.println("Test: " + methodName);
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(MakeBucketArgs.builder().bucket(name).build());
client.enableVersioning(EnableVersioningArgs.builder().bucket(name).build());
if (!client.isVersioningEnabled(IsVersioningEnabledArgs.builder().bucket(name).build())) {
throw new Exception("[FAILED] isVersioningEnabled(): expected: true, got: false");
}
client.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
mintSuccessLog(methodName, null, startTime);
} catch (Exception e) {
handleException(methodName, null, startTime, e);
}
}
/** Test: disableVersioning(DisableVersioningArgs args). */
public static void disableVersioning_test() throws Exception {
String methodName = "disableVersioning(DisableVersioningArgs args)";
if (!mintEnv) {
System.out.println("Test: " + methodName);
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(MakeBucketArgs.builder().bucket(name).build());
client.disableVersioning(DisableVersioningArgs.builder().bucket(name).build());
if (client.isVersioningEnabled(IsVersioningEnabledArgs.builder().bucket(name).build())) {
throw new Exception("[FAILED] isVersioningEnabled(): expected: false, got: true");
}
client.enableVersioning(EnableVersioningArgs.builder().bucket(name).build());
client.disableVersioning(DisableVersioningArgs.builder().bucket(name).build());
if (client.isVersioningEnabled(IsVersioningEnabledArgs.builder().bucket(name).build())) {
throw new Exception("[FAILED] isVersioningEnabled(): expected: false, got: true");
}
client.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
mintSuccessLog(methodName, null, startTime);
} catch (Exception e) {
handleException(methodName, null, startTime, e);
}
}
/** Test: listBuckets(). */
public static void listBuckets_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: listBuckets()");
}
long startTime = System.currentTimeMillis();
try {
long nowSeconds = ZonedDateTime.now().toEpochSecond();
String bucketName = getRandomName();
boolean found = false;
client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
for (Bucket bucket : client.listBuckets()) {
if (bucket.name().equals(bucketName)) {
if (found) {
throw new Exception(
"[FAILED] duplicate entry " + bucketName + " found in list buckets");
}
found = true;
// excuse 15 minutes
if ((bucket.creationDate().toEpochSecond() - nowSeconds) > (15 * 60)) {
throw new Exception(
"[FAILED] bucket creation time too apart in "
+ (bucket.creationDate().toEpochSecond() - nowSeconds)
+ " seconds");
}
}
}
client.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
if (!found) {
throw new Exception("[FAILED] created bucket not found in list buckets");
}
mintSuccessLog("listBuckets()", null, startTime);
} catch (Exception e) {
mintFailedLog(
"listBuckets()",
null,
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/** Test: bucketExists(BucketExistsArgs args). */
public static void bucketExists_test() throws Exception {
String methodName = "bucketExists(BucketExistsArgs args)";
if (!mintEnv) {
System.out.println("Test: " + methodName);
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(MakeBucketArgs.builder().bucket(name).build());
if (!client.bucketExists(BucketExistsArgs.builder().bucket(name).build())) {
throw new Exception("[FAILED] bucket does not exist");
}
client.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
mintSuccessLog(methodName, null, startTime);
} catch (Exception e) {
handleException(methodName, null, startTime, e);
}
}
/** Test: removeBucket(RemoveBucketArgs args). */
public static void removeBucket_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: removeBucket(RemoveBucketArgs args)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(MakeBucketArgs.builder().bucket(name).build());
client.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
mintSuccessLog("removeBucket(RemoveBucketArgs args)", null, startTime);
} catch (Exception e) {
mintFailedLog(
"removeBucket(RemoveBucketArgs args)",
null,
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/** Tear down test setup. */
public static void setup() throws Exception {
long startTime = System.currentTimeMillis();
try {
client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
handleException("makeBucket(MakeBucketArgs args)", null, startTime, e);
}
}
/** Tear down test setup. */
public static void teardown() throws Exception {
long startTime = System.currentTimeMillis();
try {
client.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
handleException("removeBucket(RemoveBucketArgs args)", null, startTime, e);
}
}
public static void testUploadObject(String testTags, String filename, String contentType)
throws Exception {
String methodName = "uploadObject()";
long startTime = System.currentTimeMillis();
try {
try {
UploadObjectArgs.Builder builder =
UploadObjectArgs.builder().bucket(bucketName).object(filename).filename(filename);
if (contentType != null) {
builder.contentType(contentType);
}
client.uploadObject(builder.build());
mintSuccessLog(methodName, testTags, startTime);
} finally {
Files.delete(Paths.get(filename));
client.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(filename).build());
}
} catch (Exception e) {
handleException(methodName, testTags, startTime, e);
}
}
/** Test: uploadObject() [single upload] */
public static void uploadObject_test() throws Exception {
String methodName = "uploadObject()";
if (!mintEnv) {
System.out.println("Test: " + methodName);
}
testUploadObject("[single upload]", createFile1Kb(), null);
if (isQuickTest) {
return;
}
testUploadObject("[multi-part upload]", createFile6Mb(), null);
testUploadObject("[custom content-type]", createFile1Kb(), customContentType);
}
public static void testPutObject(String testTags, PutObjectArgs args, ErrorCode errorCode)
throws Exception {
String methodName = "putObject()";
long startTime = System.currentTimeMillis();
try {
try {
client.putObject(args);
} catch (ErrorResponseException e) {
if (errorCode == null || e.errorResponse().errorCode() != errorCode) {
throw e;
}
}
client.removeObject(
RemoveObjectArgs.builder().bucket(args.bucket()).object(args.object()).build());
mintSuccessLog(methodName, testTags, startTime);
} catch (Exception e) {
handleException(methodName, testTags, startTime, e);
}
}
public static void testThreadedPutObject() throws Exception {
String methodName = "putObject()";
String testTags = "[threaded]";
long startTime = System.currentTimeMillis();
try {
int count = 7;
Thread[] threads = new Thread[count];
for (int i = 0; i < count; i++) {
threads[i] = new Thread(new PutObjectRunnable(client, bucketName, createFile6Mb()));
}
for (int i = 0; i < count; i++) {
threads[i].start();
}
// Waiting for threads to complete.
for (int i = 0; i < count; i++) {
threads[i].join();
}
// All threads are completed.
mintSuccessLog(methodName, testTags, startTime);
} catch (Exception e) {
handleException(methodName, testTags, startTime, e);
}
}
public static void putObject_test() throws Exception {
String methodName = "putObject()";
if (!mintEnv) {
System.out.println("Test: " + methodName);
}
testPutObject(
"[single upload]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(1 * KB), 1 * KB, -1)
.contentType(customContentType)
.build(),
null);
if (isQuickTest) {
return;
}
testPutObject(
"[multi-part upload]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(11 * MB), 11 * MB, -1)
.contentType(customContentType)
.build(),
null);
testPutObject(
"[object name with path segments]",
PutObjectArgs.builder().bucket(bucketName).object("path/to/" + getRandomName()).stream(
new ContentInputStream(1 * KB), 1 * KB, -1)
.contentType(customContentType)
.build(),
null);
testPutObject(
"[zero sized object]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(0), 0, -1)
.build(),
null);
testPutObject(
"[object name ends with '/']",
PutObjectArgs.builder().bucket(bucketName).object("path/to/" + getRandomName() + "/")
.stream(new ContentInputStream(0), 0, -1)
.contentType(customContentType)
.build(),
null);
testPutObject(
"[unknown stream size, single upload]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(1 * KB), -1, PutObjectArgs.MIN_MULTIPART_SIZE)
.contentType(customContentType)
.build(),
null);
testPutObject(
"[unknown stream size, multi-part upload]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(11 * MB), -1, PutObjectArgs.MIN_MULTIPART_SIZE)
.contentType(customContentType)
.build(),
null);
Map<String, String> userMetadata = new HashMap<>();
userMetadata.put("My-Project", "Project One");
userMetadata.put("My-header1", " a b c ");
userMetadata.put("My-Header2", "\"a b c\"");
testPutObject(
"[user metadata]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(1 * KB), 1 * KB, -1)
.userMetadata(userMetadata)
.build(),
null);
Map<String, String> headers = new HashMap<>();
headers.put("X-Amz-Storage-Class", "REDUCED_REDUNDANCY");
testPutObject(
"[storage-class=REDUCED_REDUNDANCY]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(1 * KB), 1 * KB, -1)
.headers(headers)
.build(),
null);
headers.put("X-Amz-Storage-Class", "STANDARD");
testPutObject(
"[storage-class=STANDARD]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(1 * KB), 1 * KB, -1)
.headers(headers)
.build(),
null);
headers.put("X-Amz-Storage-Class", "INVALID");
testPutObject(
"[storage-class=INVALID negative case]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(1 * KB), 1 * KB, -1)
.headers(headers)
.build(),
ErrorCode.INVALID_STORAGE_CLASS);
testPutObject(
"[SSE-S3]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(1 * KB), 1 * KB, -1)
.contentType(customContentType)
.sse(sseS3)
.build(),
null);
testThreadedPutObject();
if (!isSecureEndpoint) {
return;
}
testPutObject(
"[SSE-C single upload]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(1 * KB), 1 * KB, -1)
.contentType(customContentType)
.sse(ssec)
.build(),
null);
testPutObject(
"[SSE-C multi-part upload]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(11 * MB), 11 * MB, -1)
.contentType(customContentType)
.sse(ssec)
.build(),
null);
if (sseKms == null) {
mintIgnoredLog(methodName, null, System.currentTimeMillis());
return;
}
testPutObject(
"[SSE-KMS]",
PutObjectArgs.builder().bucket(bucketName).object(getRandomName()).stream(
new ContentInputStream(1 * KB), 1 * KB, -1)
.contentType(customContentType)
.sse(sseKms)
.build(),
null);
}
/** Test: statObject(StatObjectArgs args). */
public static void statObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: statObject(StatObjectArgs args)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("my-custom-data", "foo");
client.putObject(
PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
new ContentInputStream(1), 1, -1)
.contentType(customContentType)
.userMetadata(headerMap)
.build());
ObjectStat objectStat =
client.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
if (!(objectName.equals(objectStat.name())
&& (objectStat.length() == 1)
&& bucketName.equals(objectStat.bucketName())
&& objectStat.contentType().equals(customContentType))) {
throw new Exception("[FAILED] object stat differs");
}
Map<String, List<String>> httpHeaders = objectStat.httpHeaders();
if (!httpHeaders.containsKey("x-amz-meta-my-custom-data")) {
throw new Exception("[FAILED] metadata not found in object stat");
}
List<String> values = httpHeaders.get("x-amz-meta-my-custom-data");
if (values.size() != 1) {
throw new Exception("[FAILED] too many metadata value. expected: 1, got: " + values.size());
}
if (!values.get(0).equals("foo")) {
throw new Exception("[FAILED] wrong metadata value. expected: foo, got: " + values.get(0));
}
client.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
mintSuccessLog("statObject(StatObjectArgs args)", null, startTime);
} catch (Exception e) {
mintFailedLog(
"statObject(StatObjectArgs args)",
null,
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/** Test: with SSE-C: statObject(StatObjectArgs args). */
public static void statObject_test2() throws Exception {
long startTime = System.currentTimeMillis();
if (!isSecureEndpoint) {
mintIgnoredLog("statObject(StatObjectArgs args) using SSE_C.", null, startTime);
return;
}
if (!mintEnv) {
System.out.println("Test: with SSE-C: statObject(StatObjectArgs args)");
}