-
-
Notifications
You must be signed in to change notification settings - Fork 724
Expand file tree
/
Copy pathS3_PING.java
More file actions
3025 lines (2584 loc) · 120 KB
/
S3_PING.java
File metadata and controls
3025 lines (2584 loc) · 120 KB
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
package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.annotations.Experimental;
import org.jgroups.annotations.Property;
import org.jgroups.annotations.Unsupported;
import org.jgroups.util.Util;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.lang.String.valueOf;
/**
* Discovery protocol using Amazon's S3 storage. The S3 access code reuses the example shipped by Amazon.
* This protocol is unsupported and experimental !
* @author Bela Ban
* @version $Id: S3_PING.java,v 1.11 2010/06/18 04:39:08 belaban Exp $
*/
@Experimental
public class S3_PING extends FILE_PING {
@Property(description="The access key to AWS (S3)")
protected String access_key=null;
@Property(description="The secret access key to AWS (S3)")
protected String secret_access_key=null;
@Property(description="When non-null, we set location to prefix-UUID")
protected String prefix=null;
protected AWSAuthConnection conn=null;
public void init() throws Exception {
super.init();
if(access_key == null || secret_access_key == null)
throw new IllegalArgumentException("access_key and secret_access_key must be non-null");
conn=new AWSAuthConnection(access_key, secret_access_key);
if(prefix != null && prefix.length() > 0) {
ListAllMyBucketsResponse bucket_list=conn.listAllMyBuckets(null);
List buckets=bucket_list.entries;
if(buckets != null) {
boolean found=false;
for(Object tmp: buckets) {
if(tmp instanceof Bucket) {
Bucket bucket=(Bucket)tmp;
if(bucket.name.startsWith(prefix)) {
location=bucket.name;
found=true;
}
}
}
if(!found) {
location=prefix + "-" + java.util.UUID.randomUUID().toString();
}
}
}
if(!conn.checkBucketExists(location)) {
conn.createBucket(location, AWSAuthConnection.LOCATION_DEFAULT, null).connection.getResponseMessage();
}
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
remove(group_addr, local_addr);
}
});
}
protected void createRootDir() {
; // do *not* create root file system (don't remove !)
}
protected List<PingData> readAll(String clustername) {
if(clustername == null)
return null;
List<PingData> retval=new ArrayList<PingData>();
try {
ListBucketResponse rsp=conn.listBucket(location, clustername, null, null, null);
if(rsp.entries != null) {
for(Iterator<ListEntry> it=rsp.entries.iterator(); it.hasNext();) {
ListEntry key=it.next();
GetResponse val=conn.get(location, key.key, null);
if(val.object != null) {
byte[] buf=val.object.data;
if(buf != null) {
try {
PingData data=(PingData)Util.objectFromByteBuffer(buf);
retval.add(data);
}
catch(Exception e) {
log.error("failed marshalling buffer to address", e);
}
}
}
}
}
return retval;
}
catch(IOException ex) {
log.error("failed reading addresses", ex);
return retval;
}
}
protected void writeToFile(PingData data, String clustername) {
if(clustername == null || data == null)
return;
String filename=local_addr instanceof org.jgroups.util.UUID? ((org.jgroups.util.UUID)local_addr).toStringLong() : local_addr.toString();
String key=clustername + "/" + filename;
try {
Map headers=new TreeMap();
headers.put("Content-Type", Arrays.asList("text/plain"));
byte[] buf=Util.objectToByteBuffer(data);
S3Object val=new S3Object(buf, null);
conn.put(location, key, val, headers).connection.getResponseMessage();
}
catch(Exception e) {
log.error("failed marshalling " + data + " to buffer", e);
}
}
protected void remove(String clustername, Address addr) {
if(clustername == null || addr == null)
return;
String filename=addr instanceof org.jgroups.util.UUID? ((org.jgroups.util.UUID)addr).toStringLong() : addr.toString();
String key=clustername + "/" + filename;
try {
Map headers=new TreeMap();
headers.put("Content-Type", Arrays.asList("text/plain"));
conn.delete(location, key, headers).connection.getResponseMessage();
if(log.isTraceEnabled())
log.trace("removing " + location + "/" + key);
}
catch(Exception e) {
log.error("failure removing data", e);
}
}
/**
* The following classes have been copied from Amazon's sample code
*/
static class AWSAuthConnection {
public static final String LOCATION_DEFAULT=null;
public static final String LOCATION_EU="EU";
private String awsAccessKeyId;
private String awsSecretAccessKey;
private boolean isSecure;
private String server;
private int port;
private CallingFormat callingFormat;
public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey) {
this(awsAccessKeyId, awsSecretAccessKey, true);
}
public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure) {
this(awsAccessKeyId, awsSecretAccessKey, isSecure, Utils.DEFAULT_HOST);
}
public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure,
String server) {
this(awsAccessKeyId, awsSecretAccessKey, isSecure, server,
isSecure? Utils.SECURE_PORT : Utils.INSECURE_PORT);
}
public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure,
String server, int port) {
this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, port, CallingFormat.getSubdomainCallingFormat());
}
public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure,
String server, CallingFormat format) {
this(awsAccessKeyId, awsSecretAccessKey, isSecure, server,
isSecure? Utils.SECURE_PORT : Utils.INSECURE_PORT,
format);
}
/**
* Create a new interface to interact with S3 with the given credential and connection
* parameters
* @param awsAccessKeyId Your user key into AWS
* @param awsSecretAccessKey The secret string used to generate signatures for authentication.
* @param isSecure use SSL encryption
* @param server Which host to connect to. Usually, this will be s3.amazonaws.com
* @param port Which port to use.
* @param format Type of request Regular/Vanity or Pure Vanity domain
*/
public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure,
String server, int port, CallingFormat format) {
this.awsAccessKeyId=awsAccessKeyId;
this.awsSecretAccessKey=awsSecretAccessKey;
this.isSecure=isSecure;
this.server=server;
this.port=port;
this.callingFormat=format;
}
/**
* Creates a new bucket.
* @param bucket The name of the bucket to create.
* @param headers A Map of String to List of Strings representing the http headers to pass (can be null).
*/
public Response createBucket(String bucket, Map headers) throws IOException {
return createBucket(bucket, null, headers);
}
/**
* Creates a new bucket.
* @param bucket The name of the bucket to create.
* @param location Desired location ("EU") (or null for default).
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
* @throws IllegalArgumentException on invalid location
*/
public Response createBucket(String bucket, String location, Map headers) throws IOException {
String body;
if(location == null) {
body=null;
}
else if(LOCATION_EU.equals(location)) {
if(!callingFormat.supportsLocatedBuckets())
throw new IllegalArgumentException("Creating location-constrained bucket with unsupported calling-format");
body="<CreateBucketConstraint><LocationConstraint>" + location + "</LocationConstraint></CreateBucketConstraint>";
}
else
throw new IllegalArgumentException("Invalid Location: " + location);
// validate bucket name
if(!Utils.validateBucketName(bucket, callingFormat))
throw new IllegalArgumentException("Invalid Bucket Name: " + bucket);
HttpURLConnection request=makeRequest("PUT", bucket, "", null, headers);
if(body != null) {
request.setDoOutput(true);
request.getOutputStream().write(body.getBytes("UTF-8"));
}
return new Response(request);
}
/**
* Check if the specified bucket exists (via a HEAD request)
* @param bucket The name of the bucket to check
* @return true if HEAD access returned success
*/
public boolean checkBucketExists(String bucket) throws IOException {
HttpURLConnection response=makeRequest("HEAD", bucket, "", null, null);
int httpCode=response.getResponseCode();
if(httpCode >= 200 && httpCode < 300)
return true;
if(httpCode == HttpURLConnection.HTTP_NOT_FOUND) // bucket doesn't exist
return false;
throw new IOException("bucket '" + bucket + "' could not be accessed (rsp=" +
httpCode + " (" + response.getResponseMessage() + "). Maybe the bucket is owned by somebody else or " +
"the authentication failed");
}
/**
* Lists the contents of a bucket.
* @param bucket The name of the bucket to create.
* @param prefix All returned keys will start with this string (can be null).
* @param marker All returned keys will be lexographically greater than
* this string (can be null).
* @param maxKeys The maximum number of keys to return (can be null).
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public ListBucketResponse listBucket(String bucket, String prefix, String marker,
Integer maxKeys, Map headers) throws IOException {
return listBucket(bucket, prefix, marker, maxKeys, null, headers);
}
/**
* Lists the contents of a bucket.
* @param bucket The name of the bucket to list.
* @param prefix All returned keys will start with this string (can be null).
* @param marker All returned keys will be lexographically greater than
* this string (can be null).
* @param maxKeys The maximum number of keys to return (can be null).
* @param delimiter Keys that contain a string between the prefix and the first
* occurrence of the delimiter will be rolled up into a single element.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public ListBucketResponse listBucket(String bucket, String prefix, String marker,
Integer maxKeys, String delimiter, Map headers) throws IOException {
Map pathArgs=Utils.paramsForListOptions(prefix, marker, maxKeys, delimiter);
return new ListBucketResponse(makeRequest("GET", bucket, "", pathArgs, headers));
}
/**
* Deletes a bucket.
* @param bucket The name of the bucket to delete.
* @param headers A Map of String to List of Strings representing the http headers to pass (can be null).
*/
public Response deleteBucket(String bucket, Map headers) throws IOException {
return new Response(makeRequest("DELETE", bucket, "", null, headers));
}
/**
* Writes an object to S3.
* @param bucket The name of the bucket to which the object will be added.
* @param key The name of the key to use.
* @param object An S3Object containing the data to write.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public Response put(String bucket, String key, S3Object object, Map headers) throws IOException {
HttpURLConnection request=
makeRequest("PUT", bucket, Utils.urlencode(key), null, headers, object);
request.setDoOutput(true);
request.getOutputStream().write(object.data == null? new byte[]{} : object.data);
return new Response(request);
}
/**
* Creates a copy of an existing S3 Object. In this signature, we will copy the
* existing metadata. The default access control policy is private; if you want
* to override it, please use x-amz-acl in the headers.
* @param sourceBucket The name of the bucket where the source object lives.
* @param sourceKey The name of the key to copy.
* @param destinationBucket The name of the bucket to which the object will be added.
* @param destinationKey The name of the key to use.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null). You may wish to set the x-amz-acl header appropriately.
*/
public Response copy(String sourceBucket, String sourceKey, String destinationBucket, String destinationKey, Map headers)
throws IOException {
S3Object object=new S3Object(new byte[]{}, new HashMap());
headers=headers == null? new HashMap() : new HashMap(headers);
headers.put("x-amz-copy-source", Arrays.asList(sourceBucket + "/" + sourceKey));
headers.put("x-amz-metadata-directive", Arrays.asList("COPY"));
return verifyCopy(put(destinationBucket, destinationKey, object, headers));
}
/**
* Creates a copy of an existing S3 Object. In this signature, we will replace the
* existing metadata. The default access control policy is private; if you want
* to override it, please use x-amz-acl in the headers.
* @param sourceBucket The name of the bucket where the source object lives.
* @param sourceKey The name of the key to copy.
* @param destinationBucket The name of the bucket to which the object will be added.
* @param destinationKey The name of the key to use.
* @param metadata A Map of String to List of Strings representing the S3 metadata
* for the new object.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null). You may wish to set the x-amz-acl header appropriately.
*/
public Response copy(String sourceBucket, String sourceKey, String destinationBucket, String destinationKey, Map metadata, Map headers)
throws IOException {
S3Object object=new S3Object(new byte[]{}, metadata);
headers=headers == null? new HashMap() : new HashMap(headers);
headers.put("x-amz-copy-source", Arrays.asList(sourceBucket + "/" + sourceKey));
headers.put("x-amz-metadata-directive", Arrays.asList("REPLACE"));
return verifyCopy(put(destinationBucket, destinationKey, object, headers));
}
/**
* Copy sometimes returns a successful response and starts to send whitespace
* characters to us. This method processes those whitespace characters and
* will throw an exception if the response is either unknown or an error.
* @param response Response object from the PUT request.
* @return The response with the input stream drained.
* @throws IOException If anything goes wrong.
*/
private static Response verifyCopy(Response response) throws IOException {
if(response.connection.getResponseCode() < 400) {
byte[] body=GetResponse.slurpInputStream(response.connection.getInputStream());
String message=new String(body);
if(message.contains("<Error")) {
throw new IOException(message.substring(message.indexOf("<Error")));
}
else if(message.contains("</CopyObjectResult>")) {
// It worked!
}
else {
throw new IOException("Unexpected response: " + message);
}
}
return response;
}
/**
* Reads an object from S3.
* @param bucket The name of the bucket where the object lives.
* @param key The name of the key to use.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public GetResponse get(String bucket, String key, Map headers) throws IOException {
return new GetResponse(makeRequest("GET", bucket, Utils.urlencode(key), null, headers));
}
/**
* Deletes an object from S3.
* @param bucket The name of the bucket where the object lives.
* @param key The name of the key to use.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public Response delete(String bucket, String key, Map headers) throws IOException {
return new Response(makeRequest("DELETE", bucket, Utils.urlencode(key), null, headers));
}
/**
* Get the requestPayment xml document for a given bucket
* @param bucket The name of the bucket
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public GetResponse getBucketRequestPayment(String bucket, Map headers) throws IOException {
Map pathArgs=new HashMap();
pathArgs.put("requestPayment", null);
return new GetResponse(makeRequest("GET", bucket, "", pathArgs, headers));
}
/**
* Write a new requestPayment xml document for a given bucket
* @param bucket The name of the bucket
* @param requestPaymentXMLDoc
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public Response putBucketRequestPayment(String bucket, String requestPaymentXMLDoc, Map headers)
throws IOException {
Map pathArgs=new HashMap();
pathArgs.put("requestPayment", null);
S3Object object=new S3Object(requestPaymentXMLDoc.getBytes(), null);
HttpURLConnection request=makeRequest("PUT", bucket, "", pathArgs, headers, object);
request.setDoOutput(true);
request.getOutputStream().write(object.data == null? new byte[]{} : object.data);
return new Response(request);
}
/**
* Get the logging xml document for a given bucket
* @param bucket The name of the bucket
* @param headers A Map of String to List of Strings representing the http headers to pass (can be null).
*/
public GetResponse getBucketLogging(String bucket, Map headers) throws IOException {
Map pathArgs=new HashMap();
pathArgs.put("logging", null);
return new GetResponse(makeRequest("GET", bucket, "", pathArgs, headers));
}
/**
* Write a new logging xml document for a given bucket
* @param loggingXMLDoc The xml representation of the logging configuration as a String
* @param bucket The name of the bucket
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public Response putBucketLogging(String bucket, String loggingXMLDoc, Map headers) throws IOException {
Map pathArgs=new HashMap();
pathArgs.put("logging", null);
S3Object object=new S3Object(loggingXMLDoc.getBytes(), null);
HttpURLConnection request=makeRequest("PUT", bucket, "", pathArgs, headers, object);
request.setDoOutput(true);
request.getOutputStream().write(object.data == null? new byte[]{} : object.data);
return new Response(request);
}
/**
* Get the ACL for a given bucket
* @param bucket The name of the bucket where the object lives.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public GetResponse getBucketACL(String bucket, Map headers) throws IOException {
return getACL(bucket, "", headers);
}
/**
* Get the ACL for a given object (or bucket, if key is null).
* @param bucket The name of the bucket where the object lives.
* @param key The name of the key to use.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public GetResponse getACL(String bucket, String key, Map headers) throws IOException {
if(key == null) key="";
Map pathArgs=new HashMap();
pathArgs.put("acl", null);
return new GetResponse(
makeRequest("GET", bucket, Utils.urlencode(key), pathArgs, headers)
);
}
/**
* Write a new ACL for a given bucket
* @param aclXMLDoc The xml representation of the ACL as a String
* @param bucket The name of the bucket where the object lives.
* @param headers A Map of String to List of Strings representing the http headers to pass (can be null).
*/
public Response putBucketACL(String bucket, String aclXMLDoc, Map headers) throws IOException {
return putACL(bucket, "", aclXMLDoc, headers);
}
/**
* Write a new ACL for a given object
* @param aclXMLDoc The xml representation of the ACL as a String
* @param bucket The name of the bucket where the object lives.
* @param key The name of the key to use.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public Response putACL(String bucket, String key, String aclXMLDoc, Map headers)
throws IOException {
S3Object object=new S3Object(aclXMLDoc.getBytes(), null);
Map pathArgs=new HashMap();
pathArgs.put("acl", null);
HttpURLConnection request=
makeRequest("PUT", bucket, Utils.urlencode(key), pathArgs, headers, object);
request.setDoOutput(true);
request.getOutputStream().write(object.data == null? new byte[]{} : object.data);
return new Response(request);
}
public LocationResponse getBucketLocation(String bucket)
throws IOException {
Map pathArgs=new HashMap();
pathArgs.put("location", null);
return new LocationResponse(makeRequest("GET", bucket, "", pathArgs, null));
}
/**
* List all the buckets created by this account.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
public ListAllMyBucketsResponse listAllMyBuckets(Map headers)
throws IOException {
return new ListAllMyBucketsResponse(makeRequest("GET", "", "", null, headers));
}
/**
* Make a new HttpURLConnection without passing an S3Object parameter.
* Use this method for key operations that do require arguments
* @param method The method to invoke
* @param bucketName the bucket this request is for
* @param key the key this request is for
* @param pathArgs the
* @param headers
* @return
* @throws MalformedURLException
* @throws IOException
*/
private HttpURLConnection makeRequest(String method, String bucketName, String key, Map pathArgs, Map headers)
throws IOException {
return makeRequest(method, bucketName, key, pathArgs, headers, null);
}
/**
* Make a new HttpURLConnection.
* @param method The HTTP method to use (GET, PUT, DELETE)
* @param bucket The bucket name this request affects
* @param key The key this request is for
* @param pathArgs parameters if any to be sent along this request
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
* @param object The S3Object that is to be written (can be null).
*/
private HttpURLConnection makeRequest(String method, String bucket, String key, Map pathArgs, Map headers,
S3Object object)
throws IOException {
CallingFormat format=Utils.getCallingFormatForBucket(this.callingFormat, bucket);
if(isSecure && format != CallingFormat.getPathCallingFormat() && bucket.contains(".")) {
System.err.println("You are making an SSL connection, however, the bucket contains periods and the wildcard certificate will not match by default. Please consider using HTTP.");
}
// build the domain based on the calling format
URL url=format.getURL(isSecure, server, this.port, bucket, key, pathArgs);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod(method);
// subdomain-style urls may encounter http redirects.
// Ensure that redirects are supported.
if(!connection.getInstanceFollowRedirects()
&& format.supportsLocatedBuckets())
throw new RuntimeException("HTTP redirect support required.");
addHeaders(connection, headers);
if(object != null) addMetadataHeaders(connection, object.metadata);
addAuthHeader(connection, method, bucket, key, pathArgs);
return connection;
}
/**
* Add the given headers to the HttpURLConnection.
* @param connection The HttpURLConnection to which the headers will be added.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
*/
private static void addHeaders(HttpURLConnection connection, Map headers) {
addHeaders(connection, headers, "");
}
/**
* Add the given metadata fields to the HttpURLConnection.
* @param connection The HttpURLConnection to which the headers will be added.
* @param metadata A Map of String to List of Strings representing the s3
* metadata for this resource.
*/
private static void addMetadataHeaders(HttpURLConnection connection, Map metadata) {
addHeaders(connection, metadata, Utils.METADATA_PREFIX);
}
/**
* Add the given headers to the HttpURLConnection with a prefix before the keys.
* @param connection The HttpURLConnection to which the headers will be added.
* @param headers A Map of String to List of Strings representing the http
* headers to pass (can be null).
* @param prefix The string to prepend to each key before adding it to the connection.
*/
private static void addHeaders(HttpURLConnection connection, Map headers, String prefix) {
if(headers != null) {
for(Iterator i=headers.keySet().iterator(); i.hasNext();) {
String key=(String)i.next();
for(Iterator j=((List)headers.get(key)).iterator(); j.hasNext();) {
String value=(String)j.next();
connection.addRequestProperty(prefix + key, value);
}
}
}
}
/**
* Add the appropriate Authorization header to the HttpURLConnection.
* @param connection The HttpURLConnection to which the header will be added.
* @param method The HTTP method to use (GET, PUT, DELETE)
* @param bucket the bucket name this request is for
* @param key the key this request is for
* @param pathArgs path arguments which are part of this request
*/
private void addAuthHeader(HttpURLConnection connection, String method, String bucket, String key, Map pathArgs) {
if(connection.getRequestProperty("Date") == null) {
connection.setRequestProperty("Date", httpDate());
}
if(connection.getRequestProperty("Content-Type") == null) {
connection.setRequestProperty("Content-Type", "");
}
String canonicalString=
Utils.makeCanonicalString(method, bucket, key, pathArgs, connection.getRequestProperties());
String encodedCanonical=Utils.encode(this.awsSecretAccessKey, canonicalString, false);
connection.setRequestProperty("Authorization",
"AWS " + this.awsAccessKeyId + ":" + encodedCanonical);
}
/**
* Generate an rfc822 date for use in the Date HTTP header.
*/
public static String httpDate() {
final String DateFormat="EEE, dd MMM yyyy HH:mm:ss ";
SimpleDateFormat format=new SimpleDateFormat(DateFormat, Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format.format(new Date()) + "GMT";
}
}
static class ListEntry {
/**
* The name of the object
*/
public String key;
/**
* The date at which the object was last modified.
*/
public Date lastModified;
/**
* The object's ETag, which can be used for conditional GETs.
*/
public String eTag;
/**
* The size of the object in bytes.
*/
public long size;
/**
* The object's storage class
*/
public String storageClass;
/**
* The object's owner
*/
public Owner owner;
public String toString() {
return key;
}
}
static class Owner {
public String id;
public String displayName;
}
static class Response {
public HttpURLConnection connection;
public Response(HttpURLConnection connection) throws IOException {
this.connection=connection;
}
}
static class GetResponse extends Response {
public S3Object object;
/**
* Pulls a representation of an S3Object out of the HttpURLConnection response.
*/
public GetResponse(HttpURLConnection connection) throws IOException {
super(connection);
if(connection.getResponseCode() < 400) {
Map metadata=extractMetadata(connection);
byte[] body=slurpInputStream(connection.getInputStream());
this.object=new S3Object(body, metadata);
}
}
/**
* Examines the response's header fields and returns a Map from String to List of Strings
* representing the object's metadata.
*/
private static Map extractMetadata(HttpURLConnection connection) {
TreeMap metadata=new TreeMap();
Map headers=connection.getHeaderFields();
for(Iterator i=headers.keySet().iterator(); i.hasNext();) {
String key=(String)i.next();
if(key == null) continue;
if(key.startsWith(Utils.METADATA_PREFIX)) {
metadata.put(key.substring(Utils.METADATA_PREFIX.length()), headers.get(key));
}
}
return metadata;
}
/**
* Read the input stream and dump it all into a big byte array
*/
static byte[] slurpInputStream(InputStream stream) throws IOException {
final int chunkSize=2048;
byte[] buf=new byte[chunkSize];
ByteArrayOutputStream byteStream=new ByteArrayOutputStream(chunkSize);
int count;
while((count=stream.read(buf)) != -1) byteStream.write(buf, 0, count);
return byteStream.toByteArray();
}
}
static class LocationResponse extends Response {
String location;
/**
* Parse the response to a ?location query.
*/
public LocationResponse(HttpURLConnection connection) throws IOException {
super(connection);
if(connection.getResponseCode() < 400) {
try {
XMLReader xr=Utils.createXMLReader();
;
LocationResponseHandler handler=new LocationResponseHandler();
xr.setContentHandler(handler);
xr.setErrorHandler(handler);
xr.parse(new InputSource(connection.getInputStream()));
this.location=handler.loc;
}
catch(SAXException e) {
throw new RuntimeException("Unexpected error parsing ListAllMyBuckets xml", e);
}
}
else {
this.location="<error>";
}
}
/**
* Report the location-constraint for a bucket.
* A value of null indicates an error;
* the empty string indicates no constraint;
* and any other value is an actual location constraint value.
*/
public String getLocation() {
return location;
}
/**
* Helper class to parse LocationConstraint response XML
*/
static class LocationResponseHandler extends DefaultHandler {
String loc=null;
private StringBuffer currText=null;
public void startDocument() {
}
public void startElement(String uri, String name, String qName, Attributes attrs) {
if(name.equals("LocationConstraint")) {
this.currText=new StringBuffer();
}
}
public void endElement(String uri, String name, String qName) {
if(name.equals("LocationConstraint")) {
loc=this.currText.toString();
this.currText=null;
}
}
public void characters(char ch[], int start, int length) {
if(currText != null)
this.currText.append(ch, start, length);
}
}
}
static class Bucket {
/**
* The name of the bucket.
*/
public String name;
/**
* The bucket's creation date.
*/
public Date creationDate;
public Bucket() {
this.name=null;
this.creationDate=null;
}
public Bucket(String name, Date creationDate) {
this.name=name;
this.creationDate=creationDate;
}
public String toString() {
return this.name;
}
}
static class ListBucketResponse extends Response {
/**
* The name of the bucket being listed. Null if request fails.
*/
public String name=null;
/**
* The prefix echoed back from the request. Null if request fails.
*/
public String prefix=null;
/**
* The marker echoed back from the request. Null if request fails.
*/
public String marker=null;
/**
* The delimiter echoed back from the request. Null if not specified in
* the request, or if it fails.
*/
public String delimiter=null;
/**
* The maxKeys echoed back from the request if specified. 0 if request fails.
*/
public int maxKeys=0;
/**
* Indicates if there are more results to the list. True if the current
* list results have been truncated. false if request fails.
*/
public boolean isTruncated=false;
/**
* Indicates what to use as a marker for subsequent list requests in the event
* that the results are truncated. Present only when a delimiter is specified.
* Null if request fails.
*/
public String nextMarker=null;
/**
* A List of ListEntry objects representing the objects in the given bucket.
* Null if the request fails.
*/
public List entries=null;
/**
* A List of CommonPrefixEntry objects representing the common prefixes of the
* keys that matched up to the delimiter. Null if the request fails.
*/
public List commonPrefixEntries=null;
public ListBucketResponse(HttpURLConnection connection) throws IOException {
super(connection);
if(connection.getResponseCode() < 400) {
try {
XMLReader xr=Utils.createXMLReader();
ListBucketHandler handler=new ListBucketHandler();
xr.setContentHandler(handler);
xr.setErrorHandler(handler);
xr.parse(new InputSource(connection.getInputStream()));
this.name=handler.getName();
this.prefix=handler.getPrefix();
this.marker=handler.getMarker();
this.delimiter=handler.getDelimiter();
this.maxKeys=handler.getMaxKeys();
this.isTruncated=handler.getIsTruncated();
this.nextMarker=handler.getNextMarker();
this.entries=handler.getKeyEntries();
this.commonPrefixEntries=handler.getCommonPrefixEntries();
}
catch(SAXException e) {
throw new RuntimeException("Unexpected error parsing ListBucket xml", e);
}
}
}
static class ListBucketHandler extends DefaultHandler {
private String name=null;
private String prefix=null;
private String marker=null;
private String delimiter=null;
private int maxKeys=0;