Path: blob/master/code_examples/java_examples/S3Examples/DeleteObjectVersionEnabledBucket.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.BucketVersioningConfiguration;11import com.amazonaws.services.s3.model.DeleteVersionRequest;12import com.amazonaws.services.s3.model.PutObjectResult;1314public class DeleteObjectVersionEnabledBucket {1516public static void main(String[] args) throws IOException {17String clientRegion = "*** Client region ***";18String bucketName = "*** Bucket name ***";19String keyName = "*** Key name ****";2021try {22AmazonS3 s3Client = AmazonS3ClientBuilder.standard()23.withCredentials(new ProfileCredentialsProvider())24.withRegion(clientRegion)25.build();2627// Check to ensure that the bucket is versioning-enabled.28String bucketVersionStatus = s3Client.getBucketVersioningConfiguration(bucketName).getStatus();29if(!bucketVersionStatus.equals(BucketVersioningConfiguration.ENABLED)) {30System.out.printf("Bucket %s is not versioning-enabled.", bucketName);31}32else {33// Add an object.34PutObjectResult putResult = s3Client.putObject(bucketName, keyName, "Sample content for deletion example.");35System.out.printf("Object %s added to bucket %s\n", keyName, bucketName);3637// Delete the version of the object that we just created.38System.out.println("Deleting versioned object " + keyName);39s3Client.deleteVersion(new DeleteVersionRequest(bucketName, keyName, putResult.getVersionId()));40System.out.printf("Object %s, version %s deleted\n", keyName, putResult.getVersionId());41}42}43catch(AmazonServiceException e) {44// The call was transmitted successfully, but Amazon S3 couldn't process45// it, so it returned an error response.46e.printStackTrace();47}48catch(SdkClientException e) {49// Amazon S3 couldn't be contacted for a response, or the client50// couldn't parse the response from Amazon S3.51e.printStackTrace();52}53}54}5556