Create a topic and return its ARN.
public static String createSNSTopic(SnsClient snsClient, String topicName ) {
CreateTopicResponse result = null;
try {
CreateTopicRequest request = CreateTopicRequest.builder()
.name(topicName)
.build();
result = snsClient.createTopic(request);
return result.topicArn();
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
}
Subscribe an endpoint to a topic.
public static void subTextSNS( SnsClient snsClient, String topicArn, String phoneNumber) {
try {
SubscribeRequest request = SubscribeRequest.builder()
.protocol("sms")
.endpoint(phoneNumber)
.returnSubscriptionArn(true)
.topicArn(topicArn)
.build();
SubscribeResponse result = snsClient.subscribe(request);
System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode());
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
Set attributes on the message, such as the ID of the sender, the maximum price, and its type.
Message attributes are optional.
public class SetSMSAttributes {
public static void main(String[] args) {
HashMap<String, String> attributes = new HashMap<>(1);
attributes.put("DefaultSMSType", "Transactional");
attributes.put("UsageReportS3Bucket", "janbucket" );
SnsClient snsClient = SnsClient.builder()
.region(Region.US_EAST_1)
.credentialsProvider(ProfileCredentialsProvider.create())
.build();
setSNSAttributes(snsClient, attributes);
snsClient.close();
}
public static void setSNSAttributes( SnsClient snsClient, HashMap<String, String> attributes) {
try {
SetSmsAttributesRequest request = SetSmsAttributesRequest.builder()
.attributes(attributes)
.build();
SetSmsAttributesResponse result = snsClient.setSMSAttributes(request);
System.out.println("Set default Attributes to " + attributes + ". Status was " + result.sdkHttpResponse().statusCode());
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
Publish a message to a topic. The message is sent to every subscriber.
public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) {
try {
PublishRequest request = PublishRequest.builder()
.message(message)
.phoneNumber(phoneNumber)
.build();
PublishResponse result = snsClient.publish(request);
System.out.println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}