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

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

Introduction

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

Prototype


public void setMessage(String message) 

Source Link

Document

The message you want to send.

Usage

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   ww  w  .j  a v  a2 s.  c  o m
    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 . j a va2s  .  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:edu.utn.frba.grupo5303.serverenviolibre.services.NotificacionesPushService.java

@Override
public void enviarNotificacion(NotificacionPush notificacion) {
    try {//ww w.  j  a va2 s. 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());
    }
}

From source file:io.macgyver.plugin.cloud.aws.event.SNSMacGyverEventWriter.java

License:Apache License

public void subscribe(EventSystem eventSystem) {

    Consumer consumer = new Consumer() {
        public void accept(Object event) {

            try {
                if (isEnabled()) {
                    PublishRequest request = new PublishRequest();
                    request.setTopicArn(getTopicArn().get());
                    request.setMessage(MacGyverMessage.class.cast(event).getEnvelope().toString());
                    getSNSClient().get().publishAsync(request, new ResponseHandler());
                }//from w  ww .j a  va2s.  c om
            } catch (Exception e) {
                logger.error("problem sending message to SNS: {}", e.toString());
            }
        }
    };
    ConcurrentSubscribers.createConcurrentSubscriber(eventSystem.createObservable(MacGyverMessage.class))
            .withNewExecutor(b -> {
                b.withThreadPoolSize(2).withThreadNameFormat("SNSMacGyverEventWriter-%d");
            }).subscribe(consumer);

}

From source file:io.starter.messaging.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()) {

        // TODO: link to updated SNS lib
        //   publishRequest.setMessageAttributes(notificationAttributes);
    }//ww  w .j  av a 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
    if (message == null)
        message = getPlatformStarterMessage(platform);

    Map<String, String> messageMap = new HashMap<String, String>();
    messageMap.put(platform.name(), message);
    message = NotificationMessageGenerator.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:org.apache.camel.component.aws.sns.SnsProducer.java

License:Apache License

public void process(Exchange exchange) throws Exception {
    PublishRequest request = new PublishRequest();
    request.setTopicArn(getConfiguration().getTopicArn());
    request.setMessage(exchange.getIn().getBody(String.class));
    request.setSubject(determineSubject(exchange));

    LOG.trace("Sending request [{}] from exchange [{}]...", request, exchange);

    PublishResult result = getEndpoint().getSNSClient().publish(request);

    LOG.trace("Received result [{}]", result);

    Message message = getMessageForResponse(exchange);
    message.setHeader(SnsConstants.MESSAGE_ID, result.getMessageId());
}

From source file:org.apache.nifi.processors.aws.sns.PutSNS.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    FlowFile flowFile = session.get();/*from   w w w .ja  v a2s .  com*/
    if (flowFile == null) {
        return;
    }

    if (flowFile.getSize() > MAX_SIZE) {
        getLogger().error(
                "Cannot publish {} to SNS because its size exceeds Amazon SNS's limit of 256KB; routing to failure",
                new Object[] { flowFile });
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    final Charset charset = Charset
            .forName(context.getProperty(CHARACTER_ENCODING).evaluateAttributeExpressions(flowFile).getValue());

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    session.exportTo(flowFile, baos);
    final String message = new String(baos.toByteArray(), charset);

    final AmazonSNSClient client = getClient();
    final PublishRequest request = new PublishRequest();
    request.setMessage(message);

    if (context.getProperty(USE_JSON_STRUCTURE).asBoolean()) {
        request.setMessageStructure("json");
    }

    final String arn = context.getProperty(ARN).evaluateAttributeExpressions(flowFile).getValue();
    final String arnType = context.getProperty(ARN_TYPE).getValue();
    if (arnType.equalsIgnoreCase(ARN_TYPE_TOPIC.getValue())) {
        request.setTopicArn(arn);
    } else {
        request.setTargetArn(arn);
    }

    final String subject = context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue();
    if (subject != null) {
        request.setSubject(subject);
    }

    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (entry.getKey().isDynamic() && !StringUtils.isEmpty(entry.getValue())) {
            final MessageAttributeValue value = new MessageAttributeValue();
            value.setStringValue(
                    context.getProperty(entry.getKey()).evaluateAttributeExpressions(flowFile).getValue());
            value.setDataType("String");
            request.addMessageAttributesEntry(entry.getKey().getName(), value);
        }
    }

    try {
        client.publish(request);
        session.transfer(flowFile, REL_SUCCESS);
        session.getProvenanceReporter().send(flowFile, arn);
        getLogger().info("Successfully published notification for {}", new Object[] { flowFile });
    } catch (final Exception e) {
        getLogger().error("Failed to publish Amazon SNS message for {} due to {}",
                new Object[] { flowFile, e });
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:org.springframework.integration.aws.outbound.SnsMessageHandler.java

License:Apache License

@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
    Object payload = requestMessage.getPayload();

    PublishRequest publishRequest = null;

    if (payload instanceof PublishRequest) {
        publishRequest = (PublishRequest) payload;
    } else {/*from   w w  w.  jav  a 2  s . co  m*/
        Assert.state(this.topicArnExpression != null, "'topicArn' or 'topicArnExpression' must be specified.");
        publishRequest = new PublishRequest();
        String topicArn = this.topicArnExpression.getValue(this.evaluationContext, requestMessage,
                String.class);
        if (this.resourceIdResolver != null) {
            topicArn = this.resourceIdResolver.resolveToPhysicalResourceId(topicArn);
        }
        publishRequest.setTopicArn(topicArn);

        if (this.subjectExpression != null) {
            String subject = this.subjectExpression.getValue(this.evaluationContext, requestMessage,
                    String.class);
            publishRequest.setSubject(subject);
        }

        Object snsMessage = requestMessage.getPayload();

        if (this.bodyExpression != null) {
            snsMessage = this.bodyExpression.getValue(this.evaluationContext, requestMessage);
        }

        if (snsMessage instanceof SnsBodyBuilder) {
            publishRequest.withMessageStructure("json").setMessage(((SnsBodyBuilder) snsMessage).build());
        } else {
            publishRequest.setMessage(getConversionService().convert(snsMessage, String.class));
        }
    }

    PublishResult publishResult = this.amazonSns.publish(publishRequest);

    if (this.produceReply) {
        return getMessageBuilderFactory().withPayload(publishRequest)
                .setHeader(AwsHeaders.TOPIC, publishRequest.getTopicArn())
                .setHeader(AwsHeaders.SNS_PUBLISHED_MESSAGE_ID, publishResult.getMessageId());
    } else {
        return null;
    }
}

From source file:tools.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);
    }//from   w w  w.ja  v  a2s .  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);

    PublishResult result = null;
    try {
        result = snsClient.publish(publishRequest);
    } catch (EndpointDisabledException e) {
        System.out.println("Endpoint disabled:  TODO remove from dynamo DB");
    } catch (Exception e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }

    return result;
}