-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
XmlResponsesSaxParser.java
3932 lines (3408 loc) · 153 KB
/
XmlResponsesSaxParser.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Portions copyright 2006-2009 James Murty. Please see LICENSE.txt
* for applicable license terms and NOTICE.txt for applicable notices.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.s3.model.transform;
import com.amazonaws.services.s3.model.*;
import static com.amazonaws.util.StringUtils.UTF8;
import com.amazonaws.services.s3.model.inventory.ServerSideEncryptionKMS;
import com.amazonaws.services.s3.model.inventory.ServerSideEncryptionS3;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.amazonaws.services.s3.model.lifecycle.LifecycleAndOperator;
import com.amazonaws.services.s3.model.lifecycle.LifecycleFilter;
import com.amazonaws.services.s3.model.lifecycle.LifecycleFilterPredicate;
import com.amazonaws.services.s3.model.lifecycle.LifecyclePrefixPredicate;
import com.amazonaws.services.s3.model.lifecycle.LifecycleTagPredicate;
import com.amazonaws.services.s3.model.metrics.MetricsAndOperator;
import com.amazonaws.services.s3.model.metrics.MetricsConfiguration;
import com.amazonaws.services.s3.model.metrics.MetricsFilter;
import com.amazonaws.services.s3.model.metrics.MetricsFilterPredicate;
import com.amazonaws.services.s3.model.metrics.MetricsPrefixPredicate;
import com.amazonaws.services.s3.model.metrics.MetricsTagPredicate;
import com.amazonaws.services.s3.model.analytics.AnalyticsAndOperator;
import com.amazonaws.services.s3.model.analytics.AnalyticsConfiguration;
import com.amazonaws.services.s3.model.analytics.AnalyticsExportDestination;
import com.amazonaws.services.s3.model.analytics.AnalyticsFilter;
import com.amazonaws.services.s3.model.analytics.AnalyticsFilterPredicate;
import com.amazonaws.services.s3.model.analytics.AnalyticsPrefixPredicate;
import com.amazonaws.services.s3.model.analytics.AnalyticsS3BucketDestination;
import com.amazonaws.services.s3.model.analytics.AnalyticsTagPredicate;
import com.amazonaws.services.s3.model.analytics.StorageClassAnalysis;
import com.amazonaws.services.s3.model.analytics.StorageClassAnalysisDataExport;
import com.amazonaws.services.s3.model.inventory.InventoryConfiguration;
import com.amazonaws.services.s3.model.inventory.InventoryDestination;
import com.amazonaws.services.s3.model.inventory.InventoryFilter;
import com.amazonaws.services.s3.model.inventory.InventoryPrefixPredicate;
import com.amazonaws.services.s3.model.inventory.InventoryS3BucketDestination;
import com.amazonaws.services.s3.model.inventory.InventorySchedule;
import com.amazonaws.services.s3.model.replication.ReplicationAndOperator;
import com.amazonaws.services.s3.model.replication.ReplicationFilter;
import com.amazonaws.services.s3.model.replication.ReplicationFilterPredicate;
import com.amazonaws.services.s3.model.replication.ReplicationPrefixPredicate;
import com.amazonaws.services.s3.model.replication.ReplicationTagPredicate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.internal.Constants;
import com.amazonaws.services.s3.internal.DeleteObjectsResponse;
import com.amazonaws.services.s3.internal.ObjectExpirationResult;
import com.amazonaws.services.s3.internal.S3RequesterChargedResult;
import com.amazonaws.services.s3.internal.S3VersionResult;
import com.amazonaws.services.s3.internal.ServerSideEncryptionResult;
import com.amazonaws.services.s3.internal.ServiceUtils;
import com.amazonaws.services.s3.model.BucketLifecycleConfiguration.NoncurrentVersionTransition;
import com.amazonaws.services.s3.model.BucketLifecycleConfiguration.Rule;
import com.amazonaws.services.s3.model.BucketLifecycleConfiguration.Transition;
import com.amazonaws.services.s3.model.CORSRule.AllowedMethods;
import com.amazonaws.services.s3.model.DeleteObjectsResult.DeletedObject;
import com.amazonaws.services.s3.model.MultiObjectDeleteException.DeleteError;
import com.amazonaws.services.s3.model.RequestPaymentConfiguration.Payer;
import com.amazonaws.util.DateUtils;
import com.amazonaws.util.SdkHttpUtils;
import com.amazonaws.util.StringUtils;
/**
* XML Sax parser to read XML documents returned by S3 via the REST interface,
* converting these documents into objects.
*/
public class XmlResponsesSaxParser {
private static final Log log = LogFactory.getLog(XmlResponsesSaxParser.class);
private XMLReader xr = null;
private boolean sanitizeXmlDocument = true;
/**
* Constructs the XML SAX parser.
*
* @throws SdkClientException
*/
public XmlResponsesSaxParser() throws SdkClientException {
// Ensure we can load the XML Reader.
try {
xr = XMLReaderFactory.createXMLReader();
disableExternalResourceFetching(xr);
} catch (SAXException e) {
throw new SdkClientException("Couldn't initialize a SAX driver to create an XMLReader", e);
}
}
/**
* Parses an XML document from an input stream using a document handler.
*
* @param handler
* the handler for the XML document
* @param inputStream
* an input stream containing the XML document to parse
*
* @throws IOException
* on error reading from the input stream (ie connection reset)
* @throws SdkClientException
* on error with malformed XML, etc
*/
protected void parseXmlInputStream(DefaultHandler handler, InputStream inputStream)
throws IOException {
try {
if (log.isDebugEnabled()) {
log.debug("Parsing XML response document with handler: " + handler.getClass());
}
BufferedReader breader = new BufferedReader(new InputStreamReader(inputStream,
Constants.DEFAULT_ENCODING));
xr.setContentHandler(handler);
xr.setErrorHandler(handler);
xr.parse(new InputSource(breader));
} catch (IOException e) {
throw e;
} catch (Throwable t) {
try {
inputStream.close();
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error("Unable to close response InputStream up after XML parse failure", e);
}
}
throw new SdkClientException("Failed to parse XML document with handler "
+ handler.getClass(), t);
}
}
protected InputStream sanitizeXmlDocument(DefaultHandler handler, InputStream inputStream)
throws IOException {
if (!sanitizeXmlDocument) {
// No sanitizing will be performed, return the original input stream unchanged.
return inputStream;
} else {
if (log.isDebugEnabled()) {
log.debug("Sanitizing XML document destined for handler " + handler.getClass());
}
InputStream sanitizedInputStream = null;
try {
/*
* Read object listing XML document from input stream provided into a
* string buffer, so we can replace troublesome characters before
* sending the document to the XML parser.
*/
StringBuilder listingDocBuffer = new StringBuilder();
BufferedReader br = new BufferedReader(
new InputStreamReader(inputStream, Constants.DEFAULT_ENCODING));
char[] buf = new char[8192];
int read = -1;
while ((read = br.read(buf)) != -1) {
listingDocBuffer.append(buf, 0, read);
}
br.close();
/*
* Replace any carriage return (\r) characters with explicit XML
* character entities, to prevent the SAX parser from
* misinterpreting 0x0D characters as 0x0A and being unable to
* parse the XML.
*/
String listingDoc = listingDocBuffer.toString().replaceAll("\r", "
");
sanitizedInputStream = new ByteArrayInputStream(
listingDoc.getBytes(UTF8));
} catch (IOException e) {
throw e;
} catch (Throwable t) {
try {
inputStream.close();
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error("Unable to close response InputStream after failure sanitizing XML document", e);
}
}
throw new SdkClientException("Failed to sanitize XML document destined for handler "
+ handler.getClass(), t);
}
return sanitizedInputStream;
}
}
/**
* Disables certain dangerous features that attempt to automatically fetch DTDs
*
* See <a href="https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#XMLReader">OWASP XXE Cheat Sheet</a>
* @param reader the reader to disable the features on
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
*/
private void disableExternalResourceFetching(XMLReader reader) throws SAXNotRecognizedException, SAXNotSupportedException {
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false);
}
/**
* Checks if the specified string is empty or null and if so, returns null.
* Otherwise simply returns the string.
*
* @param s
* The string to check.
* @return Null if the specified string was null, or empty, otherwise
* returns the string the caller passed in.
*/
private static String checkForEmptyString(String s) {
if (s == null) return null;
if (s.length() == 0) return null;
return s;
}
/**
* Safely parses the specified string as an integer and returns the value.
* If a NumberFormatException occurs while parsing the integer, an error is
* logged and -1 is returned.
*
* @param s
* The string to parse and return as an integer.
*
* @return The integer value of the specified string, otherwise -1 if there
* were any problems parsing the string as an integer.
*/
private static int parseInt(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
log.error("Unable to parse integer value '" + s + "'", nfe);
}
return -1;
}
/**
* Safely parses the specified string as a long and returns the value. If a
* NumberFormatException occurs while parsing the long, an error is logged
* and -1 is returned.
*
* @param s
* The string to parse and return as a long.
*
* @return The long value of the specified string, otherwise -1 if there
* were any problems parsing the string as a long.
*/
private static long parseLong(String s) {
try {
return Long.parseLong(s);
} catch (NumberFormatException nfe) {
log.error("Unable to parse long value '" + s + "'", nfe);
}
return -1;
}
/**
* Perform a url decode on the given value if specified.
* Return value by default;
*/
private static String decodeIfSpecified(String value, boolean decode) {
return decode ? SdkHttpUtils.urlDecode(value) : value;
}
/**
* Parses a ListBucket response XML document from an input stream.
*
* @param inputStream
* XML data input stream.
* @return the XML handler object populated with data parsed from the XML
* stream.
* @throws SdkClientException
*/
public ListBucketHandler parseListBucketObjectsResponse(InputStream inputStream, final boolean shouldSDKDecodeResponse)
throws IOException {
ListBucketHandler handler = new ListBucketHandler(shouldSDKDecodeResponse);
parseXmlInputStream(handler, sanitizeXmlDocument(handler, inputStream));
return handler;
}
/**
* Parses a ListBucketV2 response XML document from an input stream.
*
* @param inputStream
* XML data input stream.
* @return the XML handler object populated with data parsed from the XML
* stream.
* @throws SdkClientException
*/
public ListObjectsV2Handler parseListObjectsV2Response(InputStream inputStream, final boolean shouldSDKDecodeResponse)
throws IOException {
ListObjectsV2Handler handler = new ListObjectsV2Handler(shouldSDKDecodeResponse);
parseXmlInputStream(handler, sanitizeXmlDocument(handler, inputStream));
return handler;
}
/**
* Parses a ListVersions response XML document from an input stream.
*
* @param inputStream
* XML data input stream.
* @return the XML handler object populated with data parsed from the XML
* stream.
* @throws SdkClientException
*/
public ListVersionsHandler parseListVersionsResponse(InputStream inputStream, final boolean shouldSDKDecodeResponse)
throws IOException {
ListVersionsHandler handler = new ListVersionsHandler(shouldSDKDecodeResponse);
parseXmlInputStream(handler, sanitizeXmlDocument(handler, inputStream));
return handler;
}
/**
* Parses a ListAllMyBuckets response XML document from an input stream.
*
* @param inputStream
* XML data input stream.
* @return the XML handler object populated with data parsed from the XML
* stream.
* @throws SdkClientException
*/
public ListAllMyBucketsHandler parseListMyBucketsResponse(InputStream inputStream)
throws IOException {
ListAllMyBucketsHandler handler = new ListAllMyBucketsHandler();
parseXmlInputStream(handler, sanitizeXmlDocument(handler, inputStream));
return handler;
}
/**
* Parses an AccessControlListHandler response XML document from an input
* stream.
*
* @param inputStream
* XML data input stream.
* @return the XML handler object populated with data parsed from the XML
* stream.
*
* @throws SdkClientException
*/
public AccessControlListHandler parseAccessControlListResponse(InputStream inputStream)
throws IOException {
AccessControlListHandler handler = new AccessControlListHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
/**
* Parses a LoggingStatus response XML document for a bucket from an input
* stream.
*
* @param inputStream
* XML data input stream.
* @return the XML handler object populated with data parsed from the XML
* stream.
*
* @throws SdkClientException
*/
public BucketLoggingConfigurationHandler parseLoggingStatusResponse(InputStream inputStream)
throws IOException {
BucketLoggingConfigurationHandler handler = new BucketLoggingConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public BucketLifecycleConfigurationHandler parseBucketLifecycleConfigurationResponse(InputStream inputStream)
throws IOException {
BucketLifecycleConfigurationHandler handler = new BucketLifecycleConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public BucketCrossOriginConfigurationHandler parseBucketCrossOriginConfigurationResponse(InputStream inputStream)
throws IOException {
BucketCrossOriginConfigurationHandler handler = new BucketCrossOriginConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public String parseBucketLocationResponse(InputStream inputStream)
throws IOException {
BucketLocationHandler handler = new BucketLocationHandler();
parseXmlInputStream(handler, inputStream);
return handler.getLocation();
}
public BucketVersioningConfigurationHandler parseVersioningConfigurationResponse(InputStream inputStream)
throws IOException {
BucketVersioningConfigurationHandler handler = new BucketVersioningConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public BucketWebsiteConfigurationHandler parseWebsiteConfigurationResponse(InputStream inputStream)
throws IOException {
BucketWebsiteConfigurationHandler handler = new BucketWebsiteConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public BucketReplicationConfigurationHandler parseReplicationConfigurationResponse(InputStream inputStream)
throws IOException {
BucketReplicationConfigurationHandler handler = new BucketReplicationConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public BucketTaggingConfigurationHandler parseTaggingConfigurationResponse(InputStream inputStream)
throws IOException {
BucketTaggingConfigurationHandler handler = new BucketTaggingConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public BucketAccelerateConfigurationHandler parseAccelerateConfigurationResponse(InputStream inputStream)
throws IOException {
BucketAccelerateConfigurationHandler handler = new BucketAccelerateConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public DeleteObjectsHandler parseDeletedObjectsResult(InputStream inputStream)
throws IOException {
DeleteObjectsHandler handler = new DeleteObjectsHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public CopyObjectResultHandler parseCopyObjectResponse(InputStream inputStream)
throws IOException {
CopyObjectResultHandler handler = new CopyObjectResultHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public CompleteMultipartUploadHandler parseCompleteMultipartUploadResponse(InputStream inputStream)
throws IOException {
CompleteMultipartUploadHandler handler = new CompleteMultipartUploadHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public InitiateMultipartUploadHandler parseInitiateMultipartUploadResponse(InputStream inputStream)
throws IOException {
InitiateMultipartUploadHandler handler = new InitiateMultipartUploadHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public ListMultipartUploadsHandler parseListMultipartUploadsResponse(InputStream inputStream)
throws IOException {
ListMultipartUploadsHandler handler = new ListMultipartUploadsHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public ListPartsHandler parseListPartsResponse(InputStream inputStream)
throws IOException {
ListPartsHandler handler = new ListPartsHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public GetObjectTaggingHandler parseObjectTaggingResponse(InputStream inputStream) throws IOException {
GetObjectTaggingHandler handler = new GetObjectTaggingHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public GetBucketMetricsConfigurationHandler parseGetBucketMetricsConfigurationResponse(InputStream inputStream)
throws IOException {
GetBucketMetricsConfigurationHandler handler = new GetBucketMetricsConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public ListBucketMetricsConfigurationsHandler parseListBucketMetricsConfigurationsResponse(InputStream inputStream)
throws IOException {
ListBucketMetricsConfigurationsHandler handler = new ListBucketMetricsConfigurationsHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public GetBucketAnalyticsConfigurationHandler parseGetBucketAnalyticsConfigurationResponse(InputStream inputStream)
throws IOException {
GetBucketAnalyticsConfigurationHandler handler = new GetBucketAnalyticsConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public ListBucketAnalyticsConfigurationHandler parseListBucketAnalyticsConfigurationResponse(InputStream inputStream)
throws IOException {
ListBucketAnalyticsConfigurationHandler handler = new ListBucketAnalyticsConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public GetBucketInventoryConfigurationHandler parseGetBucketInventoryConfigurationResponse(InputStream inputStream)
throws IOException {
GetBucketInventoryConfigurationHandler handler = new GetBucketInventoryConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public ListBucketInventoryConfigurationsHandler parseBucketListInventoryConfigurationsResponse(InputStream inputStream)
throws IOException {
ListBucketInventoryConfigurationsHandler handler = new ListBucketInventoryConfigurationsHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
/**
* @param inputStream
*
* @return true if the bucket's is configured as Requester Pays, false if it
* is configured as Owner pays.
*
* @throws SdkClientException
*/
public RequestPaymentConfigurationHandler parseRequestPaymentConfigurationResponse(InputStream inputStream)
throws IOException {
RequestPaymentConfigurationHandler handler = new RequestPaymentConfigurationHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public GetObjectLegalHoldResponseHandler parseGetObjectLegalHoldResponse(InputStream inputStream) throws IOException {
GetObjectLegalHoldResponseHandler handler = new GetObjectLegalHoldResponseHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public GetObjectLockConfigurationResponseHandler parseGetObjectLockConfigurationResponse(InputStream inputStream) throws IOException {
GetObjectLockConfigurationResponseHandler handler = new GetObjectLockConfigurationResponseHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
public GetObjectRetentionResponseHandler parseGetObjectRetentionResponse(InputStream inputStream) throws IOException {
GetObjectRetentionResponseHandler handler = new GetObjectRetentionResponseHandler();
parseXmlInputStream(handler, inputStream);
return handler;
}
// ////////////
// Handlers //
// ////////////
/**
* Handler for ListBucket response XML documents.
*/
public static class ListBucketHandler extends AbstractHandler {
private final ObjectListing objectListing = new ObjectListing();
private final boolean shouldSDKDecodeResponse;
private S3ObjectSummary currentObject = null;
private Owner currentOwner = null;
private String lastKey = null;
public ListBucketHandler(final boolean shouldSDKDecodeResponse) {
this.shouldSDKDecodeResponse = shouldSDKDecodeResponse;
}
public ObjectListing getObjectListing() {
return objectListing;
}
@Override
protected void doStartElement(
String uri,
String name,
String qName,
Attributes attrs) {
if (in("ListBucketResult")) {
if (name.equals("Contents")) {
currentObject = new S3ObjectSummary();
currentObject.setBucketName(objectListing.getBucketName());
}
}
else if (in("ListBucketResult", "Contents")) {
if (name.equals("Owner")) {
currentOwner = new Owner();
}
}
}
@Override
protected void doEndElement(String uri, String name, String qName) {
if (atTopLevel()) {
if (name.equals("ListBucketResult")) {
/*
* S3 only includes the NextMarker XML element if the
* request specified a delimiter, but for consistency we'd
* like to always give easy access to the next marker if
* we're returning a list of results that's truncated.
*/
if (objectListing.isTruncated()
&& objectListing.getNextMarker() == null) {
String nextMarker = null;
if (!objectListing.getObjectSummaries().isEmpty()) {
nextMarker = objectListing.getObjectSummaries()
.get(objectListing.getObjectSummaries().size() - 1)
.getKey();
} else if (!objectListing.getCommonPrefixes().isEmpty()) {
nextMarker = objectListing.getCommonPrefixes()
.get(objectListing.getCommonPrefixes().size() - 1);
} else {
log.error("S3 response indicates truncated results, "
+ "but contains no object summaries or "
+ "common prefixes.");
}
objectListing.setNextMarker(nextMarker);
}
}
}
else if (in("ListBucketResult")) {
if (name.equals("Name")) {
objectListing.setBucketName(getText());
if (log.isDebugEnabled()) {
log.debug("Examining listing for bucket: "
+ objectListing.getBucketName());
}
} else if (name.equals("Prefix")) {
objectListing.setPrefix(decodeIfSpecified
(checkForEmptyString(getText()), shouldSDKDecodeResponse));
} else if (name.equals("Marker")) {
objectListing.setMarker(decodeIfSpecified
(checkForEmptyString(getText()), shouldSDKDecodeResponse));
} else if (name.equals("NextMarker")) {
objectListing.setNextMarker(decodeIfSpecified
(getText(), shouldSDKDecodeResponse));
} else if (name.equals("MaxKeys")) {
objectListing.setMaxKeys(parseInt(getText()));
} else if (name.equals("Delimiter")) {
objectListing.setDelimiter(decodeIfSpecified
(checkForEmptyString(getText()), shouldSDKDecodeResponse));
} else if (name.equals("EncodingType")) {
objectListing.setEncodingType(shouldSDKDecodeResponse ?
null : checkForEmptyString(getText()));
} else if (name.equals("IsTruncated")) {
String isTruncatedStr =
StringUtils.lowerCase(getText());
if (isTruncatedStr.startsWith("false")) {
objectListing.setTruncated(false);
} else if (isTruncatedStr.startsWith("true")) {
objectListing.setTruncated(true);
} else {
throw new IllegalStateException(
"Invalid value for IsTruncated field: "
+ isTruncatedStr);
}
} else if (name.equals("Contents")) {
objectListing.getObjectSummaries().add(currentObject);
currentObject = null;
}
}
else if (in("ListBucketResult", "Contents")) {
if (name.equals("Key")) {
lastKey = getText();
currentObject.setKey(decodeIfSpecified
(lastKey, shouldSDKDecodeResponse));
} else if (name.equals("LastModified")) {
currentObject.setLastModified(
ServiceUtils.parseIso8601Date(getText()));
} else if (name.equals("ETag")) {
currentObject.setETag(
ServiceUtils.removeQuotes(getText()));
} else if (name.equals("Size")) {
currentObject.setSize(parseLong(getText()));
} else if (name.equals("StorageClass")) {
currentObject.setStorageClass(getText());
} else if (name.equals("Owner")) {
currentObject.setOwner(currentOwner);
currentOwner = null;
}
}
else if (in("ListBucketResult", "Contents", "Owner")) {
if (name.equals("ID")) {
currentOwner.setId(getText());
} else if (name.equals("DisplayName")) {
currentOwner.setDisplayName(getText());
}
}
else if (in("ListBucketResult", "CommonPrefixes")) {
if (name.equals("Prefix")) {
objectListing.getCommonPrefixes().add
(decodeIfSpecified(getText(), shouldSDKDecodeResponse));
}
}
}
}
/**
* Handler for ListObjectsV2 response XML documents.
*/
public static class ListObjectsV2Handler extends AbstractHandler {
private final ListObjectsV2Result result = new ListObjectsV2Result();
private final boolean shouldSDKDecodeResponse;
private S3ObjectSummary currentObject = null;
private Owner currentOwner = null;
private String lastKey = null;
public ListObjectsV2Handler(final boolean shouldSDKDecodeResponse) {
this.shouldSDKDecodeResponse = shouldSDKDecodeResponse;
}
public ListObjectsV2Result getResult() {
return result;
}
@Override
protected void doStartElement(
String uri,
String name,
String qName,
Attributes attrs) {
if (in("ListBucketResult")) {
if (name.equals("Contents")) {
currentObject = new S3ObjectSummary();
currentObject.setBucketName(result.getBucketName());
}
}
else if (in("ListBucketResult", "Contents")) {
if (name.equals("Owner")) {
currentOwner = new Owner();
}
}
}
@Override
protected void doEndElement(String uri, String name, String qName) {
if (atTopLevel()) {
if (name.equals("ListBucketResult")) {
/*
* S3 only includes the NextContinuationToken XML element if the
* request specified a delimiter, but for consistency we'd
* like to always give easy access to the next token if
* we're returning a list of results that's truncated.
*/
if (result.isTruncated()
&& result.getNextContinuationToken() == null) {
String nextContinuationToken = null;
if (!result.getObjectSummaries().isEmpty()) {
nextContinuationToken = result.getObjectSummaries()
.get(result.getObjectSummaries().size() - 1)
.getKey();
} else {
log.error("S3 response indicates truncated results, "
+ "but contains no object summaries.");
}
result.setNextContinuationToken(nextContinuationToken);
}
}
}
else if (in("ListBucketResult")) {
if (name.equals("Name")) {
result.setBucketName(getText());
if (log.isDebugEnabled()) {
log.debug("Examining listing for bucket: "
+ result.getBucketName());
}
} else if (name.equals("Prefix")) {
result.setPrefix(decodeIfSpecified
(checkForEmptyString(getText()), shouldSDKDecodeResponse));
} else if (name.equals("MaxKeys")) {
result.setMaxKeys(parseInt(getText()));
} else if (name.equals("NextContinuationToken")) {
result.setNextContinuationToken(getText());
} else if (name.equals("ContinuationToken")) {
result.setContinuationToken(getText());
} else if (name.equals("StartAfter")) {
result.setStartAfter(decodeIfSpecified
(getText(), shouldSDKDecodeResponse));
} else if (name.equals("KeyCount")) {
result.setKeyCount(parseInt(getText()));
} else if (name.equals("Delimiter")) {
result.setDelimiter(decodeIfSpecified
(checkForEmptyString(getText()), shouldSDKDecodeResponse));
} else if (name.equals("EncodingType")) {
result.setEncodingType(checkForEmptyString(getText()));
} else if (name.equals("IsTruncated")) {
String isTruncatedStr =
StringUtils.lowerCase(getText());
if (isTruncatedStr.startsWith("false")) {
result.setTruncated(false);
} else if (isTruncatedStr.startsWith("true")) {
result.setTruncated(true);
} else {
throw new IllegalStateException(
"Invalid value for IsTruncated field: "
+ isTruncatedStr);
}
} else if (name.equals("Contents")) {
result.getObjectSummaries().add(currentObject);
currentObject = null;
}
}
else if (in("ListBucketResult", "Contents")) {
if (name.equals("Key")) {
lastKey = getText();
currentObject.setKey(decodeIfSpecified
(lastKey, shouldSDKDecodeResponse));
} else if (name.equals("LastModified")) {
currentObject.setLastModified(
ServiceUtils.parseIso8601Date(getText()));
} else if (name.equals("ETag")) {
currentObject.setETag(
ServiceUtils.removeQuotes(getText()));
} else if (name.equals("Size")) {
currentObject.setSize(parseLong(getText()));
} else if (name.equals("StorageClass")) {
currentObject.setStorageClass(getText());
} else if (name.equals("Owner")) {
currentObject.setOwner(currentOwner);
currentOwner = null;
}
}
else if (in("ListBucketResult", "Contents", "Owner")) {
if (name.equals("ID")) {
currentOwner.setId(getText());
} else if (name.equals("DisplayName")) {
currentOwner.setDisplayName(getText());
}
}
else if (in("ListBucketResult", "CommonPrefixes")) {
if (name.equals("Prefix")) {
result.getCommonPrefixes().add
(decodeIfSpecified(getText(), shouldSDKDecodeResponse));
}
}
}
}
/**
* Handler for ListAllMyBuckets response XML documents. The document is
* parsed into {@link Bucket}s available via the {@link #getBuckets()}
* method.
*/
public static class ListAllMyBucketsHandler extends AbstractHandler {
private final List<Bucket> buckets = new ArrayList<Bucket>();
private Owner bucketsOwner = null;
private Bucket currentBucket = null;
/**
* @return the buckets listed in the document.
*/
public List<Bucket> getBuckets() {
return buckets;
}
/**
* @return the owner of the buckets.
*/
public Owner getOwner() {
return bucketsOwner;
}
@Override
protected void doStartElement(
String uri,
String name,
String qName,
Attributes attrs) {
if (in("ListAllMyBucketsResult")) {
if (name.equals("Owner")) {
bucketsOwner = new Owner();
}
} else if (in("ListAllMyBucketsResult", "Buckets")) {
if (name.equals("Bucket")) {
currentBucket = new Bucket();
currentBucket.setOwner(bucketsOwner);
}
}
}
@Override
protected void doEndElement(String uri, String name, String qName) {
if (in("ListAllMyBucketsResult", "Owner")) {
if (name.equals("ID")) {
bucketsOwner.setId(getText());
} else if (name.equals("DisplayName")) {
bucketsOwner.setDisplayName(getText());
}
}
else if (in("ListAllMyBucketsResult", "Buckets")) {
if (name.equals("Bucket")) {
buckets.add(currentBucket);
currentBucket = null;
}
}
else if (in("ListAllMyBucketsResult", "Buckets", "Bucket")) {
if (name.equals("Name")) {
currentBucket.setName(getText());
} else if (name.equals("CreationDate")) {
Date creationDate = DateUtils.parseISO8601Date(getText());
currentBucket.setCreationDate(creationDate);
}
}
}