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

The following examples show how to use com.amazonaws.services.sqs.model.DeleteMessageRequest. 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: AmazonSQSIdleQueueDeletingClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
@Override
public DeleteMessageResult deleteMessage(DeleteMessageRequest request) {
    String queueUrl = request.getQueueUrl();
    try {
        heartbeatToQueueIfNecessary(queueUrl);
        return super.deleteMessage(request);
    } catch (QueueDoesNotExistException|ReceiptHandleIsInvalidException e) {
        try {
            return super.deleteMessage(
                    request.clone().withQueueUrl(alternateQueueName(request.getQueueUrl())));
        } catch (QueueDoesNotExistException e2) {
            // Silently fail - the message is definitely deleted after all!
            return new DeleteMessageResult();
        }
    }
}
 
Example #2
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 #3
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 #4
Source File: SqsExecutor.java    From spring-integration-aws with MIT License 5 votes vote down vote up
public String acknowlegdeReceipt(Message<?> message) {
	String receiptHandle = (String) message.getHeaders().get(
			SqsHeaders.MSG_RECEIPT_HANDLE);
	if (sqsClient != null && receiptHandle != null
			&& !receiptHandle.isEmpty()) {
		sqsClient.deleteMessage(new DeleteMessageRequest(queueUrl,
				receiptHandle));
	}

	return receiptHandle;
}
 
Example #5
Source File: SqsClient.java    From kafka-connect-sqs with Apache License 2.0 5 votes vote down vote up
/**
 * Delete a message from the SQS queue.
 *
 * @param url           SQS queue url.
 * @param receiptHandle Message receipt handle of message to delete.
 */
public void delete(final String url, final String receiptHandle) {
  Guard.verifyValidUrl(url);
  Guard.verifyNotNullOrEmpty(receiptHandle, "receiptHandle");

  final DeleteMessageRequest request = new DeleteMessageRequest(url, receiptHandle);
  final DeleteMessageResult result = client.deleteMessage(request);

  log.debug(".delete:receipt-handle={}, rc={}", receiptHandle, result.getSdkHttpMetadata().getHttpStatusCode());
}
 
Example #6
Source File: UnorderedAcknowledgerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test acknowledge does not impact messages that were not specifically acknowledge
 */
@Test
public void testAcknowledge() throws JMSException {
    int populateMessageSize = 37;
    populateMessage(populateMessageSize);
    int counter = 0;

    List<SQSMessage> populatedMessagesCopy =  new ArrayList<SQSMessage>(populatedMessages);
    while (!populatedMessagesCopy.isEmpty()) {

        int rand = new Random().nextInt(populatedMessagesCopy.size());
        SQSMessage message = populatedMessagesCopy.remove(rand);
        message.acknowledge();
        assertEquals(populateMessageSize - (++counter), acknowledger.getUnAckMessages().size());
    }
    assertEquals(0, acknowledger.getUnAckMessages().size());

    ArgumentCaptor<DeleteMessageRequest> argumentCaptor = ArgumentCaptor.forClass(DeleteMessageRequest.class);
    verify(amazonSQSClient, times(populateMessageSize)).deleteMessage(argumentCaptor.capture());

    for (SQSMessage msg : populatedMessages) {
        DeleteMessageRequest deleteRequest = new DeleteMessageRequest()
                .withQueueUrl(msg.getQueueUrl())
                .withReceiptHandle(msg.getReceiptHandle());
        assertTrue(argumentCaptor.getAllValues().contains(deleteRequest));
    }
}
 
Example #7
Source File: AutoAcknowledgerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test acknowledging message with auto acknowledger
 */
@Test
public void testAcknowledge() throws Exception {

    /*
     * Set up message mock
     */
    SQSMessage message = mock(SQSMessage.class);
    when(message.getQueueUrl())
            .thenReturn(QUEUE_URL);
    when(message.getReceiptHandle())
            .thenReturn(RECEIPT_HANDLE);

    /*
     * Use the acknowledger to ack the message
     */
    acknowledger.acknowledge(message);

    /*
     * Verify results
     */
    ArgumentCaptor<DeleteMessageRequest> argumentCaptor = ArgumentCaptor.forClass(DeleteMessageRequest.class);
    verify(amazonSQSClient).deleteMessage(argumentCaptor.capture());
    assertEquals(1, argumentCaptor.getAllValues().size());

    DeleteMessageRequest input = argumentCaptor.getAllValues().get(0);
    assertEquals(QUEUE_URL, input.getQueueUrl());
    assertEquals(RECEIPT_HANDLE, input.getReceiptHandle());
}
 
Example #8
Source File: AmazonSQSMessagingClientWrapperTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
@Test(expected = JMSException.class)
public void testDeleteMessageThrowAmazonServiceException() throws JMSException {

    DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
    doThrow(new AmazonServiceException("ase"))
            .when(amazonSQSClient).deleteMessage(eq(deleteMessageRequest));

    wrapper.deleteMessage(deleteMessageRequest);
}
 
Example #9
Source File: AmazonSQSMessagingClientWrapperTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
@Test(expected = JMSException.class)
public void testDeleteMessageThrowAmazonClientException() throws JMSException {

    DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
    doThrow(new AmazonClientException("ace"))
            .when(amazonSQSClient).deleteMessage(eq(deleteMessageRequest));

    wrapper.deleteMessage(deleteMessageRequest);
}
 
Example #10
Source File: UnorderedAcknowledger.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Acknowledges the consumed message via calling <code>deleteMessage</code>.
 */
@Override
public void acknowledge(SQSMessage message) throws JMSException {
    session.checkClosed();
    amazonSQSClient.deleteMessage(new DeleteMessageRequest(
            message.getQueueUrl(), message.getReceiptHandle()));
    unAckMessages.remove(message.getReceiptHandle());
}
 
Example #11
Source File: AutoAcknowledger.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/** Acknowledges the consumed message via calling <code>deleteMessage</code> */
@Override
public void acknowledge(SQSMessage message) throws JMSException {
    session.checkClosed();
    amazonSQSClient.deleteMessage(new DeleteMessageRequest(
            message.getQueueUrl(), message.getReceiptHandle()));
}
 
Example #12
Source File: SqsManager.java    From aws-cloudtrail-processing-library with Apache License 2.0 5 votes vote down vote up
/**
 * Delete a message from the SQS queue that you specified in the configuration file.
 *
 * @param sqsMessage the {@link Message} that you want to delete.
 * @param progressStatus {@link ProgressStatus} tracks the start and end status.
 *
 */
public void deleteMessageFromQueue(Message sqsMessage, ProgressStatus progressStatus) {
    final Object reportObject = progressReporter.reportStart(progressStatus);
    boolean deleteMessageSuccess = false;
    try {
        sqsClient.deleteMessage(new DeleteMessageRequest(config.getSqsUrl(), sqsMessage.getReceiptHandle()));
        deleteMessageSuccess = true;
    } catch (AmazonServiceException e) {
        LibraryUtils.handleException(exceptionHandler, progressStatus, e, "Failed to delete sqs message.");
    }
    LibraryUtils.endToProcess(progressReporter, deleteMessageSuccess, progressStatus, reportObject);
}
 
Example #13
Source File: CloudtrailSQSClient.java    From graylog-plugin-aws with Apache License 2.0 5 votes vote down vote up
public void deleteNotification(CloudtrailSNSNotification notification) {
    LOG.debug("Deleting SQS CloudTrail notification <{}>.", notification.getReceiptHandle());

    sqs.deleteMessage(new DeleteMessageRequest()
            .withQueueUrl(queueName)
            .withReceiptHandle(notification.getReceiptHandle()));
}
 
Example #14
Source File: AmazonSQSStubTest.java    From aws-java-sdk-stubs with Apache License 2.0 5 votes vote down vote up
@Test(expected = ReceiptHandleIsInvalidException.class)
public void deleteMessageFailsWithInvalidReceiptHandle() {
  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 ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest().withQueueUrl(queueUrl);
  final ReceiveMessageResult receiveMessageResult = sqs.receiveMessage(receiveMessageRequest);
  final List<Message> messages = receiveMessageResult.getMessages();
  assertThat(messages.size(), equalTo(1));

  final String receiptHandle = "bizo";
  final DeleteMessageRequest deleteMessageRequest =
    new DeleteMessageRequest().withQueueUrl(queueUrl).withReceiptHandle(receiptHandle);

  sqs.deleteMessage(deleteMessageRequest);
}
 
Example #15
Source File: AmazonSQSStubTest.java    From aws-java-sdk-stubs with Apache License 2.0 5 votes vote down vote up
@Test
public void deleteMessageSucceedsWithValidReceiptHandle() {
  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));

  final String receiptHandle = messages.get(0).getReceiptHandle();
  final DeleteMessageRequest deleteMessageRequest =
    new DeleteMessageRequest().withQueueUrl(queueUrl).withReceiptHandle(receiptHandle);

  try {
    sqs.deleteMessage(deleteMessageRequest);
  } catch (ReceiptHandleIsInvalidException e) {
    fail("ReceiptHandleIsInvalidException was thrown");
  }
}
 
Example #16
Source File: AmazonSQSVirtualQueuesClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
public DeleteMessageResult deleteMessage(DeleteMessageRequest request) {
    heartbeat();
    DeleteMessageRequest virtualQueueResult = new DeleteMessageRequest()
            .withQueueUrl(id.getHostQueueUrl())
            .withReceiptHandle(request.getReceiptHandle());
    return amazonSqsToBeExtended.deleteMessage(virtualQueueResult);
}
 
Example #17
Source File: MockSQSQueue.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
public DeleteMessageResult deleteMessage(DeleteMessageRequest request) {
    String receiptHandle = request.getReceiptHandle();
    if (inflight.remove(receiptHandle) == null) {
        // TODO-RS: Error? Or at least a hook so tests can
        // assert it actually succeeded?
    }
    return new DeleteMessageResult();
}
 
Example #18
Source File: SqsQueueNotificationWorker.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest()
        .withQueueUrl(queueUrl)
        .withMaxNumberOfMessages(MAX_NUMBER_OF_MESSAGES)
        .withVisibilityTimeout(VISIBILITY_TIMEOUT)
        .withWaitTimeSeconds(WAIT_TIME_SECONDS);
    
    while (!shutdown) {
        // Long pole the SQS queue.  This will return as soon as a message
        // is received, or when WAIT_TIME_SECONDS has elapsed.
        List<Message> messages = amazonSqs.receiveMessage(receiveMessageRequest).getMessages();
        if (messages == null) {
            // If there were no messages during this poll period, SQS
            // will return this list as null.  Continue polling.
            continue;
        }
        
        synchronized(handlers) {
            for (Message message : messages) {
                try {
                    // Parse notification and call handlers.
                    JobStatusNotification notification = parseNotification(message);
                    for (JobStatusNotificationHandler handler : handlers) {
                        handler.handle(notification);
                    }
                } catch (IOException e) {
                    System.out.println("Failed to convert notification: " + e.getMessage());
                }
                
                // Delete the message from the queue.
                amazonSqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(queueUrl).withReceiptHandle(message.getReceiptHandle()));
            }
        }
    }
}
 
Example #19
Source File: SqsTriggeredJobExecutor.java    From soundwave with Apache License 2.0 5 votes vote down vote up
public void deleteMessage(Message msg) {
  DeleteMessageRequest
      request =
      new DeleteMessageRequest()
          .withQueueUrl(this.queueUrl)
          .withReceiptHandle(msg.getReceiptHandle());
  this.getClient().deleteMessage(request);
}
 
Example #20
Source File: SQSScanWorkflow.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseScanRangeTask(ScanRangeTask task) {
    // Signal that the range is complete
    signalScanRangeComplete(task.getScanId());

    // Ack the task
    _sqs.deleteMessage(new DeleteMessageRequest()
            .withQueueUrl(getQueueUrl(_pendingScanRangeQueue))
            .withReceiptHandle(((QueueScanRangeTask) task).getMessageId()));
}
 
Example #21
Source File: AmazonSQSExtendedClient.java    From amazon-sqs-java-extended-client-lib with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * Deletes the specified message from the specified queue and deletes the
 * message payload from Amazon S3 when necessary. You specify the message by
 * using the message's <code>receipt handle</code> and not the
 * <code>message ID</code> you received when you sent the message. Even if
 * the message is locked by another reader due to the visibility timeout
 * setting, it is still deleted from the queue. If you leave a message in
 * the queue for longer than the queue's configured retention period, Amazon
 * SQS automatically deletes it.
 * </p>
 * <p>
 * <b>NOTE:</b> The receipt handle is associated with a specific instance of
 * receiving the message. If you receive a message more than once, the
 * receipt handle you get each time you receive the message is different.
 * When you request DeleteMessage, if you don't provide the most recently
 * received receipt handle for the message, the request will still succeed,
 * but the message might not be deleted.
 * </p>
 * <p>
 * <b>IMPORTANT:</b> It is possible you will receive a message even after
 * you have deleted it. This might happen on rare occasions if one of the
 * servers storing a copy of the message is unavailable when you request to
 * delete the message. The copy remains on the server and might be returned
 * to you again on a subsequent receive request. You should create your
 * system to be idempotent so that receiving a particular message more than
 * once is not a problem.
 * </p>
 *
 * @param deleteMessageRequest
 *            Container for the necessary parameters to execute the
 *            DeleteMessage service method on AmazonSQS.
 *
 * @return The response from the DeleteMessage service method, as returned
 *         by AmazonSQS.
 *
 * @throws ReceiptHandleIsInvalidException
 * @throws InvalidIdFormatException
 *
 * @throws AmazonClientException
 *             If any internal errors are encountered inside the client
 *             while attempting to make the request or handle the response.
 *             For example if a network connection is not available.
 * @throws AmazonServiceException
 *             If an error response is returned by AmazonSQS indicating
 *             either a problem with the data in the request, or a server
 *             side issue.
 */
public DeleteMessageResult deleteMessage(DeleteMessageRequest deleteMessageRequest) {

	if (deleteMessageRequest == null) {
		String errorMessage = "deleteMessageRequest cannot be null.";
		LOG.error(errorMessage);
		throw new AmazonClientException(errorMessage);
	}

	deleteMessageRequest.getRequestClientOptions().appendUserAgent(SQSExtendedClientConstants.USER_AGENT_HEADER);

	if (!clientConfiguration.isLargePayloadSupportEnabled()) {
		return super.deleteMessage(deleteMessageRequest);
	}

	String receiptHandle = deleteMessageRequest.getReceiptHandle();
	String origReceiptHandle = receiptHandle;
	if (isS3ReceiptHandle(receiptHandle)) {
		deleteMessagePayloadFromS3(receiptHandle);
		origReceiptHandle = getOrigReceiptHandle(receiptHandle);
	}
	deleteMessageRequest.setReceiptHandle(origReceiptHandle);
	return super.deleteMessage(deleteMessageRequest);
}
 
Example #22
Source File: AmazonSQSVirtualQueuesClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 4 votes vote down vote up
@Override
public DeleteMessageResult deleteMessage(DeleteMessageRequest request) {
    return getVirtualQueue(request.getQueueUrl())
            .map(virtualQueue -> virtualQueue.deleteMessage(request))
            .orElseGet(() -> amazonSqsToBeExtended.deleteMessage(request));
}
 
Example #23
Source File: AbstractAmazonSQSClientWrapper.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 4 votes vote down vote up
@Override
public DeleteMessageResult deleteMessage(DeleteMessageRequest request) {
    request.getRequestClientOptions().appendUserAgent(userAgent);
    return amazonSqsToBeExtended.deleteMessage(request);
}
 
Example #24
Source File: MockSQS.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 4 votes vote down vote up
@Override
public DeleteMessageResult deleteMessage(DeleteMessageRequest request) {
    return getQueue(request.getQueueUrl()).deleteMessage(request);
}
 
Example #25
Source File: AbstractAmazonSQSClientWrapperTest.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 4 votes vote down vote up
@Test
public void deleteMessage() {
    assertWrappedMethod(AmazonSQS::deleteMessage, new DeleteMessageRequest());
}
 
Example #26
Source File: MessageImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public void delete(ResultCapture<Void> extractor) {
    DeleteMessageRequest request = new DeleteMessageRequest();
    delete(request, extractor);
}
 
Example #27
Source File: MessageImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public void delete(DeleteMessageRequest request, ResultCapture<Void>
        extractor) {

    resource.performAction("Delete", request, extractor);
}
 
Example #28
Source File: MessageImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public void delete(DeleteMessageRequest request) {
    delete(request, null);
}
 
Example #29
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void receiveMessage_withMessageListenerMethodAndNeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion()
		throws Exception {
	// Arrange
	CountDownLatch countDownLatch = new CountDownLatch(1);
	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer() {

		@Override
		protected void executeMessage(
				org.springframework.messaging.Message<String> stringMessage) {
			countDownLatch.countDown();
			super.executeMessage(stringMessage);
		}
	};

	AmazonSQSAsync sqs = mock(AmazonSQSAsync.class);
	container.setAmazonSqs(sqs);

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

	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("testListener",
			TestMessageListenerWithManualDeletionPolicy.class);

	mockGetQueueUrl(sqs, "testQueue",
			"https://receiveMessage_withMessageListenerMethodAnd"
					+ "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com");
	mockGetQueueAttributesWithEmptyResult(sqs,
			"https://receiveMessage_withMessageListenerMethodAnd"
					+ "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com");

	messageHandler.setApplicationContext(applicationContext);
	messageHandler.afterPropertiesSet();
	container.afterPropertiesSet();

	mockReceiveMessage(sqs, "https://receiveMessage_withMessageListenerMethodAnd"
			+ "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com",
			"messageContent", "ReceiptHandle");

	// Act
	container.start();

	// Assert
	countDownLatch.await(1L, TimeUnit.SECONDS);
	verify(sqs, never()).deleteMessageAsync(eq(new DeleteMessageRequest(
			"https://receiveMessage_withMessageListenerMethodAnd"
					+ "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com",
			"ReceiptHandle")), any(AsyncHandler.class));
	TestMessageListenerWithManualDeletionPolicy testMessageListenerWithManualDeletionPolicy = applicationContext
			.getBean(TestMessageListenerWithManualDeletionPolicy.class);
	testMessageListenerWithManualDeletionPolicy.getCountDownLatch().await(1L,
			TimeUnit.SECONDS);
	testMessageListenerWithManualDeletionPolicy.acknowledge();
	verify(sqs, times(1)).deleteMessageAsync(eq(new DeleteMessageRequest(
			"https://receiveMessage_withMessageListenerMethodAnd"
					+ "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com",
			"ReceiptHandle")), any(AsyncHandler.class));
	container.stop();
}
 
Example #30
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void executeMessage_executionThrowsExceptionAndQueueHasRedrivePolicy_shouldNotRemoveMessageFromQueue()
		throws Exception {
	// Arrange
	CountDownLatch countDownLatch = new CountDownLatch(1);
	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer() {

		@Override
		protected void executeMessage(
				org.springframework.messaging.Message<String> stringMessage) {
			countDownLatch.countDown();
			super.executeMessage(stringMessage);
		}
	};

	AmazonSQSAsync sqs = mock(AmazonSQSAsync.class);
	container.setAmazonSqs(sqs);

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

	StaticApplicationContext applicationContext = new StaticApplicationContext();
	Class clazz = TestMessageListenerThatThrowsAnExceptionWithAllExceptOnRedriveDeletionPolicy.class;
	applicationContext.registerSingleton("testMessageListener", clazz);

	mockGetQueueUrl(sqs, "testQueue",
			"https://executeMessage_executionThrowsExceptionAnd"
					+ "QueueHasRedrivePolicy_shouldNotRemoveMessageFromQueue.amazonaws.com");
	mockGetQueueAttributesWithRedrivePolicy(sqs,
			"https://executeMessage_executionThrowsExceptionAnd"
					+ "QueueHasRedrivePolicy_shouldNotRemoveMessageFromQueue.amazonaws.com");

	messageHandler.setApplicationContext(applicationContext);
	messageHandler.afterPropertiesSet();
	container.afterPropertiesSet();

	when(sqs.receiveMessage(new ReceiveMessageRequest(
			"https://executeMessage_executionThrowsExceptionAnd"
					+ "QueueHasRedrivePolicy_shouldNotRemoveMessageFromQueue.amazonaws.com")
							.withAttributeNames("All").withMaxNumberOfMessages(10)
							.withWaitTimeSeconds(20)
							.withMessageAttributeNames("All")))
									.thenReturn(
											new ReceiveMessageResult()
													.withMessages(new Message()
															.withBody(
																	"messageContent")
															.withReceiptHandle(
																	"ReceiptHandle")),
											new ReceiveMessageResult());

	// Act
	container.start();

	// Assert
	assertThat(countDownLatch.await(2L, TimeUnit.SECONDS)).isTrue();
	container.stop();
	verify(sqs, never()).deleteMessageAsync(eq(new DeleteMessageRequest(
			"https://executeMessage_executionThrowsExceptionAnd"
					+ "QueueHasRedrivePolicy_shouldNotRemoveMessageFromQueue.amazonaws.com",
			"ReceiptHandle")), any(AsyncHandler.class));
}