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/ModifyACLExistingObject.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.AccessControlList;
12
import com.amazonaws.services.s3.model.CanonicalGrantee;
13
import com.amazonaws.services.s3.model.EmailAddressGrantee;
14
import com.amazonaws.services.s3.model.Permission;
15
16
public class ModifyACLExistingObject {
17
18
public static void main(String[] args) throws IOException {
19
String clientRegion = "*** Client region ***";
20
String bucketName = "*** Bucket name ***";
21
String keyName = "*** Key name ***";
22
String emailGrantee = "*** [email protected] ***";
23
24
try {
25
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
26
.withCredentials(new ProfileCredentialsProvider())
27
.withRegion(clientRegion)
28
.build();
29
30
// Get the existing object ACL that we want to modify.
31
AccessControlList acl = s3Client.getObjectAcl(bucketName, keyName);
32
33
// Clear the existing list of grants.
34
acl.getGrantsAsList().clear();
35
36
// Grant a sample set of permissions, using the existing ACL owner for Full Control permissions.
37
acl.grantPermission(new CanonicalGrantee(acl.getOwner().getId()), Permission.FullControl);
38
acl.grantPermission(new EmailAddressGrantee(emailGrantee), Permission.WriteAcp);
39
40
// Save the modified ACL back to the object.
41
s3Client.setObjectAcl(bucketName, keyName, acl);
42
}
43
catch(AmazonServiceException e) {
44
// The call was transmitted successfully, but Amazon S3 couldn't process
45
// it, so it returned an error response.
46
e.printStackTrace();
47
}
48
catch(SdkClientException e) {
49
// Amazon S3 couldn't be contacted for a response, or the client
50
// couldn't parse the response from Amazon S3.
51
e.printStackTrace();
52
}
53
}
54
}
55