All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.rajivprab.sava.events.SNSPublisher Maven / Gradle / Ivy

package org.rajivprab.sava.events;

import com.amazonaws.services.sns.AmazonSNS;
import com.google.common.base.Strings;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.javatuples.Triplet;

/**
 * Implementation of publisher that uses SNS
 *
 * Created by rajivprab on 6/4/17.
 */
class SNSPublisher implements Publisher {
    private static final Log log = LogFactory.getLog(Publisher.class);

    private final AmazonSNS snsClient;
    private String sendErrorTopic;

    public SNSPublisher(AmazonSNS client) {
        this.snsClient = client;
    }

    @Override
    public Publisher withSendErrorTopic(String sendErrorTopic) {
        this.sendErrorTopic = sendErrorTopic;
        return this;
    }

    @Override
    public void publish(String topic, String title, String message) {
        try {
            safePublish(topic, title, message);
        } catch (RuntimeException e) {
            if (Strings.isNullOrEmpty(sendErrorTopic)) {
                throw e;
            } else {
                log.error("Not throwing exception but SNS-Publish Error on Topic/Title/Message: " +
                                  Triplet.with(topic, title, message), e);
                try {
                    safePublish(sendErrorTopic, "SNS Publish Error",
                                "See sys-logs for failure reason and message contents");
                } catch (RuntimeException e2) {
                    log.fatal("Error reporting SNS-publish failed as well", e2);
                    throw e2;
                }
            }
        }
    }

    // -- Helper

    private void safePublish(String topic, String title, String message) {
        title = title.length() > 99 ? title.substring(0, 90) : title;
        title = title.trim().length() < 5 ? title + "_____" : title;
        title = title.replaceAll("[^A-Za-z0-9 ]", "_");
        snsClient.publish(topic, message, title);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy