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/EnableNotificationOnABucket.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
import java.util.EnumSet;
6
7
import com.amazonaws.AmazonServiceException;
8
import com.amazonaws.SdkClientException;
9
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
10
import com.amazonaws.services.s3.AmazonS3;
11
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
12
import com.amazonaws.services.s3.model.BucketNotificationConfiguration;
13
import com.amazonaws.services.s3.model.TopicConfiguration;
14
import com.amazonaws.services.s3.model.QueueConfiguration;
15
import com.amazonaws.services.s3.model.S3Event;
16
import com.amazonaws.services.s3.model.SetBucketNotificationConfigurationRequest;
17
18
public class EnableNotificationOnABucket {
19
20
public static void main(String[] args) throws IOException {
21
String bucketName = "*** Bucket name ***";
22
String clientRegion = "*** Client region ***";
23
String snsTopicARN = "*** SNS Topic ARN ***";
24
String sqsQueueARN = "*** SQS Queue ARN ***";
25
26
try {
27
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
28
.withCredentials(new ProfileCredentialsProvider())
29
.withRegion(clientRegion)
30
.build();
31
BucketNotificationConfiguration notificationConfiguration = new BucketNotificationConfiguration();
32
33
// Add an SNS topic notification.
34
notificationConfiguration.addConfiguration("snsTopicConfig",
35
new TopicConfiguration(snsTopicARN, EnumSet.of(S3Event.ObjectCreated)));
36
37
// Add an SQS queue notification.
38
notificationConfiguration.addConfiguration("sqsQueueConfig",
39
new QueueConfiguration(sqsQueueARN, EnumSet.of(S3Event.ObjectCreated)));
40
41
// Create the notification configuration request and set the bucket notification configuration.
42
SetBucketNotificationConfigurationRequest request = new SetBucketNotificationConfigurationRequest(
43
bucketName, notificationConfiguration);
44
s3Client.setBucketNotificationConfiguration(request);
45
}
46
catch(AmazonServiceException e) {
47
// The call was transmitted successfully, but Amazon S3 couldn't process
48
// it, so it returned an error response.
49
e.printStackTrace();
50
}
51
catch(SdkClientException e) {
52
// Amazon S3 couldn't be contacted for a response, or the client
53
// couldn't parse the response from Amazon S3.
54
e.printStackTrace();
55
}
56
}
57
}
58