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

The following examples show how to use com.amazonaws.services.sqs.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: AmazonSQSResponderClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 7 votes vote down vote up
@Override
public void sendResponseMessage(MessageContent request, MessageContent response) {
    MessageAttributeValue attribute = request.getMessageAttributes().get(AmazonSQSRequesterClient.RESPONSE_QUEUE_URL_ATTRIBUTE_NAME);

    if (attribute != null) {
        String replyQueueUrl = attribute.getStringValue();
        try {
            SendMessageRequest responseRequest = response.toSendMessageRequest()
                    .withQueueUrl(replyQueueUrl);
            sqs.sendMessage(responseRequest);
        } catch (QueueDoesNotExistException e) {
            // Stale request, ignore
            // TODO-RS: CW metric
            LOG.warn("Ignoring response to deleted response queue: " + replyQueueUrl);
        }
    } else {
        // TODO-RS: CW metric
        LOG.warn("Attempted to send response when none was requested");
    }
}
 
Example #2
Source File: SendMessageTracingRequestHandler.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
private void injectPerMessage(String queueUrl,
    Map<String, MessageAttributeValue> messageAttributes) {
  TraceContext maybeParent = currentTraceContext.get();

  Span span;
  if (maybeParent == null) {
    span = tracer.nextSpan(extractAndClearHeaders(messageAttributes));
  } else {
    // If we have a span in scope assume headers were cleared before
    span = tracer.newChild(maybeParent);
  }

  if (!span.isNoop()) {
    span.kind(PRODUCER).name("publish");
    span.remoteServiceName("amazon-sqs");
    span.tag("queue.url", queueUrl);
    // incur timestamp overhead only once
    long timestamp = tracing.clock(span.context()).currentTimeMicroseconds();
    span.start(timestamp).finish(timestamp);
  }

  injector.inject(span.context(), messageAttributes);
}
 
Example #3
Source File: SqsDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public SendMessageResult sendMessage(AwsParamsDto awsParamsDto, String queueName, 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 sqsOperations.sendMessage(queueName, messageText, messageAttributes, awsClientFactory.getAmazonSQSClient(awsParamsDto));
}
 
Example #4
Source File: MockSqsOperationsImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public SendMessageResult sendMessage(String queueName, String messageText, Map<String, MessageAttributeValue> messageAttributes, AmazonSQS amazonSQS)
{
    // Throw a throttling exception for a specific queue name for testing purposes.
    if (queueName.equals(MockAwsOperationsHelper.AMAZON_THROTTLING_EXCEPTION))
    {
        AmazonServiceException throttlingException = new AmazonServiceException("test throttling exception");
        throttlingException.setErrorCode("ThrottlingException");
        throw throttlingException;
    }

    // Throw an illegal state exception for a specific queue name for testing purposes.
    if (queueName.equals(MOCK_SQS_QUEUE_NOT_FOUND_NAME))
    {
        throw new IllegalStateException(String.format("AWS SQS queue with \"%s\" name not found.", queueName));
    }

    // Nothing else to do in the normal case since our unit tests aren't reading messages once they have been published.
    return new SendMessageResult().withMessageId(AbstractDaoTest.MESSAGE_ID);
}
 
Example #5
Source File: AmazonSQSExtendedClient.java    From amazon-sqs-java-extended-client-lib with Apache License 2.0 6 votes vote down vote up
private int getMsgAttributesSize(Map<String, MessageAttributeValue> msgAttributes) {
	int totalMsgAttributesSize = 0;
	for (Entry<String, MessageAttributeValue> entry : msgAttributes.entrySet()) {
		totalMsgAttributesSize += getStringSizeInBytes(entry.getKey());

		MessageAttributeValue entryVal = entry.getValue();
		if (entryVal.getDataType() != null) {
			totalMsgAttributesSize += getStringSizeInBytes(entryVal.getDataType());
		}

		String stringVal = entryVal.getStringValue();
		if (stringVal != null) {
			totalMsgAttributesSize += getStringSizeInBytes(entryVal.getStringValue());
		}

		ByteBuffer binaryVal = entryVal.getBinaryValue();
		if (binaryVal != null) {
			totalMsgAttributesSize += binaryVal.array().length;
		}
	}
	return totalMsgAttributesSize;
}
 
Example #6
Source File: SQSMessageProducer.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the reply-to queue name and url attributes during send as part of the send message
 * request, if necessary
 */
private void addReplyToQueueReservedAttributes(Map<String, MessageAttributeValue> messageAttributes,
                                               SQSMessage message) throws JMSException {

    Destination replyTo = message.getJMSReplyTo();
    if (replyTo instanceof SQSQueueDestination) {
        SQSQueueDestination replyToQueue = (SQSQueueDestination)replyTo;

        /**
         * This will override the existing attributes if exists. Everything that
         * has prefix JMS_ is reserved for JMS Provider, but if the user sets that
         * attribute, it will be overwritten.
         */
        addStringAttribute(messageAttributes, SQSMessage.JMS_SQS_REPLY_TO_QUEUE_NAME, replyToQueue.getQueueName());
        addStringAttribute(messageAttributes, SQSMessage.JMS_SQS_REPLY_TO_QUEUE_URL, replyToQueue.getQueueUrl());
    }
}
 
Example #7
Source File: AmazonSQSRequesterClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Message> sendMessageAndGetResponseAsync(SendMessageRequest request, int timeout, TimeUnit unit) {
    String queueName = queuePrefix + UUID.randomUUID().toString();
    CreateQueueRequest createQueueRequest = new CreateQueueRequest()
            .withQueueName(queueName)
            .withAttributes(queueAttributes);
    String responseQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

    SendMessageRequest requestWithResponseUrl = SQSQueueUtils.copyWithExtraAttributes(request,
            Collections.singletonMap(RESPONSE_QUEUE_URL_ATTRIBUTE_NAME, 
                    new MessageAttributeValue().withDataType("String").withStringValue(responseQueueUrl)));
    // TODO-RS: Should be using sendMessageAsync
    sqs.sendMessage(requestWithResponseUrl);

    CompletableFuture<Message> future = new CompletableFuture<>();
    
    // TODO-RS: accept an AmazonSQSAsync instead and use its threads instead of our own.
    // TODO-RS: complete the future exceptionally, for the right set of SQS exceptions
    SQSMessageConsumer consumer = new ResponseListener(responseQueueUrl, future);
    responseConsumers.add(consumer);
    consumer.runFor(timeout, unit);
    return future;
}
 
Example #8
Source File: QueueMessageChannel.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private SendMessageRequest prepareSendMessageRequest(Message<?> message) {
	SendMessageRequest sendMessageRequest = new SendMessageRequest(this.queueUrl,
			String.valueOf(message.getPayload()));

	if (message.getHeaders().containsKey(SqsMessageHeaders.SQS_GROUP_ID_HEADER)) {
		sendMessageRequest.setMessageGroupId(message.getHeaders()
				.get(SqsMessageHeaders.SQS_GROUP_ID_HEADER, String.class));
	}

	if (message.getHeaders()
			.containsKey(SqsMessageHeaders.SQS_DEDUPLICATION_ID_HEADER)) {
		sendMessageRequest.setMessageDeduplicationId(message.getHeaders()
				.get(SqsMessageHeaders.SQS_DEDUPLICATION_ID_HEADER, String.class));
	}

	if (message.getHeaders().containsKey(SqsMessageHeaders.SQS_DELAY_HEADER)) {
		sendMessageRequest.setDelaySeconds(message.getHeaders()
				.get(SqsMessageHeaders.SQS_DELAY_HEADER, Integer.class));
	}

	Map<String, MessageAttributeValue> messageAttributes = getMessageAttributes(
			message);
	if (!messageAttributes.isEmpty()) {
		sendMessageRequest.withMessageAttributes(messageAttributes);
	}

	return sendMessageRequest;
}
 
Example #9
Source File: SQSMessageProducerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test sendInternal input with SQSByteMessage
 */
@Test
public void testSendInternalSQSByteMessageFromReceivedMessage() throws JMSException, IOException {
    
    /*
     * Set up non JMS sqs message
     */
    Map<String,MessageAttributeValue> mapMessageAttributes = new HashMap<String, MessageAttributeValue>();
    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue(SQSMessage.BYTE_MESSAGE_TYPE);
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue);

    Map<String, String> mapAttributes = new HashMap<String, String>();
    mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1");

    byte[] byteArray = new byte[] { 1, 0, 'a', 65 };
    String messageBody = Base64.encodeAsString(byteArray);
    com.amazonaws.services.sqs.model.Message message =
            new com.amazonaws.services.sqs.model.Message()
                    .withMessageAttributes(mapMessageAttributes)
                    .withAttributes(mapAttributes)
                    .withBody(messageBody);

    SQSObjectMessage msg = spy(new SQSObjectMessage(acknowledger, QUEUE_URL, message));

    Map<String, MessageAttributeValue> messageAttributes = createMessageAttribute("object");

    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_1))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_2));

    producer.sendInternal(destination, msg);

    verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, Arrays.asList(messageBody),
            messageAttributes)));
    verify(msg).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1);
    verify(msg).setSQSMessageId(MESSAGE_ID_1);
}
 
Example #10
Source File: SQSMessageProducerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test sendInternal input with SQSByteMessage
 */
@Test
public void testSendInternalSQSByteMessage() throws JMSException {

    SQSBytesMessage msg = spy(new SQSBytesMessage());
    msg.writeByte((byte)0);
    msg.reset();

    Map<String, MessageAttributeValue> messageAttributes = createMessageAttribute("byte");

    String messageId = "MessageId";
    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_1))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_2));

    producer.sendInternal(destination, msg);

    /*
     * Re send the message
     */
    msg.clearBody();
    msg.writeInt(42);
    producer.sendInternal(destination, msg);

    List<String> messagesBody = Arrays.asList("AA==", "AAAAKg==");
    verify(amazonSQSClient, times(2)).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messagesBody,
                                                                                        messageAttributes)));

    verify(msg, times(2)).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_2);
    verify(msg).setSQSMessageId(MESSAGE_ID_1);
    verify(msg).setSQSMessageId(MESSAGE_ID_2);
}
 
Example #11
Source File: QueueMessageChannel.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 #12
Source File: QueueMessageChannel.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 #13
Source File: SQSMessageProducer.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Not verified on the client side, but SQS Attribute names must be valid
 * letter or digit on the basic multilingual plane in addition to allowing
 * '_', '-' and '.'. No component of an attribute name may be empty, thus an
 * attribute name may neither start nor end in '.'. And it may not contain
 * "..".
 */
Map<String, MessageAttributeValue> propertyToMessageAttribute(SQSMessage message)
        throws JMSException {
    Map<String, MessageAttributeValue> messageAttributes = new HashMap<String, MessageAttributeValue>();
    Enumeration<String> propertyNames = message.getPropertyNames();

    while (propertyNames.hasMoreElements()) {
        String propertyName = propertyNames.nextElement();

        // This is generated from SQS message attribute "ApproximateReceiveCount"
        if (propertyName.equals(SQSMessagingClientConstants.JMSX_DELIVERY_COUNT)) {
            continue;
        }

        // This property will be used as DeduplicationId argument of SendMessage call
        // On receive it is mapped back to this JMS property
        if (propertyName.equals(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID)) {
            continue;
        }

        // the JMSXGroupID and JMSXGroupSeq are always stored as message
        // properties, so they are not lost between send and receive
        // even though SQS Classic does not respect those values when returning messages
        // and SQS FIFO has a different understanding of message groups

        JMSMessagePropertyValue propertyObject = message.getJMSMessagePropertyValue(propertyName);
        MessageAttributeValue messageAttributeValue = new MessageAttributeValue();

        messageAttributeValue.setDataType(propertyObject.getType());
        messageAttributeValue.setStringValue(propertyObject.getStringMessageAttributeValue());

        messageAttributes.put(propertyName, messageAttributeValue);
    }
    return messageAttributes;
}
 
Example #14
Source File: QueueMessageUtils.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private static Map<String, Object> getMessageAttributesAsMessageHeaders(
		com.amazonaws.services.sqs.model.Message message) {
	Map<String, Object> messageHeaders = new HashMap<>();
	for (Map.Entry<String, MessageAttributeValue> messageAttribute : message
			.getMessageAttributes().entrySet()) {
		if (MessageHeaders.CONTENT_TYPE.equals(messageAttribute.getKey())) {
			messageHeaders.put(MessageHeaders.CONTENT_TYPE,
					MimeType.valueOf(messageAttribute.getValue().getStringValue()));
		}
		else if (MessageHeaders.ID.equals(messageAttribute.getKey())) {
			messageHeaders.put(MessageHeaders.ID,
					UUID.fromString(messageAttribute.getValue().getStringValue()));
		}
		else if (MessageAttributeDataTypes.STRING
				.equals(messageAttribute.getValue().getDataType())) {
			messageHeaders.put(messageAttribute.getKey(),
					messageAttribute.getValue().getStringValue());
		}
		else if (messageAttribute.getValue().getDataType()
				.startsWith(MessageAttributeDataTypes.NUMBER)) {
			messageHeaders.put(messageAttribute.getKey(),
					getNumberValue(messageAttribute.getValue()));
		}
		else if (MessageAttributeDataTypes.BINARY
				.equals(messageAttribute.getValue().getDataType())) {
			messageHeaders.put(messageAttribute.getKey(),
					messageAttribute.getValue().getBinaryValue());
		}
	}

	return messageHeaders;
}
 
Example #15
Source File: SQSMessageProducerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test sendInternal input with SQSObjectMessage
 */
@Test
public void testSendInternalSQSObjectMessage() throws JMSException {

    HashSet<String> set1 = new HashSet<String>();
    set1.add("data1");
    HashSet<String> set2 = new HashSet<String>();
    set2.add("data2");

    SQSObjectMessage msg = spy(new SQSObjectMessage(set1));
    String megBody1 = msg.getMessageBody();

    Map<String, MessageAttributeValue> messageAttributes = createMessageAttribute("object");

    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_1))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_2));

    producer.sendInternal(destination, msg);

    /*
     * Re send the message
     */
    msg.clearBody();
    msg.setObject(set2);
    String megBody2 = msg.getMessageBody();
    producer.sendInternal(destination, msg);
    
    ArgumentCaptor<SendMessageRequest> argumentCaptor = ArgumentCaptor.forClass(SendMessageRequest.class);
    verify(amazonSQSClient, times(2)).sendMessage(argumentCaptor.capture());
    
    assertEquals(megBody1, argumentCaptor.getAllValues().get(0).getMessageBody());
    assertEquals(megBody2, argumentCaptor.getAllValues().get(1).getMessageBody());
    verify(msg, times(2)).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_2);
    verify(msg).setSQSMessageId(MESSAGE_ID_1);
    verify(msg).setSQSMessageId(MESSAGE_ID_2);
}
 
Example #16
Source File: SQSMessageProducerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test sendInternal input with SQSTextMessage
 */
@Test
public void testSendInternalSQSTextMessageFromReceivedMessage() throws JMSException {

    /*
     * Set up non JMS sqs message
     */
    Map<String,MessageAttributeValue> mapMessageAttributes = new HashMap<String, MessageAttributeValue>();
    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue(SQSMessage.TEXT_MESSAGE_TYPE);
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue);

    Map<String, String> mapAttributes = new HashMap<String, String>();
    mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1");

    com.amazonaws.services.sqs.model.Message message =
            new com.amazonaws.services.sqs.model.Message()
                        .withMessageAttributes(mapMessageAttributes)
                        .withAttributes(mapAttributes)
                        .withBody("MessageBody");

    SQSTextMessage msg = spy(new SQSTextMessage(acknowledger, QUEUE_URL, message));

    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_1));

    producer.sendInternal(destination, msg);

    List<String> messagesBody = Arrays.asList("MessageBody");
    verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messagesBody, mapMessageAttributes)));
    verify(msg).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1);
    verify(msg).setSQSMessageId(MESSAGE_ID_1);
}
 
Example #17
Source File: SQSMessageProducerFifoTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test sendInternal input with SQSTextMessage
 */
@Test
public void testSendInternalSQSTextMessageFromReceivedMessage() throws JMSException {

    /*
     * Set up non JMS sqs message
     */
    Map<String,MessageAttributeValue> mapMessageAttributes = new HashMap<String, MessageAttributeValue>();
    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue(SQSMessage.TEXT_MESSAGE_TYPE);
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue);

    Map<String, String> mapAttributes = new HashMap<String, String>();
    mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1");
    mapAttributes.put(SQSMessagingClientConstants.MESSAGE_GROUP_ID, GROUP_ID);
    mapAttributes.put(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, DEDUP_ID);
    mapAttributes.put(SQSMessagingClientConstants.SEQUENCE_NUMBER, SEQ_NUMBER);

    com.amazonaws.services.sqs.model.Message message =
            new com.amazonaws.services.sqs.model.Message()
                        .withMessageAttributes(mapMessageAttributes)
                        .withAttributes(mapAttributes)
                        .withBody("MessageBody");

    SQSTextMessage msg = spy(new SQSTextMessage(acknowledger, QUEUE_URL, message));

    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID).withSequenceNumber(SEQ_NUMBER_2));

    producer.sendInternal(destination, msg);

    verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, "MessageBody", SQSMessage.TEXT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID)));
    verify(msg).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID);
    verify(msg).setSQSMessageId(MESSAGE_ID);
    verify(msg).setSequenceNumber(SEQ_NUMBER_2);
}
 
Example #18
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveMessage_withMimeTypeMessageAttribute_shouldCopyToHeaders()
		throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);
	MimeType mimeType = new MimeType("test", "plain", Charset.forName("UTF-8"));
	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(0).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All"))).thenReturn(new ReceiveMessageResult()
					.withMessages(new com.amazonaws.services.sqs.model.Message()
							.withBody("Hello")
							.withMessageAttributes(Collections.singletonMap(
									MessageHeaders.CONTENT_TYPE,
									new MessageAttributeValue()
											.withDataType(
													MessageAttributeDataTypes.STRING)
											.withStringValue(mimeType.toString())))));

	PollableChannel messageChannel = new QueueMessageChannel(amazonSqs,
			"http://testQueue");

	// Act
	Message<?> receivedMessage = messageChannel.receive();

	// Assert
	assertThat(receivedMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE))
			.isEqualTo(mimeType);
}
 
Example #19
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveMessage_withStringMessageHeader_shouldBeReceivedAsQueueMessageAttribute()
		throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);
	String headerValue = "Header value";
	String headerName = "MyHeader";
	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(0).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All")))
					.thenReturn(new ReceiveMessageResult().withMessages(
							new com.amazonaws.services.sqs.model.Message()
									.withBody("Hello")
									.withMessageAttributes(Collections.singletonMap(
											headerName,
											new MessageAttributeValue().withDataType(
													MessageAttributeDataTypes.STRING)
													.withStringValue(headerValue)))));

	PollableChannel messageChannel = new QueueMessageChannel(amazonSqs,
			"http://testQueue");

	// Act
	Message<?> receivedMessage = messageChannel.receive();

	// Assert
	assertThat(receivedMessage.getHeaders().get(headerName)).isEqualTo(headerValue);
}
 
Example #20
Source File: SQSMessageProducerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test sendInternal input with SQSTextMessage
 */
@Test
public void testSendInternalSQSTextMessage() throws JMSException {

    String messageBody1 = "MyText1";
    String messageBody2 = "MyText2";
    SQSTextMessage msg = spy(new SQSTextMessage(messageBody1));

    Map<String, MessageAttributeValue> messageAttributes = createMessageAttribute("text");

    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_1))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_2));

    producer.sendInternal(destination, msg);

    /*
     * Re send the message
     */
    msg.setText(messageBody2);
    producer.sendInternal(destination, msg);

    List<String> messagesBody = Arrays.asList(messageBody1, messageBody2);
    verify(amazonSQSClient, times(2)).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messagesBody, messageAttributes)));
    verify(msg, times(2)).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_2);
    verify(msg).setSQSMessageId(MESSAGE_ID_1);
    verify(msg).setSQSMessageId(MESSAGE_ID_2);
}
 
Example #21
Source File: TestGetSQS.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMessageNoAutoDelete() {
    runner.setProperty(GetSQS.QUEUE_URL, "https://sqs.us-west-2.amazonaws.com/123456789012/test-queue-000000000");
    runner.setProperty(GetSQS.AUTO_DELETE, "false");

    Message message1 = new Message();
    message1.setBody("TestMessage1");
    message1.addAttributesEntry("attrib-key-1", "attrib-value-1");
    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue("msg-attrib-value-1");
    message1.addMessageAttributesEntry("msg-attrib-key-1", messageAttributeValue);
    message1.setMD5OfBody("test-md5-hash-1");
    message1.setMessageId("test-message-id-1");
    message1.setReceiptHandle("test-receipt-handle-1");
    ReceiveMessageResult receiveMessageResult = new ReceiveMessageResult()
            .withMessages(message1);
    Mockito.when(mockSQSClient.receiveMessage(Mockito.any(ReceiveMessageRequest.class))).thenReturn(receiveMessageResult);

    runner.run(1);

    ArgumentCaptor<ReceiveMessageRequest> captureRequest = ArgumentCaptor.forClass(ReceiveMessageRequest.class);
    Mockito.verify(mockSQSClient, Mockito.times(1)).receiveMessage(captureRequest.capture());
    ReceiveMessageRequest request = captureRequest.getValue();
    assertEquals("https://sqs.us-west-2.amazonaws.com/123456789012/test-queue-000000000", request.getQueueUrl());
    Mockito.verify(mockSQSClient, Mockito.never()).deleteMessageBatch(Mockito.any(DeleteMessageBatchRequest.class));

    runner.assertAllFlowFilesTransferred(GetSQS.REL_SUCCESS, 1);
    List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(GetSQS.REL_SUCCESS);
    MockFlowFile ff0 = flowFiles.get(0);
    ff0.assertAttributeEquals("sqs.attrib-key-1", "attrib-value-1");
    ff0.assertAttributeEquals("sqs.msg-attrib-key-1", "msg-attrib-value-1");
    ff0.assertAttributeEquals("hash.value", "test-md5-hash-1");
    ff0.assertAttributeEquals("hash.algorithm", "md5");
    ff0.assertAttributeEquals("sqs.message.id", "test-message-id-1");
    ff0.assertAttributeEquals("sqs.receipt.handle", "test-receipt-handle-1");
}
 
Example #22
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveMessage_withIncompatibleNumericMessageHeader_shouldThrowAnException()
		throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);

	HashMap<String, MessageAttributeValue> messageAttributes = new HashMap<>();
	AtomicInteger atomicInteger = new AtomicInteger(17);
	messageAttributes.put("atomicInteger",
			new MessageAttributeValue()
					.withDataType(MessageAttributeDataTypes.NUMBER
							+ ".java.util.concurrent.atomic.AtomicInteger")
					.withStringValue(String.valueOf(atomicInteger)));

	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(0).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All")))
					.thenReturn(new ReceiveMessageResult().withMessages(
							new com.amazonaws.services.sqs.model.Message()
									.withBody("Hello")
									.withMessageAttributes(messageAttributes)));

	PollableChannel messageChannel = new QueueMessageChannel(amazonSqs,
			"http://testQueue");

	// Assert
	assertThatThrownBy(messageChannel::receive)
			.isInstanceOf(IllegalArgumentException.class).hasMessageContaining(
					"Cannot convert String [17] to target class [java.util.concurrent.atomic.AtomicInteger]");
}
 
Example #23
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveMessage_withMissingNumericMessageHeaderTargetClass_shouldThrowAnException()
		throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);

	HashMap<String, MessageAttributeValue> messageAttributes = new HashMap<>();
	messageAttributes.put("classNotFound",
			new MessageAttributeValue()
					.withDataType(
							MessageAttributeDataTypes.NUMBER + ".class.not.Found")
					.withStringValue("12"));

	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(0).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All")))
					.thenReturn(new ReceiveMessageResult().withMessages(
							new com.amazonaws.services.sqs.model.Message()
									.withBody("Hello")
									.withMessageAttributes(messageAttributes)));

	PollableChannel messageChannel = new QueueMessageChannel(amazonSqs,
			"http://testQueue");

	// Assert
	assertThatThrownBy(messageChannel::receive).isInstanceOf(MessagingException.class)
			.hasMessageContaining(
					"Message attribute with value '12' and data type 'Number.class.not.Found' could not be converted"
							+ " into a Number because target class was not found.");
}
 
Example #24
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveMessage_withBinaryMessageHeader_shouldBeReceivedAsByteBufferMessageAttribute()
		throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);
	ByteBuffer headerValue = ByteBuffer.wrap("My binary data!".getBytes());
	String headerName = "MyHeader";
	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(0).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All")))
					.thenReturn(new ReceiveMessageResult().withMessages(
							new com.amazonaws.services.sqs.model.Message()
									.withBody("Hello")
									.withMessageAttributes(Collections.singletonMap(
											headerName,
											new MessageAttributeValue().withDataType(
													MessageAttributeDataTypes.BINARY)
													.withBinaryValue(headerValue)))));

	PollableChannel messageChannel = new QueueMessageChannel(amazonSqs,
			"http://testQueue");

	// Act
	Message<?> receivedMessage = messageChannel.receive();

	// Assert
	assertThat(receivedMessage.getHeaders().get(headerName)).isEqualTo(headerValue);
}
 
Example #25
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveMessage_withIdOfTypeString_IdShouldBeConvertedToUuid() throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);
	UUID uuid = UUID.randomUUID();
	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(0).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All"))).thenReturn(new ReceiveMessageResult()
					.withMessages(new com.amazonaws.services.sqs.model.Message()
							.withBody("Hello")
							.withMessageAttributes(Collections.singletonMap(
									MessageHeaders.ID,
									new MessageAttributeValue()
											.withDataType(
													MessageAttributeDataTypes.STRING)
											.withStringValue(uuid.toString())))));

	PollableChannel messageChannel = new QueueMessageChannel(amazonSqs,
			"http://testQueue");

	// Act
	Message<?> receivedMessage = messageChannel.receive();

	// Assert
	Object idMessageHeader = receivedMessage.getHeaders().get(MessageHeaders.ID);
	assertThat(UUID.class.isInstance(idMessageHeader)).isTrue();
	assertThat(idMessageHeader).isEqualTo(uuid);
}
 
Example #26
Source File: QueueMessageUtilsTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("validArguments")
void createsMessageWithNumberHeader(String value, String type, Number expected) {
	Message message = new Message().withBody("some body").addMessageAttributesEntry(
			"number-attribute",
			new MessageAttributeValue().withStringValue(value).withDataType(type));

	org.springframework.messaging.Message<String> result = QueueMessageUtils
			.createMessage(message);

	assertThat(result.getHeaders().get("number-attribute")).isEqualTo(expected);
}
 
Example #27
Source File: SQSMessageProducerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test propertyToMessageAttribute with empty messages of different type
 */
@Test
public void testPropertyToMessageAttributeWithEmpty() throws JMSException {

    /*
     * Test Empty text message default attribute
     */
    SQSMessage sqsText = new SQSTextMessage();
    Map<String, MessageAttributeValue> messageAttributeText = producer.propertyToMessageAttribute(sqsText);

    assertEquals(0, messageAttributeText.size());

    /*
     * Test Empty object message default attribute
     */
    SQSMessage sqsObject = new SQSObjectMessage();
    Map<String, MessageAttributeValue> messageAttributeObject = producer.propertyToMessageAttribute(sqsObject);

    assertEquals(0, messageAttributeObject.size());

    /*
     * Test Empty byte message default attribute
     */
    MessageAttributeValue messageAttributeValueByte = new MessageAttributeValue();
    messageAttributeValueByte.setDataType("String");
    messageAttributeValueByte.setStringValue("byte");

    SQSMessage sqsByte = new SQSBytesMessage();
    Map<String, MessageAttributeValue> messageAttributeByte = producer.propertyToMessageAttribute(sqsByte);

    assertEquals(0, messageAttributeObject.size());
}
 
Example #28
Source File: SQSResourcesIntegrationTest.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
/**
 * Tests sending of message with message attributes. Asserts that the
 * message received has the attributes. Also changes the visibility of the
 * messages and tries to retrieve them. Performs delete action on the
 * message to the delete it from the queue.
 */
@Test
@Ignore
public void testSendReceiveMessageAttributes() throws InterruptedException {

    SendMessageResult sendMessageResult = queue
            .sendMessage(new SendMessageRequest().withMessageBody(
                    TEST_MESSAGE_ATTRIBUTES).withMessageAttributes(
                    ImmutableMapParameter.of(
                            "testAttribute",
                            new MessageAttributeValue().withDataType(
                                    "String").withStringValue(
                                    "testAttributeValue"))));

    List<Message> messages = waitForMessagesFromQueue(new ReceiveMessageRequest()
            .withMessageAttributeNames("testAttribute"));

    assertNotNull(messages);
    assertEquals(1, messages.size());
    Message message = messages.get(0);
    assertMessage(TEST_MESSAGE_ATTRIBUTES,
            sendMessageResult.getMessageId(),
            sendMessageResult.getMD5OfMessageBody(), message);

    Map<String, MessageAttributeValue> messageAttributes = message
            .getMessageAttributes();
    assertNotNull(messageAttributes);
    assertTrue(messageAttributes.containsKey("testAttribute"));
    assertEquals(messageAttributes.get("testAttribute").getStringValue(),
            "testAttributeValue");

    message.changeVisibility(10);

    messages = waitForMessagesFromQueue(null);
    message.delete();
}
 
Example #29
Source File: SQSMessageProducer.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience method for adding a single string attribute.
 */
private void addStringAttribute(Map<String, MessageAttributeValue> messageAttributes,
                                String key, String value) {
    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    messageAttributeValue.setStringValue(value);
    messageAttributes.put(key, messageAttributeValue);
}
 
Example #30
Source File: SQSMessageProducer.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the correlation ID attribute during send as part of the send message
 * request, if necessary
 */
private void addCorrelationIDToQueueReservedAttributes(Map<String, MessageAttributeValue> messageAttributes,
                                               SQSMessage message) throws JMSException {

    String correlationID = message.getJMSCorrelationID();
    if (correlationID != null) {
        addStringAttribute(messageAttributes, SQSMessage.JMS_SQS_CORRELATION_ID, correlationID);
    }
}