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

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

Introduction

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

Prototype

public PublishRequest() 

Source Link

Document

Default constructor for PublishRequest object.

Usage

From source file:com.cloudbees.gasp.services.SNSMobile.java

License:Open Source License

private PublishResult apnPublish(String endpointArn, Platform platform, String theMessage) {
    PublishRequest publishRequest = new PublishRequest();
    Map<String, String> messageMap = new HashMap<String, String>();
    String message;//from  ww  w .  j  a  v  a  2 s  .c om
    messageMap.put("default", defaultMessage);
    messageMap.put(platform.name(), theMessage);
    // For direct publish to mobile end points, topicArn is not relevant.
    publishRequest.setTargetArn(endpointArn);
    publishRequest.setMessageStructure("json");
    message = jsonify(messageMap);

    // Display the message that will be sent to the endpoint/
    LOGGER.debug(message);

    publishRequest.setMessage(message);
    return snsClient.publish(publishRequest);
}

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

License:Apache License

public static void main(String[] args) {

    try {//from  w w w  .  j ava2s. c o 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.dev.appx.sns.tools.AmazonSNSClientWrapper.java

License:Open Source License

public PublishResult publish(String endpointArn, Platform platform,
        Map<Platform, Map<String, MessageAttributeValue>> attributesMap) {
    PublishRequest publishRequest = new PublishRequest();
    Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes(
            attributesMap.get(platform));
    if (notificationAttributes != null && !notificationAttributes.isEmpty()) {
        publishRequest.setMessageAttributes(notificationAttributes);
    }/*from  w  w  w  . ja  va2 s. co m*/
    publishRequest.setMessageStructure("json");
    // If the message attributes are not set in the requisite method,
    // notification is sent with default attributes
    String message = getPlatformSampleMessage(platform);
    Map<String, String> messageMap = new HashMap<String, String>();
    messageMap.put(platform.name(), message);
    message = SampleMessageGenerator.jsonify(messageMap);
    // For direct publish to mobile end points, topicArn is not relevant.
    publishRequest.setTargetArn(endpointArn);

    // Display the message that will be sent to the endpoint/
    System.out.println("{Message Body: " + message + "}");
    StringBuilder builder = new StringBuilder();
    builder.append("{Message Attributes: ");
    for (Map.Entry<String, MessageAttributeValue> entry : notificationAttributes.entrySet()) {
        builder.append("(\"" + entry.getKey() + "\": \"" + entry.getValue().getStringValue() + "\"),");
    }
    builder.deleteCharAt(builder.length() - 1);
    builder.append("}");
    System.out.println(builder.toString());

    publishRequest.setMessage(message);
    return snsClient.publish(publishRequest);
}

From source file:com.gafful.AmazonSNSClientWrapper.java

License:Open Source License

private PublishResult publish(String endpointArn, Platform platform,
        Map<Platform, Map<String, MessageAttributeValue>> attributesMap) {
    PublishRequest publishRequest = new PublishRequest();
    Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes(
            attributesMap.get(platform));
    if (notificationAttributes != null && !notificationAttributes.isEmpty()) {
        publishRequest.setMessageAttributes(notificationAttributes);
    }// ww  w.  j  a va 2 s.c  o  m
    publishRequest.setMessageStructure("json");
    // If the message attributes are not set in the requisite method,
    // notification is sent with default attributes
    String message = getPlatformSampleMessage(platform);
    Map<String, String> messageMap = new HashMap<String, String>();
    messageMap.put(platform.name(), message);
    message = SampleMessageGenerator.jsonify(messageMap);
    // For direct publish to mobile end points, topicArn is not relevant.
    publishRequest.setTargetArn(endpointArn);

    // Display the message that will be sent to the endpoint/
    System.out.println("{Message Body: " + message + "}");
    StringBuilder builder = new StringBuilder();
    builder.append("{Message Attributes: ");
    for (Map.Entry<String, MessageAttributeValue> entry : notificationAttributes.entrySet()) {
        builder.append("(\"" + entry.getKey() + "\": \"" + entry.getValue().getStringValue() + "\"),");
    }
    builder.deleteCharAt(builder.length() - 1);
    builder.append("}");
    System.out.println(builder.toString());

    publishRequest.setMessage(message);
    return snsClient.publish(publishRequest);
}

From source file:com.logpig.mweagle.rolling.S3RollingFileAppender.java

License:Apache License

private void writeErrorMessage(String message) {
    final String __subject = "[ERROR] S3RollingFileAppender";
    System.err.println(String.format("%s - %s", __subject, message));
    try {//from   www  .  j  a va 2s .  com
        final AmazonSNS snsClient = new AmazonSNSClient(s3Settings.getAWSCredentials());
        final PublishRequest __request = new PublishRequest().withTopicArn(s3Settings.getSnsTopicArn())
                .withMessage(message).withSubject(__subject);
        snsClient.publish(__request);
    } catch (Exception e) {
        System.err.println(String.format(
                "[ERROR] Unable to send notification of S3RollingFileAppender failure. %s", e.getMessage()));
    }
}

From source file:com.mistminds.service.AmazonSNSClientWrapper.java

License:Open Source License

private PublishResult publish(String endpointArn, Platform platform,
        Map<Platform, Map<String, MessageAttributeValue>> attributesMap, Map<String, String> pushData) {
    PublishRequest publishRequest = new PublishRequest();
    Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes(
            attributesMap.get(platform));
    if (notificationAttributes != null && !notificationAttributes.isEmpty()) {
        publishRequest.setMessageAttributes(notificationAttributes);
    }/*from  w ww.  j  a v a2s .  c o m*/
    publishRequest.setMessageStructure("json");
    // If the message attributes are not set in the requisite method,
    // notification is sent with default attributes
    String message = SampleMessageGenerator.getSampleAndroidMessage(pushData);
    Map<String, String> messageMap = new HashMap<String, String>();
    messageMap.put("default", message);
    message = SampleMessageGenerator.jsonify(messageMap);
    // For direct publish to mobile end points, topicArn is not relevant.
    publishRequest.setTargetArn(endpointArn);

    // Display the message that will be sent to the endpoint/
    System.out.println("{Message Body: " + message + "}");
    StringBuilder builder = new StringBuilder();
    builder.append("{Message Attributes: ");
    for (Map.Entry<String, MessageAttributeValue> entry : notificationAttributes.entrySet()) {
        builder.append("(\"" + entry.getKey() + "\": \"" + entry.getValue().getStringValue() + "\"),");
    }
    builder.deleteCharAt(builder.length() - 1);
    builder.append("}");
    System.out.println(builder.toString());

    publishRequest.setMessage(message);
    return snsClient.publish(publishRequest);
}

From source file:com.onemenu.server.util.awsnotification.tools.AmazonSNSClientWrapper.java

License:Open Source License

private PublishResult publish(String endpointArn, Platform platform,
        Map<Platform, Map<String, MessageAttributeValue>> attributesMap, String message) {
    PublishRequest publishRequest = new PublishRequest();
    Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes(
            attributesMap.get(platform));
    if (notificationAttributes != null && !notificationAttributes.isEmpty()) {
        publishRequest.setMessageAttributes(notificationAttributes);
    }//from w w  w  .  ja  va  2 s .c  om
    publishRequest.setMessageStructure("json");
    // If the message attributes are not set in the requisite method,
    // notification is sent with default attributes
    Map<String, String> messageMap = new HashMap<String, String>();
    messageMap.put(platform.name(), message);
    message = MessageGenerator.jsonify(messageMap);
    // For direct publish to mobile end points, topicArn is not relevant.
    publishRequest.setTargetArn(endpointArn);

    // Display the message that will be sent to the endpoint/
    System.out.println("{Message Body: " + message + "}");
    StringBuilder builder = new StringBuilder();
    builder.append("{Message Attributes: ");
    for (Map.Entry<String, MessageAttributeValue> entry : notificationAttributes.entrySet()) {
        builder.append("(\"" + entry.getKey() + "\": \"" + entry.getValue().getStringValue() + "\"),");
    }
    builder.deleteCharAt(builder.length() - 1);
    builder.append("}");
    System.out.println(builder.toString());

    publishRequest.setMessage(message);
    return snsClient.publish(publishRequest);
}

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

License:Open Source License

private PublishResult publish(String endpointArn, SampleMessageGenerator.Platform platform,
        Map<SampleMessageGenerator.Platform, Map<String, MessageAttributeValue>> attributesMap) {
    PublishRequest publishRequest = new PublishRequest();
    Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes(
            attributesMap.get(platform));
    if (notificationAttributes != null && !notificationAttributes.isEmpty()) {
        publishRequest.setMessageAttributes(notificationAttributes);
    }//from w  ww . jav  a2s. c o  m
    publishRequest.setMessageStructure("json");
    // If the message attributes are not set in the requisite method,
    // notification is sent with default attributes
    String message = getPlatformSampleMessage(platform);
    Map<String, String> messageMap = new HashMap<String, String>();
    messageMap.put(platform.name(), message);
    message = SampleMessageGenerator.jsonify(messageMap);
    // For direct publish to mobile end points, topicArn is not relevant.
    publishRequest.setTargetArn(endpointArn);

    // Display the message that will be sent to the endpoint/
    System.out.println("{Message Body: " + message + "}");
    StringBuilder builder = new StringBuilder();
    builder.append("{Message Attributes: ");
    for (Map.Entry<String, MessageAttributeValue> entry : notificationAttributes.entrySet()) {
        builder.append("(\"" + entry.getKey() + "\": \"" + entry.getValue().getStringValue() + "\"),");
    }
    builder.deleteCharAt(builder.length() - 1);
    builder.append("}");
    System.out.println(builder.toString());

    publishRequest.setMessage(message);

    return snsClient.publish(publishRequest);
}

From source file:com.zotoh.cloudapi.aws.SNS.java

License:Open Source License

@Override
public String publish(String topic, String subject, String message) throws CloudException, InternalException {
    tstEStrArg("message", message);
    tstEStrArg("topic-name", topic);
    tstEStrArg("subject", subject);
    PublishResult res = _svc.getCloud().getSNS()
            .publish(new PublishRequest().withTopicArn(topic).withSubject(subject).withMessage(message));
    return res == null ? null : res.getMessageId();
}

From source file:edu.utn.frba.grupo5303.serverenviolibre.services.NotificacionesPushService.java

@Override
public void enviarNotificacion(NotificacionPush notificacion) {
    try {//from w  w w. jav  a2s  .com
        logger.log(Level.INFO, "Enviando notificacion al snsId: {0}", notificacion.getGcmIdDestino());
        logger.log(Level.INFO, "Enviando notificacion de tipo: {0}", notificacion.getCodigo());
        PublishRequest publishRequest = new PublishRequest();
        Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes(
                attributesMap.get(plataforma));
        if (notificationAttributes != null && !notificationAttributes.isEmpty()) {
            publishRequest.setMessageAttributes(notificationAttributes);
        }
        publishRequest.setMessageStructure("json");
        // If the message attributes are not set in the requisite method,
        // notification is sent with default attributes
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put(plataforma.name(), notificacion.getMensajeDeNotificacion());
        String message = SampleMessageGenerator.jsonify(messageMap);

        // Create Platform Application. This corresponds to an app on a
        // platform.
        CreatePlatformApplicationResult platformApplicationResult = createPlatformApplication();

        // 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("CustomData",
                notificacion.getGcmIdDestino(), platformApplicationArn);

        // For direct publish to mobile end points, topicArn is not relevant.
        publishRequest.setTargetArn(platformEndpointResult.getEndpointArn());

        publishRequest.setMessage(message);
        snsClient.publish(publishRequest);
    } catch (AmazonServiceException ase) {
        logger.log(Level.SEVERE, "Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SNS, but was rejected with an error response for some reason.");
        logger.log(Level.SEVERE, "Error Message:    {0}", ase.getMessage());
        logger.log(Level.SEVERE, "HTTP Status Code: {0}", ase.getStatusCode());
        logger.log(Level.SEVERE, "AWS Error Code:   {0}", ase.getErrorCode());
        logger.log(Level.SEVERE, "Error Type:       {0}", ase.getErrorType());
        logger.log(Level.SEVERE, "Request ID:       {0}", ase.getRequestId());
    } catch (AmazonClientException ace) {
        logger.log(Level.SEVERE,
                "Caught an AmazonClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with SNS, such as not "
                        + "being able to access the network.");
        logger.log(Level.SEVERE, "Error Message: {0}", ace.getMessage());
    }
}