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

The following examples show how to use com.amazonaws.services.sqs.model.ReceiveMessageResult. 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: QueueMessagingTemplateTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
private AmazonSQSAsync createAmazonSqs() {
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);

	GetQueueUrlResult queueUrl = new GetQueueUrlResult();
	queueUrl.setQueueUrl("https://queue-url.com");
	when(amazonSqs.getQueueUrl(any(GetQueueUrlRequest.class))).thenReturn(queueUrl);

	ReceiveMessageResult receiveMessageResult = new ReceiveMessageResult();
	com.amazonaws.services.sqs.model.Message message = new com.amazonaws.services.sqs.model.Message();
	message.setBody("My message");
	receiveMessageResult.withMessages(message);
	when(amazonSqs.receiveMessage(any(ReceiveMessageRequest.class)))
			.thenReturn(receiveMessageResult);

	return amazonSqs;
}
 
Example #2
Source File: SQSObservableQueue.java    From conductor with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
List<Message> receiveMessages() {
	try {
		ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest()
				.withQueueUrl(queueURL)
				.withVisibilityTimeout(visibilityTimeoutInSeconds)
				.withMaxNumberOfMessages(batchSize);

		ReceiveMessageResult result = client.receiveMessage(receiveMessageRequest);

		List<Message> messages = result.getMessages().stream()
				.map(msg -> new Message(msg.getMessageId(), msg.getBody(), msg.getReceiptHandle()))
				.collect(Collectors.toList());
		Monitors.recordEventQueueMessagesProcessed(QUEUE_TYPE, this.queueName, messages.size());
		return messages;
	} catch (Exception e) {
		logger.error("Exception while getting messages from SQS", e);
		Monitors.recordObservableQMessageReceivedErrors(QUEUE_TYPE);
	}
	return new ArrayList<>();
}
 
Example #3
Source File: SqsExecutorTest.java    From spring-integration-aws with MIT License 6 votes vote down vote up
@Test
public void incorrectMD5Test() throws MessageMarshallerException {

	String payload = "Hello, World";
	String messageBody = messageMarshaller.serialize(MessageBuilder
			.withPayload(payload).build());
	com.amazonaws.services.sqs.model.Message sqsMessage = new com.amazonaws.services.sqs.model.Message();
	sqsMessage.setBody(messageBody);
	sqsMessage.setMD5OfBody(messageBody);

	ReceiveMessageResult result = new ReceiveMessageResult();
	result.setMessages(Collections.singletonList(sqsMessage));
	when(mockSQS.receiveMessage(any(ReceiveMessageRequest.class)))
			.thenReturn(result);

	Message<?> recvMessage = executor.poll();
	assertNull("No message since MD5 checksum failed", recvMessage);
}
 
Example #4
Source File: AmazonSQSRule.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
public List<Span> getSpans(boolean delete) {

    Stream<Span> spans = Stream.empty();

    ReceiveMessageResult result = client.receiveMessage(queueUrl);

    while (result != null && result.getMessages().size() > 0) {

      spans =
          Stream.concat(spans, result.getMessages().stream().flatMap(AmazonSQSRule::decodeSpans));

      result = client.receiveMessage(queueUrl);

      if (delete) {
        List<DeleteMessageRequest> deletes =
            result
                .getMessages()
                .stream()
                .map(m -> new DeleteMessageRequest(queueUrl, m.getReceiptHandle()))
                .collect(Collectors.toList());
        deletes.forEach(d -> client.deleteMessage(d));
      }
    }

    return spans.collect(Collectors.toList());
  }
 
Example #5
Source File: AmazonSQSIdleQueueDeletingClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
@Override
public ReceiveMessageResult receiveMessage(ReceiveMessageRequest request) {
    // Here we have to also fetch from the backup queue if we created it.
    String queueUrl = request.getQueueUrl();
    String alternateQueueUrl = alternateQueueName(queueUrl);
    QueueMetadata alternateMetadata = queues.get(alternateQueueUrl);
    if (alternateMetadata != null) {
        ReceiveQueueBuffer buffer = alternateMetadata.buffer;
        ReceiveMessageRequest alternateRequest = request.clone().withQueueUrl(alternateQueueUrl);
        buffer.submit(executor, () -> receiveIgnoringNonExistantQueue(request),
                queueUrl, request.getVisibilityTimeout());
        buffer.submit(executor, () -> receiveIgnoringNonExistantQueue(alternateRequest),
                queueUrl, request.getVisibilityTimeout());
        Future<ReceiveMessageResult> receiveFuture = buffer.receiveMessageAsync(request);
        return SQSQueueUtils.waitForFuture(receiveFuture);
    } else {
        try {
            heartbeatToQueueIfNecessary(queueUrl);
            return super.receiveMessage(request);
        } catch (QueueDoesNotExistException e) {
            request.setQueueUrl(recreateQueue(queueUrl));
            return super.receiveMessage(request);
        }
    }
}
 
Example #6
Source File: AWSSQSClient.java    From camel-kafka-connector with Apache License 2.0 6 votes vote down vote up
public void receive(String queue, Predicate<List<Message>> predicate) {
    final String queueUrl = getQueue(queue);

    LOG.debug("Consuming messages from {}", queueUrl);

    final ReceiveMessageRequest request = new ReceiveMessageRequest(queueUrl)
            .withWaitTimeSeconds(maxWaitTime)
            .withMaxNumberOfMessages(maxNumberOfMessages);

    while (true) {
        ReceiveMessageResult result = sqs.receiveMessage(request);

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

        if (!predicate.test(messages)) {
            return;
        }
    }
}
 
Example #7
Source File: MockSQSQueue.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
public ReceiveMessageResult receiveMessage(ReceiveMessageRequest request) {
    Integer waitTimeSeconds = request.getWaitTimeSeconds();
    long timeout = waitTimeSeconds != null ? waitTimeSeconds : 0; 
    
    try {
        MessageContent messageContent = visibleMessages.poll(timeout, TimeUnit.SECONDS);
        ReceiveMessageResult result = new ReceiveMessageResult();
        if (messageContent != null) {
            Message message = messageContent.toMessage();
            String receiptHandle = UUID.randomUUID().toString();
            inflight.put(receiptHandle, messageContent);
            message.withReceiptHandle(receiptHandle);
            result.withMessages(message);
        }
        return result;
    } catch (InterruptedException e) {
        // Imitate what the real SDK does
        throw new AmazonClientException(e);
    }
}
 
Example #8
Source File: SqsExecutorTest.java    From spring-integration-aws with MIT License 6 votes vote down vote up
@Test
public void correctMD5Test() throws Exception {

	String payload = "Hello, World";
	String messageBody = messageMarshaller.serialize(MessageBuilder
			.withPayload(payload).build());
	com.amazonaws.services.sqs.model.Message sqsMessage = new com.amazonaws.services.sqs.model.Message();
	sqsMessage.setBody(messageBody);
	sqsMessage.setMD5OfBody(new String(Hex.encodeHex(Md5Utils
			.computeMD5Hash(messageBody.getBytes("UTF-8")))));

	ReceiveMessageResult result = new ReceiveMessageResult();
	result.setMessages(Collections.singletonList(sqsMessage));
	when(mockSQS.receiveMessage(any(ReceiveMessageRequest.class)))
			.thenReturn(result);

	Message<?> recvMessage = executor.poll();
	assertNotNull("message is not null", recvMessage);

	Message<?> enclosed = messageMarshaller
			.deserialize((String) recvMessage.getPayload());
	String recvPayload = (String) enclosed.getPayload();
	assertEquals("payload must match", payload, recvPayload);
}
 
Example #9
Source File: ReceiveQueueBuffer.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
/**
 * Submits the request for retrieval of messages from the queue and returns a future that will
 * be signalled when the request is satisfied. The future may already be signalled by the time
 * it is returned.
 * 
 * @return never null
 */
public Future<ReceiveMessageResult> receiveMessageAsync(ReceiveMessageRequest rq) {
    if (shutDown) {
        throw new AmazonClientException("The buffer has been shut down.");
    }

    // issue the future...
    int numMessages = 10;
    if (rq.getMaxNumberOfMessages() != null) {
        numMessages = rq.getMaxNumberOfMessages();
    }
    long waitTimeNanos;
    if (rq.getWaitTimeSeconds() != null) {
        waitTimeNanos = TimeUnit.SECONDS.toNanos(rq.getWaitTimeSeconds());
    } else {
        waitTimeNanos = defaultWaitTimeNanos;
    }
    ReceiveMessageFuture toReturn = issueFuture(numMessages, waitTimeNanos);

    // attempt to satisfy it right away...
    satisfyFuturesFromBuffer();

    toReturn.startWaitTimer();

    return toReturn;
}
 
Example #10
Source File: SqsUnboundedReader.java    From beam with Apache License 2.0 6 votes vote down vote up
private void pull() {
  final ReceiveMessageRequest receiveMessageRequest =
      new ReceiveMessageRequest(source.getRead().queueUrl());

  receiveMessageRequest.setMaxNumberOfMessages(MAX_NUMBER_OF_MESSAGES);
  receiveMessageRequest.setAttributeNames(
      Arrays.asList(MessageSystemAttributeName.SentTimestamp.toString()));
  final ReceiveMessageResult receiveMessageResult =
      source.getSqs().receiveMessage(receiveMessageRequest);

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

  if (messages == null || messages.isEmpty()) {
    return;
  }

  for (Message message : messages) {
    messagesNotYetRead.add(message);
  }
}
 
Example #11
Source File: HerdApiClientOperations.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Gets BusinessObjectDataKey from SQS message
 *
 * @param client the AWS SQS client
 * @param queueUrl the AWS SQS queue url
 *
 * @return BusinessObjectDataKey
 * @throws IOException if fails to retrieve BusinessObjectDataKey from SQS message
 * @throws ApiException if fails to make API call
 */
@Retryable(value = ApiException.class, backoff = @Backoff(delay = 2000, multiplier = 2))
BusinessObjectDataKey getBdataKeySqs(AmazonSQS client, String queueUrl) throws IOException, ApiException
{
    ReceiveMessageRequest receiveMessageRequest =
        new ReceiveMessageRequest().withMaxNumberOfMessages(MAX_NUM_MESSAGES).withQueueUrl(queueUrl).withWaitTimeSeconds(WAIT_TIME_SECS)
            .withVisibilityTimeout(VISIBILITY_TIMEOUT_SECS);

    LOGGER.info("Checking queue");
    ReceiveMessageResult receiveMessageResult = client.receiveMessage(receiveMessageRequest);
    if (receiveMessageResult != null && receiveMessageResult.getMessages() != null && receiveMessageResult.getMessages().size() > 0)
    {
        List<Message> sqsMessageList = receiveMessageResult.getMessages();

        LOGGER.info("Scanning {} messages for {} and {}", sqsMessageList.size(), SEARCH_KEYWORD_1, SEARCH_KEYWORD_2);
        // Get message type BUS_OBJCT_DATA_STTS_CHG
        for (Message sqsMessage : sqsMessageList)
        {
            String receivedMessageBody = sqsMessage.getBody();
            if (receivedMessageBody.contains(SEARCH_KEYWORD_1) && receivedMessageBody.contains(SEARCH_KEYWORD_2))
            {
                LOGGER.info("Received Message: {}", receivedMessageBody);
                return mapJsontoBdataKey(receivedMessageBody).getBusinessObjectDataKey();
            }
        }
    }
    throw new ApiException("No SQS message found in queue: " + queueUrl);
}
 
Example #12
Source File: SpringCloudSQSLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenConvertedMessageSentAndVerified_thenSuccess() throws InterruptedException, IOException {
    
    Greeting message = new Greeting("Hello", "World");
    springCloudSQS.send(sendQueueName, message);

    AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS();

    ReceiveMessageRequest request = new ReceiveMessageRequest(sendQueueURl);
    request.setMaxNumberOfMessages(1);

    ReceiveMessageResult result = null;
    do {
        result = amazonSQS.receiveMessage(request);
        if (result.getMessages().size() == 0) {
            logger.info("Message not received at first time, waiting for 1 second");
        }
    } while (result.getMessages().size() == 0);
    assertThat(new ObjectMapper().readValue(result.getMessages().get(0).getBody(), Greeting.class)).isEqualTo(message);
    
    // Delete message so that it doen't interfere with other test
    amazonSQS.deleteMessage(sendQueueURl, result.getMessages().get(0).getReceiptHandle());
}
 
Example #13
Source File: AmazonSQSExtendedClientTest.java    From amazon-sqs-java-extended-client-lib with Apache License 2.0 6 votes vote down vote up
@Test
public void testReceiveMessageMultipleTimesDoesNotAdditionallyAlterReceiveMessageRequest() {
    ExtendedClientConfiguration extendedClientConfiguration = new ExtendedClientConfiguration()
            .withLargePayloadSupportEnabled(mockS3, S3_BUCKET_NAME);
    AmazonSQS sqsExtended = spy(new AmazonSQSExtendedClient(mockSqsBackend, extendedClientConfiguration));
    when(mockSqsBackend.receiveMessage(isA(ReceiveMessageRequest.class))).thenReturn(new ReceiveMessageResult());

    ReceiveMessageRequest messageRequest = new ReceiveMessageRequest();
    ReceiveMessageRequest expectedRequest = new ReceiveMessageRequest()
            .withMessageAttributeNames(SQSExtendedClientConstants.RESERVED_ATTRIBUTE_NAME);

    sqsExtended.receiveMessage(messageRequest);
    Assert.assertEquals(expectedRequest, messageRequest);

    sqsExtended.receiveMessage(messageRequest);
    Assert.assertEquals(expectedRequest, messageRequest);
}
 
Example #14
Source File: SpringCloudSQSLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenMessageSentAndVerified_thenSuccess() throws InterruptedException {

    String message = "Hello World";
    springCloudSQS.send(sendQueueName, message);

    AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS();

    ReceiveMessageRequest request = new ReceiveMessageRequest(sendQueueURl);
    request.setMaxNumberOfMessages(1);

    ReceiveMessageResult result = null;
    do {
        result = amazonSQS.receiveMessage(request);
        if (result.getMessages().size() == 0) {
            logger.info("Message not received at first time, waiting for 1 second");
        }
    } while (result.getMessages().size() == 0);
    assertThat(result.getMessages().get(0).getBody()).isEqualTo(message);
    
    // Delete message so that it doen't interfere with other test
    amazonSQS.deleteMessage(sendQueueURl, result.getMessages().get(0).getReceiptHandle());
    
}
 
Example #15
Source File: SqsClient.java    From kafka-connect-sqs with Apache License 2.0 6 votes vote down vote up
/**
 * Receive messages from the SQS queue.
 *
 * @param url             SQS queue url.
 * @param maxMessages     Maximum number of messages to receive for this call.
 * @param waitTimeSeconds Time to wait, in seconds, for messages to arrive.
 * @return Collection of messages received.
 */
public List<Message> receive(final String url, final int maxMessages, final int waitTimeSeconds) {
  log.debug(".receive:queue={}, max={}, wait={}", url, maxMessages, waitTimeSeconds);

  Guard.verifyValidUrl(url);
  Guard.verifyNonNegative(waitTimeSeconds, "sqs.wait.time.seconds");
  Guard.verifyInRange(maxMessages, 0, 10, "sqs.max.messages");
  if (!isValidState()) {
    throw new IllegalStateException("AmazonSQS client is not initialized");
  }

  //
  // Receive messages from queue
  //
  final ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(url)
      .withMaxNumberOfMessages(maxMessages).withWaitTimeSeconds(waitTimeSeconds).withAttributeNames("");
  final ReceiveMessageResult result = client.receiveMessage(receiveMessageRequest);
  final List<Message> messages = result.getMessages();

  log.debug(".receive:{} messages, url={}, rc={}", messages.size(), url,
      result.getSdkHttpMetadata().getHttpStatusCode());

  return messages;
}
 
Example #16
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void receiveMessage_withoutDefaultTimeout_returnsNull() throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);
	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(0).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All"))).thenReturn(
					new ReceiveMessageResult().withMessages(Collections.emptyList()));

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

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

	// Assert
	assertThat(receivedMessage).isNull();
}
 
Example #17
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void receiveMessage_withSpecifiedTimeout_returnsNull() throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);
	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(2).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All"))).thenReturn(
					new ReceiveMessageResult().withMessages(Collections.emptyList()));

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

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

	// Assert
	assertThat(receivedMessage).isNull();
}
 
Example #18
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void receiveMessage_withSpecifiedTimeout_returnsTextMessage() throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);
	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(2).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All")))
					.thenReturn(new ReceiveMessageResult().withMessages(Collections
							.singleton(new com.amazonaws.services.sqs.model.Message()
									.withBody("content"))));

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

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

	// Assert
	assertThat(receivedMessage).isNotNull();
	assertThat(receivedMessage.getPayload()).isEqualTo("content");
}
 
Example #19
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void receiveMessage_withoutTimeout_returnsTextMessage() throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);
	when(amazonSqs.receiveMessage(new ReceiveMessageRequest("http://testQueue")
			.withWaitTimeSeconds(0).withMaxNumberOfMessages(1)
			.withAttributeNames(QueueMessageChannel.ATTRIBUTE_NAMES)
			.withMessageAttributeNames("All")))
					.thenReturn(new ReceiveMessageResult().withMessages(Collections
							.singleton(new com.amazonaws.services.sqs.model.Message()
									.withBody("content"))));

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

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

	// Assert
	assertThat(receivedMessage).isNotNull();
	assertThat(receivedMessage.getPayload()).isEqualTo("content");
}
 
Example #20
Source File: SQSMessageConsumerPrefetchTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Test received messages with timeout
 */
@Test
public void testReceiveNoWaitEmpty() throws InterruptedException, JMSException {

    /*
     * Set up consumer prefetch and time stamps
     */
    consumerPrefetch.running = true;

    if (numberOfMessagesToPrefetch == 0) {
        when(amazonSQSClient.receiveMessage(any(ReceiveMessageRequest.class)))
                .thenReturn(new ReceiveMessageResult());
    }
    
    /*
     * Call receive messages
     */
    SQSMessage msg = (SQSMessage) consumerPrefetch.receiveNoWait();

    assertNull(msg);

    // Ensure the messagesRequested counter is reset correctly
    assertEquals(0, consumerPrefetch.messagesRequested);
}
 
Example #21
Source File: QueueMessageChannel.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Override
public Message<String> receive(long timeout) {
	ReceiveMessageResult receiveMessageResult = this.amazonSqs.receiveMessage(
			new ReceiveMessageRequest(this.queueUrl).withMaxNumberOfMessages(1)
					.withWaitTimeSeconds(Long.valueOf(timeout).intValue())
					.withAttributeNames(ATTRIBUTE_NAMES)
					.withMessageAttributeNames(MESSAGE_ATTRIBUTE_NAMES));
	if (receiveMessageResult.getMessages().isEmpty()) {
		return null;
	}
	com.amazonaws.services.sqs.model.Message amazonMessage = receiveMessageResult
			.getMessages().get(0);
	Message<String> message = createMessage(amazonMessage);
	this.amazonSqs.deleteMessage(new DeleteMessageRequest(this.queueUrl,
			amazonMessage.getReceiptHandle()));
	return message;
}
 
Example #22
Source File: SQSSubscriber.java    From kork with Apache License 2.0 6 votes vote down vote up
private void listenForMessages() {
  while (isEnabled.get()) {
    ReceiveMessageResult receiveMessageResult =
        amazonSQS.receiveMessage(
            new ReceiveMessageRequest(this.subscriptionInfo.queueUrl)
                .withMaxNumberOfMessages(subscription.getMaxNumberOfMessages())
                .withVisibilityTimeout(subscription.getVisibilityTimeout())
                .withWaitTimeSeconds(subscription.getWaitTimeSeconds())
                .withMessageAttributeNames("All"));

    if (receiveMessageResult.getMessages().isEmpty()) {
      log.debug("Received no messages for queue {}", queueARN);
      continue;
    }

    receiveMessageResult.getMessages().forEach(this::handleMessage);
  }
}
 
Example #23
Source File: SQSSubscriber.java    From echo with Apache License 2.0 6 votes vote down vote up
private void listenForMessages() {
  while (isEnabled.get()) {
    ReceiveMessageResult receiveMessageResult =
        amazonSQS.receiveMessage(
            new ReceiveMessageRequest(queueId)
                .withMaxNumberOfMessages(AWS_MAX_NUMBER_OF_MESSAGES)
                .withVisibilityTimeout(subscription.getVisibilityTimeout())
                .withWaitTimeSeconds(subscription.getWaitTimeSeconds())
                .withMessageAttributeNames("All"));

    if (receiveMessageResult.getMessages().isEmpty()) {
      log.debug("Received no messages for queue: {}", queueARN);
      continue;
    }

    receiveMessageResult.getMessages().forEach(this::handleMessage);
  }
}
 
Example #24
Source File: ITDeleteSQS.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleDelete() throws IOException {
    // Setup - put one message in queue
    SendMessageResult sendMessageResult = sqsClient.sendMessage(TEST_QUEUE_URL, "Test message");
    assertEquals(200, sendMessageResult.getSdkHttpMetadata().getHttpStatusCode());

    // Setup - receive message to get receipt handle
    ReceiveMessageResult receiveMessageResult = sqsClient.receiveMessage(TEST_QUEUE_URL);
    assertEquals(200, receiveMessageResult.getSdkHttpMetadata().getHttpStatusCode());
    Message deleteMessage = receiveMessageResult.getMessages().get(0);
    String receiptHandle = deleteMessage.getReceiptHandle();

    // Test - delete message with DeleteSQS
    final TestRunner runner = TestRunners.newTestRunner(new DeleteSQS());
    runner.setProperty(DeleteSQS.CREDENTIALS_FILE, CREDENTIALS_FILE);
    runner.setProperty(DeleteSQS.QUEUE_URL, TEST_QUEUE_URL);
    runner.setProperty(DeleteSQS.REGION, TEST_REGION);
    final Map<String, String> ffAttributes = new HashMap<>();
    ffAttributes.put("filename", "1.txt");
    ffAttributes.put("sqs.receipt.handle", receiptHandle);
    runner.enqueue("TestMessageBody", ffAttributes);

    runner.run(1);

    runner.assertAllFlowFilesTransferred(DeleteSQS.REL_SUCCESS, 1);
}
 
Example #25
Source File: AmazonSQSStubTest.java    From aws-java-sdk-stubs with Apache License 2.0 6 votes vote down vote up
@Test
public void sendAndReceiveMessage() {
  final String queueName = "bizo";
  final String messageBody = "hi everybody";

  final CreateQueueRequest createQueueRequest = new CreateQueueRequest().withQueueName(queueName);
  sqs.createQueue(createQueueRequest);

  final GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest().withQueueName(queueName);
  final GetQueueUrlResult getQueueUrlResult = sqs.getQueueUrl(getQueueUrlRequest);
  final String queueUrl = getQueueUrlResult.getQueueUrl();

  final SendMessageRequest sendMessageRequest =
    new SendMessageRequest().withQueueUrl(queueUrl).withMessageBody(messageBody);
  sqs.sendMessage(sendMessageRequest);

  final int maxNumberOfMessages = 10;

  final ReceiveMessageRequest receiveMessageRequest =
    new ReceiveMessageRequest().withQueueUrl(queueUrl).withMaxNumberOfMessages(maxNumberOfMessages);
  final ReceiveMessageResult receiveMessageResult = sqs.receiveMessage(receiveMessageRequest);
  final List<Message> messages = receiveMessageResult.getMessages();

  assertThat(messages.size(), equalTo(1));
  assertThat(messages.get(0).getBody(), equalTo(messageBody));
}
 
Example #26
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
public ReceiveMessageResult receiveMessage(
		ReceiveMessageRequest receiveMessageRequest)
		throws AmazonClientException {
	if ("http://testQueue.amazonaws.com".equals(
			receiveMessageRequest.getQueueUrl()) && this.receiveMessageEnabled) {
		return new ReceiveMessageResult().withMessages(new Message()
				.withBody("Hello").withReceiptHandle("ReceiptHandle"));
	}
	else {
		return new ReceiveMessageResult();
	}
}
 
Example #27
Source File: QueueImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public List<Message> receiveMessages(ResultCapture<ReceiveMessageResult>
        extractor) {

    ReceiveMessageRequest request = new ReceiveMessageRequest();
    return receiveMessages(request, extractor);
}
 
Example #28
Source File: QueueImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public List<Message> receiveMessages(ReceiveMessageRequest request,
        ResultCapture<ReceiveMessageResult> extractor) {

    ActionResult result = resource.performAction("ReceiveMessages", request,
            extractor);

    if (result == null) return null;
    return CodecUtils.transform(result.getResources(), MessageImpl.CODEC);
}
 
Example #29
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void start_withAQueueNameThatIsAlreadyRunning_shouldNotStartTheQueueAgainAndIgnoreTheCall()
		throws Exception {
	// Arrange
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("testMessageListener",
			TestMessageListener.class);

	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
	AmazonSQSAsync sqs = mock(AmazonSQSAsync.class, withSettings().stubOnly());

	when(sqs.receiveMessage(any(ReceiveMessageRequest.class)))
			.thenReturn(new ReceiveMessageResult());

	container.setAmazonSqs(sqs);
	container.setBackOffTime(0);

	QueueMessageHandler messageHandler = new QueueMessageHandler();
	messageHandler.setApplicationContext(applicationContext);
	container.setMessageHandler(messageHandler);

	mockGetQueueUrl(sqs, "testQueue",
			"https://start_withAQueueNameThatIsAlreadyRunning_shouldNotStartTheQueueAgainAndIgnoreTheCall.amazonaws.com");
	mockGetQueueAttributesWithEmptyResult(sqs,
			"https://start_withAQueueNameThatIsAlreadyRunning_shouldNotStartTheQueueAgainAndIgnoreTheCall.amazonaws.com");

	messageHandler.afterPropertiesSet();
	container.afterPropertiesSet();
	container.start();

	assertThat(container.isRunning("testQueue")).isTrue();

	// Act
	container.start("testQueue");

	// Assert
	assertThat(container.isRunning("testQueue")).isTrue();

	container.stop();
}
 
Example #30
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);
}