Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
awsdocs
GitHub Repository: awsdocs/amazon-s3-developer-guide
Path: blob/master/code_examples/java_examples/S3Examples/ListKeysVersioningEnabledBucket.java
4084 views
1
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE.)
3
4
import java.io.IOException;
5
6
import com.amazonaws.AmazonServiceException;
7
import com.amazonaws.SdkClientException;
8
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
9
import com.amazonaws.services.s3.AmazonS3;
10
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
11
import com.amazonaws.services.s3.model.ListVersionsRequest;
12
import com.amazonaws.services.s3.model.S3VersionSummary;
13
import com.amazonaws.services.s3.model.VersionListing;
14
15
public class ListKeysVersioningEnabledBucket {
16
17
public static void main(String[] args) throws IOException {
18
String clientRegion = "*** Client region ***";
19
String bucketName = "*** Bucket name ***";
20
21
try {
22
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
23
.withCredentials(new ProfileCredentialsProvider())
24
.withRegion(clientRegion)
25
.build();
26
27
// Retrieve the list of versions. If the bucket contains more versions
28
// than the specified maximum number of results, Amazon S3 returns
29
// one page of results per request.
30
ListVersionsRequest request = new ListVersionsRequest()
31
.withBucketName(bucketName)
32
.withMaxResults(2);
33
VersionListing versionListing = s3Client.listVersions(request);
34
int numVersions = 0, numPages = 0;
35
while(true) {
36
numPages++;
37
for (S3VersionSummary objectSummary :
38
versionListing.getVersionSummaries()) {
39
System.out.printf("Retrieved object %s, version %s\n",
40
objectSummary.getKey(),
41
objectSummary.getVersionId());
42
numVersions++;
43
}
44
// Check whether there are more pages of versions to retrieve. If
45
// there are, retrieve them. Otherwise, exit the loop.
46
if(versionListing.isTruncated()) {
47
versionListing = s3Client.listNextBatchOfVersions(versionListing);
48
}
49
else {
50
break;
51
}
52
}
53
System.out.println(numVersions + " object versions retrieved in " + numPages + " pages");
54
}
55
catch(AmazonServiceException e) {
56
// The call was transmitted successfully, but Amazon S3 couldn't process
57
// it, so it returned an error response.
58
e.printStackTrace();
59
}
60
catch(SdkClientException e) {
61
// Amazon S3 couldn't be contacted for a response, or the client
62
// couldn't parse the response from Amazon S3.
63
e.printStackTrace();
64
}
65
}
66
}
67