aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/eu/ortlepp/notificationsender/service/SnsNotificationSender.java
blob: 958365a7e3c1f1e42df9029820ad92f001249ac4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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<String> 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;
    }
  }

}