package eu.ortlepp.notificationsender.service; import com.amazonaws.services.lambda.runtime.LambdaLogger; import eu.ortlepp.notificationsender.util.Config; import java.util.List; import software.amazon.awssdk.http.HttpStatusCode; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * A notification sender for Amazon SNS. */ public class SnsNotificationSender implements NotificationSender { private final LambdaLogger logger; /** * Constructor to initialize the sender. * * @param logger The logger of the AWS Lambda */ public SnsNotificationSender(final LambdaLogger logger) { this.logger = logger; } /** * Send a list of notifications to the configured SNS topic. * All notifications are combined into a single message. * * @param notifications The notifications to send * @return The result of the sending; true = successful, false = error occurred */ @Override public boolean sendNotifications(final List notifications) { String notification = formatNotifications(notifications); try (SnsClient snsClient = SnsClient.builder().region(Config.REGION).build()) { PublishRequest request = PublishRequest.builder().message(notification).topicArn(Config.ARN).build(); PublishResponse result = snsClient.publish(request); int resultStatusCode = result.sdkHttpResponse().statusCode(); if (resultStatusCode == HttpStatusCode.OK) { logger.log("notification sent successfully"); return true; } logger.log("sending notification failed with status " + resultStatusCode); logger.log("failed message was " + notification); return false; } catch (SnsException ex) { logger.log("sending notification failed: " + ex.getMessage()); logger.log("failed message was " + notification); return false; } } }