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

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

Introduction

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

Prototype

public CreateTopicRequest(String name) 

Source Link

Document

Constructs a new CreateTopicRequest object.

Usage

From source file:br.com.insula.log4j.sns.SNSAppender.java

License:Open Source License

private void createTopicArn() {
    this.topicArn = amazonSNSAsync.createTopic(new CreateTopicRequest(topic)).getTopicArn();
}

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

License:Open Source License

public static CreateTopicResult createTopic(String name) {
    CreateTopicRequest req = new CreateTopicRequest(name);
    return getInstance().createTopic(req);
}

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

License:Open Source License

/**
 * Creates the SNS topic associated with an entry.  When the topic is created, 
 * we will get an ARN (Amazon Resource Name) which uniquely identifies the 
 * SNS topic.  We write that ARN to the entry entity so that we can refer to it
 * later when subscribing commenters, etc.
 * //from  ww  w  .jav a  2 s. c o  m
 * @param entry the new entry that's associated with the topic
 * @return the result returned from AWS
 */
public CreateTopicResult createTopic(Entry entry) {
    CreateTopicRequest request = new CreateTopicRequest(getTopicName(entry));
    CreateTopicResult result = snsClient.createTopic(request);
    entry.setSnsArn(result.getTopicArn());
    return result;
}

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

License:Apache License

private String createAwsSnsTopic(final String name) {
    logger.info("Creating SNS topic: " + name);
    return amazonSnsClient.createTopic(new CreateTopicRequest(name)).getTopicArn();
}

From source file:com.comcast.cmb.test.tools.CMBTutorial.java

License:Apache License

public static void main(String[] args) {

    try {//  ww  w  . ja v a2s  .co  m

        Util.initLog4jTest();

        //TODO: set user id and credentials for two distinct users

        // user "cqs_test_1"

        //BasicAWSCredentials user1Credentials = new BasicAWSCredentials("<access_key>", "<secret_key>");

        BasicAWSCredentials user1Credentials = new BasicAWSCredentials("Z2DVBFRNZ2C2SSXDWS5F",
                "bH2UQiJkpctBaE3eaDob19fj5J9Q1FVafrZantBp");

        // user "cqs_test_2"

        //String user2Id = "<user_id>";
        String user2Id = "389653920093";

        //BasicAWSCredentials user2Credentials = new BasicAWSCredentials("<access_key>", "<secret_key>");

        BasicAWSCredentials user2Credentials = new BasicAWSCredentials("QL8Q1VOBCSJC5FZ2DMIU",
                "n6a82gyJZ04Z+Xqp7OgfqPtbbKqVc3UbuOTNrF+7");

        // service urls

        //TODO: add service URLs

        //String cqsServerUrl = "http://<host>:<port>";
        //String cnsServerUrl = "http://<host>:<port>";

        String cqsServerUrl = "http://localhost:6059";
        String cnsServerUrl = "http://localhost:6061";

        // initialize service

        AmazonSQSClient sqs = new AmazonSQSClient(user1Credentials);
        sqs.setEndpoint(cqsServerUrl);

        AmazonSNSClient sns = new AmazonSNSClient(user2Credentials);
        sns.setEndpoint(cnsServerUrl);

        // create queue

        Random randomGenerator = new Random();

        String queueName = QUEUE_PREFIX + randomGenerator.nextLong();

        HashMap<String, String> attributeParams = new HashMap<String, String>();
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
        createQueueRequest.setAttributes(attributeParams);
        String queueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

        AddPermissionRequest addPermissionRequest = new AddPermissionRequest();
        addPermissionRequest.setQueueUrl(queueUrl);
        addPermissionRequest.setActions(Arrays.asList("SendMessage"));
        addPermissionRequest.setLabel(UUID.randomUUID().toString());
        addPermissionRequest.setAWSAccountIds(Arrays.asList(user2Id));
        sqs.addPermission(addPermissionRequest);

        // create topic

        String topicName = "TSTT" + randomGenerator.nextLong();

        CreateTopicRequest createTopicRequest = new CreateTopicRequest(topicName);
        CreateTopicResult createTopicResult = sns.createTopic(createTopicRequest);
        String topicArn = createTopicResult.getTopicArn();

        // subscribe and confirm cqs endpoint

        SubscribeRequest subscribeRequest = new SubscribeRequest();
        String queueArn = getArnForQueueUrl(queueUrl);
        subscribeRequest.setEndpoint(queueArn);
        subscribeRequest.setProtocol("cqs");
        subscribeRequest.setTopicArn(topicArn);
        SubscribeResult subscribeResult = sns.subscribe(subscribeRequest);
        String subscriptionArn = subscribeResult.getSubscriptionArn();

        if (subscriptionArn.equals("pending confirmation")) {

            Thread.sleep(500);

            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
            receiveMessageRequest.setQueueUrl(queueUrl);
            receiveMessageRequest.setMaxNumberOfMessages(1);
            ReceiveMessageResult receiveMessageResult = sqs.receiveMessage(receiveMessageRequest);

            List<Message> messages = receiveMessageResult.getMessages();

            if (messages != null && messages.size() == 1) {

                JSONObject o = new JSONObject(messages.get(0).getBody());

                if (!o.has("SubscribeURL")) {
                    throw new Exception("message is not a confirmation messsage");
                }

                String subscriptionUrl = o.getString("SubscribeURL");
                httpGet(subscriptionUrl);

                DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
                deleteMessageRequest.setReceiptHandle(messages.get(0).getReceiptHandle());
                deleteMessageRequest.setQueueUrl(queueUrl);
                sqs.deleteMessage(deleteMessageRequest);

            } else {
                throw new Exception("no confirmation message found");
            }
        }

        // publish and receive message

        PublishRequest publishRequest = new PublishRequest();
        String messageText = "quamvis sint sub aqua, sub aqua maledicere temptant";
        publishRequest.setMessage(messageText);
        publishRequest.setSubject("unit test message");
        publishRequest.setTopicArn(topicArn);
        sns.publish(publishRequest);

        Thread.sleep(500);

        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
        receiveMessageRequest.setQueueUrl(queueUrl);
        receiveMessageRequest.setMaxNumberOfMessages(1);
        ReceiveMessageResult receiveMessageResult = sqs.receiveMessage(receiveMessageRequest);

        List<Message> messages = receiveMessageResult.getMessages();

        if (messages != null && messages.size() == 1) {

            String messageBody = messages.get(0).getBody();

            if (!messageBody.contains(messageText)) {
                throw new Exception("message text not found");
            }

            DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
            deleteMessageRequest.setReceiptHandle(messages.get(0).getReceiptHandle());
            deleteMessageRequest.setQueueUrl(queueUrl);
            sqs.deleteMessage(deleteMessageRequest);

        } else {
            throw new Exception("no messages found");
        }

        // subscribe and confirm http endpoint

        String id = randomGenerator.nextLong() + "";
        String endPointUrl = CMBTestingConstants.HTTP_ENDPOINT_BASE_URL + "recv/" + id;
        String lastMessageUrl = CMBTestingConstants.HTTP_ENDPOINT_BASE_URL + "info/" + id + "?showLast=true";

        subscribeRequest = new SubscribeRequest();
        subscribeRequest.setEndpoint(endPointUrl);
        subscribeRequest.setProtocol("http");
        subscribeRequest.setTopicArn(topicArn);
        subscribeResult = sns.subscribe(subscribeRequest);
        subscriptionArn = subscribeResult.getSubscriptionArn();

        if (subscriptionArn.equals("pending confirmation")) {

            Thread.sleep(500);

            String response = httpGet(lastMessageUrl);

            JSONObject o = new JSONObject(response);

            if (!o.has("SubscribeURL")) {
                throw new Exception("message is not a confirmation messsage");
            }

            String subscriptionUrl = o.getString("SubscribeURL");

            response = httpGet(subscriptionUrl);
        }

        // publish and receive message

        publishRequest = new PublishRequest();
        publishRequest.setMessage(messageText);
        publishRequest.setSubject("unit test message");
        publishRequest.setTopicArn(topicArn);
        sns.publish(publishRequest);

        Thread.sleep(500);

        String response = httpGet(lastMessageUrl);

        if (response != null && response.length() > 0) {

            if (!response.contains(messageText)) {
                throw new Exception("message text not found");
            }

        } else {
            throw new Exception("no messages found");
        }

        // delete queue and topic

        DeleteTopicRequest deleteTopicRequest = new DeleteTopicRequest(topicArn);
        sns.deleteTopic(deleteTopicRequest);

        sqs.deleteQueue(new DeleteQueueRequest(queueUrl));

        System.out.println("OK");

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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

License:Apache License

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

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

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

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

    String userId = request.getParameter("userId");
    String topicName = request.getParameter("topic");
    String arn = request.getParameter("arn");
    String displayName = request.getParameter("display");
    String nextToken = request.getParameter("nextToken");

    List<Topic> topics = new ArrayList<Topic>();

    connect(request);

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

        try {

            CreateTopicRequest createTopicRequest = new CreateTopicRequest(topicName);
            CreateTopicResult createTopicResult = sns.createTopic(createTopicRequest);

            arn = createTopicResult.getTopicArn();

            SetTopicAttributesRequest setTopicAttributesRequest = new SetTopicAttributesRequest(arn,
                    "DisplayName", displayName);
            sns.setTopicAttributes(setTopicAttributesRequest);

            logger.debug("event=create topic_name=" + topicName + " topic_arn=" + arn + " user_id=" + userId);

        } catch (Exception ex) {
            logger.error("event=create topic_name=" + topicName + " user_id=" + userId);
            throw new ServletException(ex);
        }

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

        try {
            DeleteTopicRequest deleteTopicRequest = new DeleteTopicRequest(arn);
            sns.deleteTopic(deleteTopicRequest);
            logger.debug("event=delete_topic topic_arn=" + arn + " user_id= " + userId);
        } catch (Exception ex) {
            logger.error("event=delete_topic topic_arn=" + arn + " user_id= " + userId, ex);
            throw new ServletException(ex);
        }

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

        try {

            ListTopicsRequest listTopicRequest = new ListTopicsRequest();

            if (nextToken != null) {
                listTopicRequest.setNextToken(nextToken);
            }

            ListTopicsResult listTopicResult = sns.listTopics(listTopicRequest);
            topics = listTopicResult.getTopics();

        } catch (Exception ex) {
            logger.error("event=list_topics user_id= " + userId, ex);
            throw new ServletException(ex);
        }

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

            Topic t = topics.get(i);

            try {
                DeleteTopicRequest deleteTopicRequest = new DeleteTopicRequest(t.getTopicArn());
                sns.deleteTopic(deleteTopicRequest);
                logger.debug("event=delete_topic topic_arn=" + (t != null ? t.getTopicArn() : "null")
                        + " user_id= " + userId);
            } catch (Exception ex) {
                logger.error("event=delete_topic topic_arn=" + (t != null ? t.getTopicArn() : "null")
                        + " user_id= " + userId, ex);
            }
        }
    }

    out.println("<html>");

    header(request, out, "Topics");

    out.println("<body>");

    out.println("<h2>Topics</h2>");

    long numTopics = 0;

    try {
        numTopics = PersistenceFactory.getUserPersistence().getNumUserTopics(userId);
    } catch (PersistenceException ex) {
        logger.warn("event=queue_count_failure", ex);
    }

    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>");
        out.println("<tr><td><b>Topic Count</b></td><td>" + numTopics + "</td></tr></table>");
    }

    out.println("<p><table>");
    out.println("<tr><td><b>Topic Name</b></td><td><b>Topic Display Name</b></td><td></td></tr>");
    out.println("<form action=\"/webui/cnsuser?userId=" + userId + "\" " + "method=POST>");
    out.println(
            "<tr><td><input type='text' name='topic' /></td><td><input type='text' name='display'><input type='hidden' name='userId' value='"
                    + userId
                    + "'></td><td><input type='submit' value='Create' name='Create' /></td></tr></form></table></p>");

    out.println("<p><table>");
    out.println("<form action=\"/webui/cnsuser?userId=" + userId + "\" " + "method=POST>");
    out.println("<tr><td><input type='hidden' name='userId' value='" + userId
            + "'></td><td><input type='submit' value='Delete All' name='DeleteAll' onclick=\"return confirm('Are you sure you want to delete all topics?')\" /></td></tr></form></table></p>");

    ListTopicsResult listTopicResult = null;

    try {

        ListTopicsRequest listTopicRequest = new ListTopicsRequest();

        if (nextToken != null) {
            listTopicRequest.setNextToken(nextToken);
        }

        listTopicResult = sns.listTopics(listTopicRequest);
        topics = listTopicResult.getTopics();

    } catch (Exception ex) {
        logger.error("event=list_topics user_id= " + userId, ex);
        throw new ServletException(ex);
    }

    out.println("<p><hr width='100%' align='left' /></p>");
    out.println("<p><table class = 'alternatecolortable' border='1'>");
    out.println("<tr><th>&nbsp;</th>");
    out.println("<th>Topic Arn</th>");
    out.println("<th>Topic Name</th>");
    out.println("<th>Topic Display Name</th>");
    out.println("<th>User ID</th>");
    out.println("<th>Subscriptions Pending</th>");
    out.println("<th>Subscriptions Confirmed</th>");
    out.println("<th>&nbsp;</th>");
    out.println("<th>&nbsp;</th>");
    out.println("<th>&nbsp;</th>");
    out.println("<th>&nbsp;</th>");
    out.println("<th>&nbsp;</th></tr>");

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

        Topic t = topics.get(i);

        GetTopicAttributesRequest getTopicAttributesRequest = new GetTopicAttributesRequest(t.getTopicArn());
        GetTopicAttributesResult getTopicAttributesResult = sns.getTopicAttributes(getTopicAttributesRequest);
        Map<String, String> attributes = getTopicAttributesResult.getAttributes();

        out.println("<tr>");
        out.println("<form action=\"/webui/cnsuser?userId=" + userId + "\" method=POST>");
        out.println("<td>" + i + "</td>");
        out.println("<td>" + t.getTopicArn() + "<input type='hidden' name='arn' value=" + t.getTopicArn()
                + "></td>");
        out.println("<td>" + Util.getNameFromTopicArn(t.getTopicArn()) + "</td>");
        out.println("<td><a href='' onclick=\"window.open('/webui/cnsuser/editdisplayname?topicArn="
                + t.getTopicArn() + "&userId=" + userId
                + "', 'EditDisplayName', 'height=300,width=700,toolbar=no')\">"
                + (attributes.get("DisplayName") == null ? "{unset}" : attributes.get("DisplayName"))
                + "</a></td>");
        out.println("<td>" + user.getUserId() + "<input type='hidden' name='userId' value=" + user.getUserId()
                + "></td>");
        out.println("<td>" + attributes.get("SubscriptionsPending") + "</td>");
        out.println("<td>" + attributes.get("SubscriptionsConfirmed") + "</td>");
        out.println("<td><a href='/webui/cnsuser/subscription?userId=" + userId + "&topicArn=" + t.getTopicArn()
                + "'>Subscriptions</a></td>");
        out.println("<td><a href='/webui/cnsuser/publish?userId=" + userId + "&topicArn=" + t.getTopicArn()
                + "' target='_blank'>Publish</a></td>");
        out.println("<td><a href='' onclick=\"window.open('/webui/cnsuser/editdeliverypolicy?topicArn="
                + t.getTopicArn() + "&userId=" + userId
                + "', 'EditDeliveryPolicy', 'height=630,width=580,toolbar=no')\">View/Edit Topic Delivery Policy</a></td>");
        out.println("<td><a href='/webui/cnsuser/permission?topicArn=" + t.getTopicArn() + "&userId=" + userId
                + "'>Permission</a></td>");
        out.println(
                "<td><input type='submit' value='Delete' name='Delete' onclick=\"return confirm('Are you sure you want to delete topic "
                        + Util.getNameFromTopicArn(t.getTopicArn()) + "?')\" /></td></form></tr>");
    }

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

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

    out.println("<h5 style='text-align:center;'><a href='/webui'>ADMIN HOME</a></h5>");
    out.println("</body></html>");

    CMBControllerServlet.valueAccumulator.deleteAllCounters();
}

From source file:com.dev.appx.sns.SNSMobilePush.java

License:Open Source License

public void createTopic(String topic) throws IOException {
    //create a new SNS client and set endpoint
    AmazonSNSClient snsClient = new AmazonSNSClient(new ClasspathPropertiesFileCredentialsProvider());

    /*AmazonSNS snsClient = new AmazonSNSClient(new PropertiesCredentials(
    SNSMobilePush.class// w  ww.  ja v  a2  s.co m
          .getResourceAsStream("AwsCredentials.properties")));*/

    snsClient.setRegion(Region.getRegion(Regions.US_EAST_1));

    //create a new SNS topic
    CreateTopicRequest createTopicRequest = new CreateTopicRequest(topic);
    CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest);
    //print TopicArn
    System.out.println(createTopicResult);
    //get request id for CreateTopicRequest from SNS metadata      
    System.out.println("CreateTopicRequest - " + snsClient.getCachedResponseMetadata(createTopicRequest));
}

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

License:Open Source License

/**
 * {@inheritDoc}//  w w  w  .java  2  s.c o m
 */
@Override
public CreateTopicResult createTopic(AmazonSNS client, SNSTopicRequest topicRequest) {
    if (topicRequest == null) {
        return null;
    }
    // create a new SNS topic
    CreateTopicRequest createTopicRequest = new CreateTopicRequest(topicRequest.getSnsName());
    CreateTopicResult result = client.createTopic(createTopicRequest);

    return result;
}

From source file:com.pocketdealhunter.HotDealsMessagesUtil.java

License:Open Source License

protected String createTopic() {
    try {/*  w w w . jav a  2  s  .  c  o  m*/
        CreateTopicRequest ctr = new CreateTopicRequest(Constants.TOPIC_NAME);
        CreateTopicResult result = snsClient.createTopic(ctr);

        // Adding the DisplayName attribute to the Topic allows for SMS
        // notifications.
        SetTopicAttributesRequest tar = new SetTopicAttributesRequest(result.getTopicArn(), "DisplayName",
                "MessageBoard");
        this.snsClient.setTopicAttributes(tar);

        return result.getTopicArn();
    } catch (Exception exception) {
        System.out.println("Exception  = " + exception);
        return null;
    }
}

From source file:net.smartcosmos.plugin.service.aws.notification.AwsNotificationService.java

License:Apache License

@Override
public String createTopic(INotificationEndpoint notificationEndpoint) {
    Preconditions.checkArgument((notificationEndpoint != null), "Notification endpoint must not be null");

    Preconditions.checkArgument((notificationEndpoint.getTopicArn() == null),
            "Notification already has a notification URL defined");

    AmazonSNS sns = new AmazonSNSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sns.setRegion(usEast1);//from ww  w  . j av a  2 s  . com

    String topicArn = null;

    try {
        String topicName = stripUrnUuidPrefix(notificationEndpoint.getAccount());

        LOG.info("Topic Name Assigned: " + topicName);

        CreateTopicRequest request = new CreateTopicRequest(topicName);
        CreateTopicResult result = sns.createTopic(request);

        topicArn = result.getTopicArn();

        //
        // Event
        //
        INotificationResultObject<IAccount> nro = new NotificationResultObject<>(EntityReferenceType.Account,
                notificationEndpoint.getAccount(), result.getTopicArn());
        IEventService eventService = context.getServiceFactory()
                .getEventService(notificationEndpoint.getAccount());
        eventService.recordEvent(EventType.NotificationEnroll, notificationEndpoint.getAccount(), null, nro);

    } finally {
        sns.shutdown();
    }

    return topicArn;
}