Path: blob/master/code_examples/java_examples/S3Examples/CreateBucketWithACL.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;4import java.util.ArrayList;5import java.util.Collection;67import com.amazonaws.AmazonServiceException;8import com.amazonaws.SdkClientException;9import com.amazonaws.auth.profile.ProfileCredentialsProvider;10import com.amazonaws.services.s3.AmazonS3;11import com.amazonaws.services.s3.AmazonS3ClientBuilder;12import com.amazonaws.services.s3.model.AccessControlList;13import com.amazonaws.services.s3.model.CannedAccessControlList;14import com.amazonaws.services.s3.model.CanonicalGrantee;15import com.amazonaws.services.s3.model.CreateBucketRequest;16import com.amazonaws.services.s3.model.Grant;17import com.amazonaws.services.s3.model.GroupGrantee;18import com.amazonaws.services.s3.model.Permission;1920public class CreateBucketWithACL {2122public static void main(String[] args) throws IOException {23String clientRegion = "*** Client region ***";24String bucketName = "*** Bucket name ***";2526try {27AmazonS3 s3Client = AmazonS3ClientBuilder.standard()28.withCredentials(new ProfileCredentialsProvider())29.withRegion(clientRegion)30.build();3132// Create a bucket with a canned ACL. This ACL will be deleted by the33// getGrantsAsList().clear() call below. It is here for demonstration34// purposes.35CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName, clientRegion)36.withCannedAcl(CannedAccessControlList.LogDeliveryWrite);37s3Client.createBucket(createBucketRequest);3839// Create a collection of grants to add to the bucket.40Collection<Grant> grantCollection = new ArrayList<Grant>();4142// Grant the account owner full control.43Grant grant1 = new Grant(new CanonicalGrantee(s3Client.getS3AccountOwner().getId()), Permission.FullControl);44grantCollection.add(grant1);4546// Grant the LogDelivery group permission to write to the bucket.47Grant grant2 = new Grant(GroupGrantee.LogDelivery, Permission.Write);48grantCollection.add(grant2);4950// Save (replace) grants by deleting all current ACL grants and replacing51// them with the two we just created.52AccessControlList bucketAcl = s3Client.getBucketAcl(bucketName);53bucketAcl.getGrantsAsList().clear();54bucketAcl.getGrantsAsList().addAll(grantCollection);55s3Client.setBucketAcl(bucketName, bucketAcl);56}57catch(AmazonServiceException e) {58// The call was transmitted successfully, but Amazon S3 couldn't process59// it and returned an error response.60e.printStackTrace();61}62catch(SdkClientException e) {63// Amazon S3 couldn't be contacted for a response, or the client64// couldn't parse the response from Amazon S3.65e.printStackTrace();66}67}68}6970