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