Example usage for com.amazonaws.services.sns.model SubscribeRequest SubscribeRequest

List of usage examples for com.amazonaws.services.sns.model SubscribeRequest SubscribeRequest

Introduction

In this page you can find the example usage for com.amazonaws.services.sns.model SubscribeRequest SubscribeRequest.

Prototype

public SubscribeRequest(String topicArn, String protocol, String endpoint) 

Source Link

Document

Constructs a new SubscribeRequest object.

Usage

From source file:com.amazon.aws.demo.anonymous.sns.SimpleNotification.java

License:Open Source License

public static SubscribeResult subscribe(String topicArn, String protocol, String endpoint) {
    SubscribeRequest req = new SubscribeRequest(topicArn, protocol, endpoint);
    return getInstance().subscribe(req);
}

From source file:com.amazon.aws.samplecode.travellog.aws.TravelLogSNSManager.java

License:Open Source License

/**
 * Subscribe a given commenter to future comments posted to the given entry.
 * //from   w w w  .  j  a v a 2 s  . c o  m
 * @param entry the entry to subscribe the commenter to
 * @param commenter the commenter to be subscribed
 * @return the result returned by AWS
 */
public SubscribeResult subscribe(Entry entry, Commenter commenter) {
    if (StringUtils.isEmpty(entry.getSnsArn())) {
        //If ARN isn't set then entry didn't have an SNS topic created with it so we ignore
        logger.log(Level.WARNING, "Entry did not have an SNS topic associated with it");
        return null;
    }
    SubscribeRequest request = new SubscribeRequest(entry.getSnsArn(), EMAIL_PROTOCOL, commenter.getEmail());
    SubscribeResult result = snsClient.subscribe(request);
    return result;
}

From source file:com.clicktravel.infrastructure.messaging.aws.sns.SnsTopicResource.java

License:Apache License

/**
 * Adds an AWS SQS subscription to the AWS SNS topic.
 * @param sqsQueueResource {@link SqsQueueResource} representative of AWS SQS queue subscribing to the AWS SNS
 *            topic.//w  w  w .  j a  v a  2 s.c o  m
 * @throws AmazonClientException
 */
public void subscribe(final SqsQueueResource sqsQueueResource) throws AmazonClientException {
    amazonSnsClient.subscribe(new SubscribeRequest(topicArn, "sqs", sqsQueueResource.queueArn()));
}

From source file:com.comcast.cns.controller.CNSSubscriptionPageServlet.java

License:Apache License

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (redirectUnauthenticatedUser(request, response)) {
        return;/* w w w  .  j  a  v a2 s.  co m*/
    }

    CMBControllerServlet.valueAccumulator.initializeAllCounters();
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    Map<?, ?> parameters = request.getParameterMap();

    String userId = request.getParameter("userId");
    String topicArn = request.getParameter("topicArn");
    String endPoint = request.getParameter("endPoint");
    String protocol = request.getParameter("protocol");
    String arn = request.getParameter("arn");
    String nextToken = request.getParameter("nextToken");

    connect(request);

    if (parameters.containsKey("Subscribe")) {

        try {

            SubscribeRequest subscribeRequest = new SubscribeRequest(topicArn, protocol.toLowerCase(),
                    endPoint);
            sns.subscribe(subscribeRequest);

        } catch (Exception ex) {
            logger.error("event=subscribe", ex);
            throw new ServletException(ex);
        }

    } else if (parameters.containsKey("Unsubscribe")) {

        try {
            UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest(arn);
            sns.unsubscribe(unsubscribeRequest);
        } catch (Exception ex) {
            logger.error("event=unsubscribe arn=" + arn, ex);
            throw new ServletException(ex);
        }
    }

    List<Subscription> subscriptions = new ArrayList<Subscription>();
    ListSubscriptionsByTopicResult listSubscriptionsByTopicResult = null;

    try {

        listSubscriptionsByTopicResult = sns
                .listSubscriptionsByTopic(new ListSubscriptionsByTopicRequest(topicArn, nextToken));
        subscriptions = listSubscriptionsByTopicResult.getSubscriptions();

    } catch (Exception ex) {
        logger.error("event=listAllSubscriptionsByTopic topic_arn=" + topicArn, ex);
        throw new ServletException(ex);
    }

    ICNSTopicPersistence topicHandler = PersistenceFactory.getTopicPersistence();
    CNSTopic topic = null;

    try {
        topic = topicHandler.getTopic(topicArn);
    } catch (Exception ex) {
        logger.error("event=getTopic topic_arn=" + topicArn, ex);
        throw new ServletException(ex);
    }

    out.println("<html>");
    out.println("<script type='text/javascript' language='javascript'>");
    out.println("function changeEndpointHint(protocol){ ");
    out.println(" if (protocol == 'HTTP' || protocol == 'HTTPS') { ");
    out.println(" document.getElementById('endPoint').placeholder = 'e.g. http://company.com'; }");
    out.println(" else if (protocol == 'EMAIL' || protocol == 'EMAIL_JSON') { ");
    out.println(" document.getElementById('endPoint').placeholder = 'e.g. user@domain.com'; }");
    out.println(" else if (protocol == 'CQS' || protocol == 'SQS') { ");
    out.println(
            " document.getElementById('endPoint').placeholder = 'e.g. arn:aws:cqs:ccp:555555555555:my-queue'; } ");
    out.println(
            " else if (protocol == 'redis') { document.getElementById('endPoint').placeholder = 'e.g. redis://server:port/channelname'; }");
    out.println("}");
    out.println("</script>");

    header(request, out, "Subscriptions for Topic " + ((topic != null) ? topic.getName() : ""));

    out.println("<body>");

    out.println("<h2>Subscriptions for Topic " + ((topic != null) ? topic.getName() : "") + "</h2>");

    if (user != null) {
        out.println("<table><tr><td><b>User Name:</b></td><td>" + user.getUserName() + "</td></tr>");
        out.println("<tr><td><b>User ID:</b></td><td>" + user.getUserId() + "</td></tr>");
        out.println("<tr><td><b>Access Key:</b></td><td>" + user.getAccessKey() + "</td></tr>");
        out.println("<tr><td><b>Access Secret:</b></td><td>" + user.getAccessSecret() + "</td></tr>");
        out.println("<tr><td><b>Topic Name:</b></td><td>" + topic.getName() + "</td></tr>");
        out.println("<tr><td><b>Topic Display Name:</b></td><td>" + topic.getDisplayName() + "</td></tr>");
        out.println("<tr><td><b>Topic Arn:</b></td><td>" + topic.getArn() + "</td></tr>");
        out.println("<tr><td><b>Num Subscriptions:</b></td><td>" + subscriptions.size() + "</td></tr></table>");
    }

    out.println("<p><table><tr><td><b>Protocol</b></td><td><b>End Point</b></td><td>&nbsp;</td></tr>");
    out.println("<form action=\"/webui/cnsuser/subscription/?userId=" + userId + "&topicArn=" + topicArn
            + "\" method=POST>");
    out.println(
            "<tr><td><select name='protocol' onchange='changeEndpointHint(this.value)'><option value='HTTP'>HTTP</option><option value='HTTPS'>HTTPS</option><option value='EMAIL'>EMAIL</option><option value='EMAIL_JSON'>EMAIL_JSON</option><option value='CQS'>CQS</option><option value='SQS'>SQS</option><option value='redis'>REDIS</option></select></td>");
    out.println(
            "<td><input type='text' name='endPoint' id = 'endPoint' size='65' placeholder='e.g. http://company.com'><input type='hidden' name='userId' value='"
                    + userId
                    + "'></td><td><input type='submit' value='Subscribe' name='Subscribe' /></td></tr>");
    out.println("</form></table>");

    out.println("<p><hr width='100%' align='left' />");
    out.println("<p><table class = 'alternatecolortable' border='1'>");
    out.println("<tr><th>Row</th>");
    out.println("<th>Arn</th>");
    out.println("<th>Protocol</th>");
    out.println("<th>End Point</th>");
    out.println("<th>Subscription Attributes</th>");
    out.println("<th>Raw Message Delivery</th>");
    out.println("<th>&nbsp;</th></tr>");

    for (int i = 0; subscriptions != null && i < subscriptions.size(); i++) {

        Subscription s = subscriptions.get(i);
        out.println("<tr>");
        out.println("<form action=\"/webui/cnsuser/subscription/?userId=" + user.getUserId() + "&arn="
                + s.getSubscriptionArn() + "&topicArn=" + topicArn + "\" method=POST>");
        out.println("<td>" + i + "</td>");
        out.println("<td>" + s.getSubscriptionArn() + "<input type='hidden' name='arn' value="
                + s.getSubscriptionArn() + "></td>");
        out.println("<td>" + s.getProtocol() + "</td>");
        if (s.getProtocol().toLowerCase().equals("cqs") && isAdmin(request)) {
            out.println("<td><a href='/webui/cqsuser?userId=" + Util.getUserIdForQueueArn(s.getEndpoint())
                    + "'>" + s.getEndpoint() + "</a></td>");
        } else {
            out.println("<td>" + s.getEndpoint() + "</td>");
        }

        if (s.getProtocol().toString().equals("http")
                && !s.getSubscriptionArn().equals("PendingConfirmation")) {
            out.println(
                    "<td><a href='#' onclick=\"window.open('/webui/cnsuser/subscription/editdeliverypolicy?subscriptionArn="
                            + s.getSubscriptionArn() + "&userId=" + userId
                            + "', 'EditDeliveryPolicy', 'height=630,width=580,toolbar=no')\">View/Edit Delivery Policy</a></td>");
        } else {
            out.println("<td>&nbsp;</td>");
        }

        if ((s.getProtocol().toString().equals("https") || s.getProtocol().toString().equals("http")
                || s.getProtocol().toString().equals("cqs") || s.getProtocol().toString().equals("sqs"))
                && !s.getSubscriptionArn().equals("PendingConfirmation")) {
            String url = "/webui/cnsuser/subscription/rawmessagedeliverypolicy/?subscriptionArn="
                    + s.getSubscriptionArn() + "&userId=" + userId;
            out.println("<td><a href='#' onclick=\"window.open('" + url
                    + "', 'RawMessageDelivery', 'height=200,width=580,toolbar=no')\">Raw Message Delivery</a></td>");
        } else {
            out.println("<td>&nbsp;</td>");
        }

        if (s.getSubscriptionArn().equals("PendingConfirmation")) {
            out.println("<td>&nbsp;</td>");
        } else {
            out.println("<td><input type='submit' value='Unsubscribe' name='Unsubscribe'/></td>");
        }

        out.println("</form></tr>");
    }

    out.println("</table></p>");

    if (listSubscriptionsByTopicResult != null && listSubscriptionsByTopicResult.getNextToken() != null) {
        out.println("<p><a href='/webui/cnsuser/subscription/?userId=" + userId + "&topicArn=" + topicArn
                + "&nextToken=" + response.encodeURL(listSubscriptionsByTopicResult.getNextToken())
                + "'>next&nbsp;&gt;</a></p>");
    }

    out.println("<h5 style='text-align:center;'><a href='/webui'>ADMIN HOME</a>");
    out.println(
            "<a href='/webui/cnsuser?userId=" + userId + "&topicArn=" + topicArn + "'>BACK TO TOPIC</a></h5>");
    out.println("</body></html>");

    CMBControllerServlet.valueAccumulator.deleteAllCounters();
}

From source file:com.easarrive.aws.plugins.common.service.impl.SNSService.java

License:Open Source License

/**
 * {@inheritDoc}/*w  w  w  .ja v  a 2 s  . co m*/
 */
@Override
public SubscribeResult subscribingTopic(AmazonSNS client, SNSSubscribingTopicRequest subscribingTopicRequest) {
    if (subscribingTopicRequest == null) {
        return null;
    }
    SubscribeRequest subscribeRequest = new SubscribeRequest(subscribingTopicRequest.getTopicArn(),
            subscribingTopicRequest.getProtocol(), subscribingTopicRequest.getEndpoint());
    SubscribeResult result = client.subscribe(subscribeRequest);

    return result;
}

From source file:com.intuit.tank.vmManager.environment.amazon.CloudwatchInstance.java

License:Open Source License

/**
 * // w ww.  j  av  a 2 s. co m
 * @param email
 * @return
 */
public String getOrCreateNotification(String email) {
    String ret = null;
    String topicName = getTopicName(email);
    String nextToken = null;
    do {
        ListTopicsResult listTopics = asyncSnsClient.listTopics(nextToken);
        List<Topic> topics = listTopics.getTopics();
        for (Topic s : topics) {
            if (s.getTopicArn().endsWith(topicName)) {
                ret = s.getTopicArn();
                break;
            }
        }
        nextToken = listTopics.getNextToken();
    } while (ret == null && nextToken != null);
    if (ret == null) {
        // create the topic and the subscription
        CreateTopicResult topic = asyncSnsClient.createTopic(topicName);
        SubscribeRequest req = new SubscribeRequest(topic.getTopicArn(), "email", email);
        asyncSnsClient.subscribeAsync(req);
        ret = topic.getTopicArn();
    }

    return ret;
}

From source file:com.nike.cerberus.operation.gateway.CreateCloudFrontSecurityGroupUpdaterLambdaOperation.java

License:Apache License

@Override
public void run(CreateCloudFrontSecurityGroupUpdaterLambdaCommand command) {
    if (!cloudFormationService.isStackPresent(StackName.CLOUD_FRONT_IP_SYNCHRONIZER.getName())) {
        createLambda();//from w w  w  .  j a va 2 s . co m
    }

    Map<String, String> outputs = cloudFormationService
            .getStackOutputs(StackName.CLOUD_FRONT_IP_SYNCHRONIZER.getName());
    CloudFrontIpSynchronizerOutputs cloudFrontIpSynchronizerOutputs = cloudformationObjectMapper
            .convertValue(outputs, CloudFrontIpSynchronizerOutputs.class);

    final String arn = cloudFrontIpSynchronizerOutputs.getCloudFrontOriginElbSgIpSyncFunctionArn();

    // subscribe, if already subscribed it doesn't make a new sub
    amazonSNS.subscribe(new SubscribeRequest(AWS_IP_CHANGE_TOPIC_ARN, "lambda", arn));

    // force any new ELBs that have the tags we care about to be updated to only allow ingress from CloudFront
    forceLambdaToUpdateSgs(arn);
}

From source file:com.pocketdealhunter.HotDealsMessagesUtil.java

License:Open Source License

public void subscribeEmail(String email) {
    try {/*from ww w .  j  av a  2 s .c  o  m*/
        SubscribeRequest sr = new SubscribeRequest(this.topicARN, "email", email);
        this.snsClient.subscribe(sr);
    } catch (Exception exception) {
        System.out.println("Exception  = " + exception);
    }
}

From source file:com.pocketdealhunter.HotDealsMessagesUtil.java

License:Open Source License

public void subscribeSms(String sms) {
    try {//from   w ww  .  j  a  v a2 s .c om
        SubscribeRequest sr = new SubscribeRequest(this.topicARN, "sms", sms);
        this.snsClient.subscribe(sr);
    } catch (Exception exception) {
        System.out.println("Exception  = " + exception);
    }
}

From source file:com.screensaver.util.AmazonSNSClientWrapper.java

License:Open Source License

public void demoNotification(Platform platform, String principal, String credential, String platformToken,
        String applicationName, Map<Platform, Map<String, MessageAttributeValue>> attrsMap) {

    String prefEndpointArn = PrefUtils.getString(context, Constants.PREF_END_POINT_ARN, "");
    boolean updateNeeded = false;
    boolean createNeeded = false;
    if (prefEndpointArn != null && !prefEndpointArn.equalsIgnoreCase("")) {
        createNeeded = false;//from  w ww .j  a va  2s.co m
    } else {
        createNeeded = true;
    }
    if (createNeeded) {
        // Create Platform Application. This corresponds to an app on a
        // platform.
        try {

            CreatePlatformApplicationResult platformApplicationResult = createPlatformApplication(
                    applicationName, platform, principal, credential);

            // The Platform Application Arn can be used to uniquely identify the
            // Platform Application.
            String platformApplicationArn = platformApplicationResult.getPlatformApplicationArn();

            // Create an Endpoint. This corresponds to an app on a device.

            CreatePlatformEndpointResult platformEndpointResult = createPlatformEndpoint(platform,
                    "CustomData - Useful to store endpoint specific data", platformToken,
                    platformApplicationArn);
            System.out.println(platformEndpointResult);
            prefEndpointArn = platformEndpointResult.getEndpointArn();
            PrefUtils.saveString(context, Constants.PREF_END_POINT_ARN, prefEndpointArn);

            // Publish a push notification to an Endpoint.
            CreateTopicResult createTopicResult = createTopic(platform,
                    "CustomData - Useful to store endpoint specific data", platformToken,
                    platformApplicationArn);
            SubscribeRequest subscribeRequest = new SubscribeRequest(createTopicResult.getTopicArn(),
                    "application", platformEndpointResult.getEndpointArn());
            snsClient.subscribe(subscribeRequest);
            createNeeded = false;
        } catch (Exception e) {
            String message = e.getMessage();
            System.out.println("Exception message: " + message);
            Pattern p = Pattern
                    .compile(".*Endpoint (arn:aws:sns[^ ]+) already exists " + "with the same token.*");
            Matcher m = p.matcher(message);
            if (m.matches()) {
                // The platform endpoint already exists for this token, but with
                // additional custom data that
                // createEndpoint doesn't want to overwrite. Just use the
                // existing platform endpoint.
                prefEndpointArn = m.group(1);
                PrefUtils.saveString(context, Constants.PREF_END_POINT_ARN, prefEndpointArn);
            } else {
                // Rethrow the exception, the input is actually bad.
                throw e;
            }

        }
    }

    try {
        GetEndpointAttributesRequest geaReq = new GetEndpointAttributesRequest()
                .withEndpointArn(prefEndpointArn);
        GetEndpointAttributesResult geaRes = snsClient.getEndpointAttributes(geaReq);

        updateNeeded = !geaRes.getAttributes().get("Token").equals(platformToken)
                || !geaRes.getAttributes().get("Enabled").equalsIgnoreCase("true");

    } catch (Exception nfe) {
        // We had a stored ARN, but the platform endpoint associated with it
        // disappeared. Recreate it.
        createNeeded = true;
    }

    if (createNeeded) {
        // Create Platform Application. This corresponds to an app on a
        // platform.
        try {

            CreatePlatformApplicationResult platformApplicationResult = createPlatformApplication(
                    applicationName, platform, principal, credential);

            // The Platform Application Arn can be used to uniquely identify the
            // Platform Application.
            String platformApplicationArn = platformApplicationResult.getPlatformApplicationArn();

            // Create an Endpoint. This corresponds to an app on a device.

            CreatePlatformEndpointResult platformEndpointResult = createPlatformEndpoint(platform, "",
                    platformToken, platformApplicationArn);
            System.out.println(platformEndpointResult);
            prefEndpointArn = platformEndpointResult.getEndpointArn();
            PrefUtils.saveString(context, Constants.PREF_END_POINT_ARN, prefEndpointArn);

            // Publish a push notification to an Endpoint.
            CreateTopicResult createTopicResult = createTopic(platform, "", platformToken,
                    platformApplicationArn);
            SubscribeRequest subscribeRequest = new SubscribeRequest(createTopicResult.getTopicArn(),
                    "application", platformEndpointResult.getEndpointArn());
            snsClient.subscribe(subscribeRequest);
            createNeeded = false;
        } catch (Exception e) {
            String message = e.getMessage();
            System.out.println("Exception message: " + message);
            Pattern p = Pattern
                    .compile(".*Endpoint (arn:aws:sns[^ ]+) already exists " + "with the same token.*");
            Matcher m = p.matcher(message);
            if (m.matches()) {
                // The platform endpoint already exists for this token, but with
                // additional custom data that
                // createEndpoint doesn't want to overwrite. Just use the
                // existing platform endpoint.
                prefEndpointArn = m.group(1);
                PrefUtils.saveString(context, Constants.PREF_END_POINT_ARN, prefEndpointArn);
            } else {
                // Rethrow the exception, the input is actually bad.
                throw e;
            }

        }
    }
    if (updateNeeded) {
        Map attribs = new HashMap();
        attribs.put("Token", platformToken);
        attribs.put("Enabled", "true");
        SetEndpointAttributesRequest saeReq = new SetEndpointAttributesRequest()
                .withEndpointArn(prefEndpointArn).withAttributes(attribs);
        snsClient.setEndpointAttributes(saeReq);
    }

    //        PublishResult publishResult = publish(subscribeRequest.getEndpoint(), platform, attrsMap);

    // Delete the Platform Application since we will no longer be using it.
    //        deletePlatformApplication(platformApplicationArn);
}