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