com.amazonaws.services.sns.model.MessageAttributeValue Java Examples

The following examples show how to use com.amazonaws.services.sns.model.MessageAttributeValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TerraformLaunchRequestHandler.java    From aws-service-catalog-terraform-reference-architecture with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) {
    MessageAttributeValue accountIdValue = new MessageAttributeValue()
            .withDataType("String")
            .withStringValue(getAccountId(context));
    Map<String, MessageAttributeValue> messageAttributes =
            ImmutableMap.of(ACCOUNT_ID_ATTRIBUTE_KEY, accountIdValue);

    String hubSnsTopicArn = EnvConfig.getRequiredEnv(HUB_SNS_ARN_ENV_VAR);
    String cfnRequest = toRequestString(inputStream);

    try {
        publishNotification(hubSnsTopicArn, cfnRequest, messageAttributes);
    } catch (RuntimeException e) {
        CustomResourceRequest request = CustomResourceMarshaller.readCustomResourceRequest(cfnRequest, true);
        String message = String.format("Unable to publish SNS notification to hub account SNS topic. %s",
                                        e.getMessage());
        ResponsePoster.postFailure(request, message);
    }
}
 
Example #2
Source File: SnsDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public PublishResult publish(AwsParamsDto awsParamsDto, String topicArn, String messageText, List<MessageHeader> messageHeaders)
{
    Map<String, MessageAttributeValue> messageAttributes = null;

    if (CollectionUtils.isNotEmpty(messageHeaders))
    {
        messageAttributes = new HashMap<>();

        for (MessageHeader messageHeader : messageHeaders)
        {
            messageAttributes.put(messageHeader.getKey(), new MessageAttributeValue().withDataType("String").withStringValue(messageHeader.getValue()));
        }
    }

    return snsOperations.publish(topicArn, messageText, messageAttributes, awsClientFactory.getAmazonSNSClient(awsParamsDto));
}
 
Example #3
Source File: PushSnsService.java    From oxAuth with MIT License 6 votes vote down vote up
public PublishResult sendPushMessage(AmazonSNS snsClient, PushPlatform platform, String targetArn, Map<String, Object> customAppMessageMap, Map<String, MessageAttributeValue> messageAttributes) throws IOException {
	Map<String, Object> appMessageMap = new HashMap<String, Object>();

	if (platform == PushPlatform.GCM) {
		appMessageMap.put("collapse_key", "single");
		appMessageMap.put("delay_while_idle", true);
		appMessageMap.put("time_to_live", 30);
		appMessageMap.put("dry_run", false);
	}

	if (customAppMessageMap != null) {
		appMessageMap.putAll(customAppMessageMap);
	}

	String message = ServerUtil.asJson(appMessageMap);

	return sendPushMessage(snsClient, platform, targetArn, message, messageAttributes);
}
 
Example #4
Source File: PushSnsService.java    From oxAuth with MIT License 6 votes vote down vote up
public PublishResult sendPushMessage(AmazonSNS snsClient, PushPlatform platform, String targetArn, String message,
		Map<String, MessageAttributeValue> messageAttributes) throws IOException {
	Map<String, String> messageMap = new HashMap<String, String>();
	messageMap.put(platform.name(), message);
	message = ServerUtil.asJson(messageMap);

    PublishRequest publishRequest = new PublishRequest();
	publishRequest.setMessageStructure("json");
	
	if (messageAttributes != null) {
		publishRequest.setMessageAttributes(messageAttributes);
	}

	publishRequest.setTargetArn(targetArn);
	publishRequest.setMessage(message);

	PublishResult publishResult = snsClient.publish(publishRequest);

	return publishResult;
}
 
Example #5
Source File: TerraformLaunchRequestHandler.java    From aws-service-catalog-terraform-reference-architecture with Apache License 2.0 5 votes vote down vote up
private void publishNotification(String hubSnsTopicArn, String cfnRequest,
                                 Map<String, MessageAttributeValue> messageAttributes) {
    String region = ArnParser.getRegion(hubSnsTopicArn);
    AmazonSNS sns = AmazonSNSClientBuilder.standard()
            .withRegion(region)
            .build();
    sns.publish(new PublishRequest()
            .withTopicArn(hubSnsTopicArn)
            .withMessage(cfnRequest)
            .withSubject("AWS CloudFormation custom resource request with requester AccountId")
            .withMessageAttributes(messageAttributes)
    );
}
 
Example #6
Source File: SNSPublishStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected Void run() throws Exception {
	final String topicArn = this.step.getTopicArn();
	final String subject = this.step.getSubject();
	final String message = this.step.getMessage();
	final Map<String, String> messageAttributes = this.step.getMessageAttributes();

	TaskListener listener = this.getContext().get(TaskListener.class);
	AmazonSNS snsClient = AWSClientFactory.create(AmazonSNSClientBuilder.standard(), this.getContext());

	listener.getLogger().format("Publishing notification %s to %s %n", subject, topicArn);

	PublishRequest publishRequest = new PublishRequest()
			.withTopicArn(topicArn).withMessage(message).withSubject(subject);

	if (messageAttributes != null && !messageAttributes.isEmpty()) {
		for (Map.Entry<String, String> entry : messageAttributes.entrySet()) {
			MessageAttributeValue value = new MessageAttributeValue();
			value.setStringValue(entry.getValue());
			value.setDataType(STRING_DATATYPE);
			publishRequest.addMessageAttributesEntry(entry.getKey(), value);
		}
	}

	PublishResult result = snsClient.publish(publishRequest);

	listener.getLogger().format("Message published as %s %n", result.getMessageId());
	return null;
}
 
Example #7
Source File: TopicMessageChannel.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private MessageAttributeValue getNumberMessageAttribute(Object messageHeaderValue) {
	Assert.isTrue(
			NumberUtils.STANDARD_NUMBER_TYPES.contains(messageHeaderValue.getClass()),
			"Only standard number types are accepted as message header.");

	return new MessageAttributeValue()
			.withDataType(MessageAttributeDataTypes.NUMBER + "."
					+ messageHeaderValue.getClass().getName())
			.withStringValue(messageHeaderValue.toString());
}
 
Example #8
Source File: TopicMessageChannel.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private MessageAttributeValue getContentTypeMessageAttribute(
		Object messageHeaderValue) {
	if (messageHeaderValue instanceof MimeType) {
		return new MessageAttributeValue()
				.withDataType(MessageAttributeDataTypes.STRING)
				.withStringValue(messageHeaderValue.toString());
	}
	else if (messageHeaderValue instanceof String) {
		return new MessageAttributeValue()
				.withDataType(MessageAttributeDataTypes.STRING)
				.withStringValue((String) messageHeaderValue);
	}
	return null;
}
 
Example #9
Source File: SnsTopicResource.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
/**
 * Publish a message with subject to the AWS SNS topic.
 * @param subject "Subject" line of message to publish
 * @param message Content of message to publish
 * @throws AmazonClientException
 */
public void publish(final String subject, final String message) throws AmazonClientException {
    // Auto setting the subject as a message attribute to support sns message filtering by subject
    final Map<String, MessageAttributeValue> attributes = new HashMap<String, MessageAttributeValue>();
    attributes.put("subject", new MessageAttributeValue().withDataType("String").withStringValue(subject));

    final PublishRequest request = new PublishRequest().withTopicArn(topicArn).withSubject(subject)
            .withMessage(message).withMessageAttributes(attributes);
    amazonSnsClient.publish(request);
}
 
Example #10
Source File: TopicMessageChannel.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean sendInternal(Message<?> message, long timeout) {
	PublishRequest publishRequest = new PublishRequest(this.topicArn,
			message.getPayload().toString(), findNotificationSubject(message));
	Map<String, MessageAttributeValue> messageAttributes = getMessageAttributes(
			message);
	if (!messageAttributes.isEmpty()) {
		publishRequest.withMessageAttributes(messageAttributes);
	}
	this.amazonSns.publish(publishRequest);

	return true;
}
 
Example #11
Source File: TopicMessageChannel.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private Map<String, MessageAttributeValue> getMessageAttributes(Message<?> message) {
	HashMap<String, MessageAttributeValue> messageAttributes = new HashMap<>();
	for (Map.Entry<String, Object> messageHeader : message.getHeaders().entrySet()) {
		String messageHeaderName = messageHeader.getKey();
		Object messageHeaderValue = messageHeader.getValue();

		if (MessageHeaders.CONTENT_TYPE.equals(messageHeaderName)
				&& messageHeaderValue != null) {
			messageAttributes.put(messageHeaderName,
					getContentTypeMessageAttribute(messageHeaderValue));
		}
		else if (MessageHeaders.ID.equals(messageHeaderName)
				&& messageHeaderValue != null) {
			messageAttributes.put(messageHeaderName,
					getStringMessageAttribute(messageHeaderValue.toString()));
		}
		else if (messageHeaderValue instanceof String) {
			messageAttributes.put(messageHeaderName,
					getStringMessageAttribute((String) messageHeaderValue));
		}
		else if (messageHeaderValue instanceof Number) {
			messageAttributes.put(messageHeaderName,
					getNumberMessageAttribute(messageHeaderValue));
		}
		else if (messageHeaderValue instanceof ByteBuffer) {
			messageAttributes.put(messageHeaderName,
					getBinaryMessageAttribute((ByteBuffer) messageHeaderValue));
		}
		else {
			this.logger.warn(String.format(
					"Message header with name '%s' and type '%s' cannot be sent as"
							+ " message attribute because it is not supported by SNS.",
					messageHeaderName, messageHeaderValue != null
							? messageHeaderValue.getClass().getName() : ""));
		}
	}

	return messageAttributes;
}
 
Example #12
Source File: PutSNS.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    FlowFile flowFile = session.get();
    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);
    }
}
 
Example #13
Source File: SnsNotificationSender.java    From data-highway with Apache License 2.0 4 votes vote down vote up
private MessageAttributeValue attributeStringValue(String value) {
  return new MessageAttributeValue().withDataType("String").withStringValue(value);
}
 
Example #14
Source File: TopicMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void sendMessage_withNumericMessageHeaders_shouldBeSentAsTopicMessageAttributes()
		throws Exception {
	// Arrange
	AmazonSNS amazonSns = mock(AmazonSNS.class);
	ArgumentCaptor<PublishRequest> publishRequestArgumentCaptor = ArgumentCaptor
			.forClass(PublishRequest.class);
	when(amazonSns.publish(publishRequestArgumentCaptor.capture()))
			.thenReturn(new PublishResult());

	double doubleValue = 1234.56;
	long longValue = 1234L;
	int integerValue = 1234;
	byte byteValue = 2;
	short shortValue = 12;
	float floatValue = 1234.56f;
	BigInteger bigIntegerValue = new BigInteger("616416546156");
	BigDecimal bigDecimalValue = new BigDecimal("7834938");

	Message<String> message = MessageBuilder.withPayload("Hello")
			.setHeader("double", doubleValue).setHeader("long", longValue)
			.setHeader("integer", integerValue).setHeader("byte", byteValue)
			.setHeader("short", shortValue).setHeader("float", floatValue)
			.setHeader("bigInteger", bigIntegerValue)
			.setHeader("bigDecimal", bigDecimalValue).build();
	MessageChannel messageChannel = new TopicMessageChannel(amazonSns, "topicArn");

	// Act
	boolean sent = messageChannel.send(message);

	// Assert
	assertThat(sent).isTrue();
	Map<String, MessageAttributeValue> messageAttributes = publishRequestArgumentCaptor
			.getValue().getMessageAttributes();
	assertThat(messageAttributes.get("double").getDataType())
			.isEqualTo(MessageAttributeDataTypes.NUMBER + ".java.lang.Double");
	assertThat(messageAttributes.get("double").getStringValue())
			.isEqualTo(String.valueOf(doubleValue));
	assertThat(messageAttributes.get("long").getDataType())
			.isEqualTo(MessageAttributeDataTypes.NUMBER + ".java.lang.Long");
	assertThat(messageAttributes.get("long").getStringValue())
			.isEqualTo(String.valueOf(longValue));
	assertThat(messageAttributes.get("integer").getDataType())
			.isEqualTo(MessageAttributeDataTypes.NUMBER + ".java.lang.Integer");
	assertThat(messageAttributes.get("integer").getStringValue())
			.isEqualTo(String.valueOf(integerValue));
	assertThat(messageAttributes.get("byte").getDataType())
			.isEqualTo(MessageAttributeDataTypes.NUMBER + ".java.lang.Byte");
	assertThat(messageAttributes.get("byte").getStringValue())
			.isEqualTo(String.valueOf(byteValue));
	assertThat(messageAttributes.get("short").getDataType())
			.isEqualTo(MessageAttributeDataTypes.NUMBER + ".java.lang.Short");
	assertThat(messageAttributes.get("short").getStringValue())
			.isEqualTo(String.valueOf(shortValue));
	assertThat(messageAttributes.get("float").getDataType())
			.isEqualTo(MessageAttributeDataTypes.NUMBER + ".java.lang.Float");
	assertThat(messageAttributes.get("float").getStringValue())
			.isEqualTo(String.valueOf(floatValue));
	assertThat(messageAttributes.get("bigInteger").getDataType())
			.isEqualTo(MessageAttributeDataTypes.NUMBER + ".java.math.BigInteger");
	assertThat(messageAttributes.get("bigInteger").getStringValue())
			.isEqualTo(String.valueOf(bigIntegerValue));
	assertThat(messageAttributes.get("bigDecimal").getDataType())
			.isEqualTo(MessageAttributeDataTypes.NUMBER + ".java.math.BigDecimal");
	assertThat(messageAttributes.get("bigDecimal").getStringValue())
			.isEqualTo(String.valueOf(bigDecimalValue));
}
 
Example #15
Source File: TopicMessageChannel.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
private MessageAttributeValue getStringMessageAttribute(String messageHeaderValue) {
	return new MessageAttributeValue().withDataType(MessageAttributeDataTypes.STRING)
			.withStringValue(messageHeaderValue);
}
 
Example #16
Source File: TopicMessageChannel.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
private MessageAttributeValue getBinaryMessageAttribute(
		ByteBuffer messageHeaderValue) {
	return new MessageAttributeValue().withDataType(MessageAttributeDataTypes.BINARY)
			.withBinaryValue(messageHeaderValue);
}
 
Example #17
Source File: MockSnsOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public PublishResult publish(String topicArn, String messageText, Map<String, MessageAttributeValue> messageAttributes, AmazonSNS amazonSNS)
{
    // Nothing to do in the normal case since our unit tests aren't reading messages once they have been published.
    return new PublishResult().withMessageId(AbstractDaoTest.MESSAGE_ID);
}
 
Example #18
Source File: SnsOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public PublishResult publish(String topicArn, String messageText, Map<String, MessageAttributeValue> messageAttributes, AmazonSNS amazonSNS)
{
    return amazonSNS.publish(new PublishRequest().withTopicArn(topicArn).withMessage(messageText).withMessageAttributes(messageAttributes));
}
 
Example #19
Source File: PutSNS.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    FlowFile flowFile = session.get();
    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);
    }
}
 
Example #20
Source File: SnsNotificationSenderTest.java    From data-highway with Apache License 2.0 4 votes vote down vote up
@Test
public void typical() throws Exception {
  snsSender = new SnsNotificationSender(sns,
      // Topic name
      n -> String.format("topicArn=%s", n.getRoadName()),
      // Subject
      (t, n) -> String.format("subject=%s", n.getRoadName()));

  HivePartitionCreated notification = HivePartitionCreated
      .builder()
      .databaseName(DATABASE_NAME)
      .locationUri(LOCATION_URI)
      .metastoreUris(HIVE_METASTORE_URIS)
      .partitionSpec(PARTITION_SPEC)
      .roadName(ROAD_NAME)
      .tableName(TABLE_NAME)
      .recordCount(1L)
      .build();

  when(sns.publish(requestCaptor.capture())).thenReturn(null);

  snsSender.send(notification);

  PublishRequest request = requestCaptor.getValue();
  assertThat(request.getTopicArn(), is("topicArn=" + ROAD_NAME));
  assertThat(request.getSubject(), is("subject=" + ROAD_NAME));
  @SuppressWarnings("unchecked")
  Map<String, Object> messageMap = new ObjectMapper().readValue(request.getMessage(), HashMap.class);
  assertThat(messageMap.keySet(), is(ImmutableSet.of("protocolVersion", "type", "roadName", "metastoreUris",
      "databaseName", "tableName", "partitionSpec", "locationUri", "recordCount")));
  assertThat(messageMap, hasEntry("protocolVersion", "1.0"));
  assertThat(messageMap, hasEntry("type", RoadNotificationType.HIVE_PARTITION_CREATED.name()));
  assertThat(messageMap, hasEntry("roadName", ROAD_NAME));
  assertThat(messageMap, hasEntry("metastoreUris", HIVE_METASTORE_URIS));
  assertThat(messageMap, hasEntry("databaseName", DATABASE_NAME));
  assertThat(messageMap, hasEntry("tableName", TABLE_NAME));
  assertThat(messageMap, hasEntry("partitionSpec", PARTITION_SPEC));
  assertThat(messageMap, hasEntry("locationUri", LOCATION_URI));
  assertThat(messageMap, hasEntry("recordCount", 1));

  Map<String, MessageAttributeValue> messageAttributes = request.getMessageAttributes();
  assertThat(messageAttributes.get(SnsNotificationSender.PROTOCOL_VERSION).getStringValue(), is("1.0"));
  assertThat(messageAttributes.get(SnsNotificationSender.PROTOCOL_VERSION).getDataType(), is("String"));
  assertThat(messageAttributes.get(SnsNotificationSender.TYPE).getStringValue(), is("HIVE_PARTITION_CREATED"));
  assertThat(messageAttributes.get(SnsNotificationSender.TYPE).getDataType(), is("String"));
  assertThat(messageAttributes.get(SnsNotificationSender.ROAD_NAME).getStringValue(), is("ROAD_NAME"));
  assertThat(messageAttributes.get(SnsNotificationSender.ROAD_NAME).getDataType(), is("String"));
}
 
Example #21
Source File: SnsOperations.java    From herd with Apache License 2.0 2 votes vote down vote up
/**
 * Sends a message to all of a topic's subscribed endpoints.
 *
 * @param topicArn the topic to publish the message to
 * @param messageText the text of the message
 * @param messageAttributes the optional SNS message attributes
 * @param amazonSNS the client for accessing AWS SNS
 *
 * @return the result of the publish operation returned by the service
 */
public PublishResult publish(String topicArn, String messageText, Map<String, MessageAttributeValue> messageAttributes, AmazonSNS amazonSNS);