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

The following examples show how to use com.amazonaws.services.sqs.model.GetQueueAttributesRequest. 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: SqsExecutor.java    From spring-integration-aws with MIT License 6 votes vote down vote up
private void addPermissions() {
	if (permissions != null && permissions.isEmpty() == false) {
		GetQueueAttributesResult result = sqsClient
				.getQueueAttributes(new GetQueueAttributesRequest(queueUrl,
						Arrays.asList("Policy")));

		AwsUtil.addPermissions(result.getAttributes(), permissions,
				new AwsUtil.AddPermissionHandler() {

					@Override
					public void execute(Permission p) {
						sqsClient.addPermission(new AddPermissionRequest()
								.withQueueUrl(queueUrl)
								.withLabel(p.getLabel())
								.withAWSAccountIds(p.getAwsAccountIds())
								.withActions(p.getActions()));
					}
				});
	}
}
 
Example #2
Source File: AmazonSQSVirtualQueuesClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
public GetQueueAttributesResult getQueueAttributes(GetQueueAttributesRequest request) {
    List<String> attributeNames = request.getAttributeNames();
    boolean includeHostQueue = 
            attributeNames.remove(VIRTUAL_QUEUE_HOST_QUEUE_ATTRIBUTE) ||
            attributeNames.contains("All");
    boolean includeRetentionPeriod = retentionPeriod.isPresent() && 
            (attributeNames.contains(IDLE_QUEUE_RETENTION_PERIOD) ||
             attributeNames.contains("All"));
    
    GetQueueAttributesRequest hostQueueRequest = new GetQueueAttributesRequest()
            .withQueueUrl(hostQueue.queueUrl)
            .withAttributeNames(attributeNames);
    GetQueueAttributesResult result = amazonSqsToBeExtended.getQueueAttributes(hostQueueRequest);
    if (includeHostQueue) {
        result.getAttributes().put(VIRTUAL_QUEUE_HOST_QUEUE_ATTRIBUTE, hostQueue.queueUrl);
    }
    if (includeRetentionPeriod) {
        result.getAttributes().put(IDLE_QUEUE_RETENTION_PERIOD, retentionPeriod.get().toString());
    }
    return result;
}
 
Example #3
Source File: ReceiveQueueBuffer.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
public ReceiveQueueBuffer(AmazonSQS sqsClient, ScheduledExecutorService waitTimer, String queueUrl) {
    this.sqsClient = sqsClient;
    this.waitTimer = waitTimer;

    if (queueUrl.endsWith(".fifo")) {
        throw new IllegalArgumentException("FIFO queues are not yet supported: " + queueUrl);
    }

    GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest().withQueueUrl(queueUrl)
            .withAttributeNames(QueueAttributeName.ReceiveMessageWaitTimeSeconds.toString(),
                    QueueAttributeName.VisibilityTimeout.toString());
    // TODO-RS: UserAgent?
    Map<String, String> attributes = sqsClient.getQueueAttributes(getQueueAttributesRequest).getAttributes();
    long visibilityTimeoutSeconds = Long.parseLong(attributes.get("VisibilityTimeout"));
    defaultVisibilityTimeoutNanos = TimeUnit.SECONDS.toNanos(visibilityTimeoutSeconds);
    long waitTimeSeconds = Long.parseLong(attributes.get("ReceiveMessageWaitTimeSeconds"));
    defaultWaitTimeNanos = TimeUnit.SECONDS.toNanos(waitTimeSeconds);
}
 
Example #4
Source File: ReceiveQueueBufferTest.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
public ReceiveQueueBufferTest() {
    this.sqs = mock(AmazonSQS.class);
    this.executor = mock(ScheduledExecutorService.class);
    this.queueUrl = "http://queue.amazon.com/123456789012/MyQueue";
    
    Map<String, String> attributes = new HashMap<>();
    attributes.put(QueueAttributeName.ReceiveMessageWaitTimeSeconds.toString(), "20");
    attributes.put(QueueAttributeName.VisibilityTimeout.toString(), "30");
    List<String> attributeNames = Arrays.asList(
            QueueAttributeName.ReceiveMessageWaitTimeSeconds.toString(),
            QueueAttributeName.VisibilityTimeout.toString());
    GetQueueAttributesResult getQueueAttributesResult = new GetQueueAttributesResult()
            .withAttributes(attributes);
    when(sqs.getQueueAttributes(
            eq(new GetQueueAttributesRequest()
                    .withQueueUrl(queueUrl)
                    .withAttributeNames(attributeNames))))
            .thenReturn(getQueueAttributesResult);
}
 
Example #5
Source File: SqsExecutor.java    From spring-integration-aws with MIT License 5 votes vote down vote up
private void resolveQueueArn() {
	GetQueueAttributesRequest request = new GetQueueAttributesRequest(
			queueUrl);
	GetQueueAttributesResult result = sqsClient.getQueueAttributes(request
			.withAttributeNames(Collections.singletonList(QUEUE_ARN_KEY)));
	queueArn = result.getAttributes().get(QUEUE_ARN_KEY);
}
 
Example #6
Source File: SQSQueueUtils.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
public static boolean isQueueEmpty(AmazonSQS sqs, String queueUrl) {
    QueueAttributeName[] messageCountAttrs = {
            QueueAttributeName.ApproximateNumberOfMessages,
            QueueAttributeName.ApproximateNumberOfMessagesDelayed,
            QueueAttributeName.ApproximateNumberOfMessagesNotVisible
    };

    GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest()
            .withQueueUrl(queueUrl)
            .withAttributeNames(messageCountAttrs);
    GetQueueAttributesResult result = sqs.getQueueAttributes(getQueueAttributesRequest);
    Map<String, String> attrValues = result.getAttributes();
    return Stream.of(messageCountAttrs).allMatch(attr ->
            Long.parseLong(attrValues.get(attr.name())) == 0);
}
 
Example #7
Source File: AWSSQSMetaDataExtension.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<MetaData> meta(Map<String, Object> parameters) {
    final String accessKey = ConnectorOptions.extractOption(parameters, "accessKey");
    final String secretKey = ConnectorOptions.extractOption(parameters, "secretKey");
    final String region = ConnectorOptions.extractOption(parameters, "region");
    AmazonSQSClientBuilder clientBuilder;
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
    clientBuilder = AmazonSQSClientBuilder.standard().withCredentials(credentialsProvider);
    clientBuilder = clientBuilder.withRegion(Regions.valueOf(region));
    AmazonSQS sqsClient = clientBuilder.build();
    List<String> attributeNames = new ArrayList<String>();
    attributeNames.add("All");
    try {
        ListQueuesResult result = sqsClient.listQueues();
        Set<String> setQueue = new HashSet<String>();
        if (result.getQueueUrls() != null) {
            for (String entry : result.getQueueUrls()) {
                GetQueueAttributesRequest req = new GetQueueAttributesRequest();
                req.setQueueUrl(entry);
                req.setAttributeNames(attributeNames);
                GetQueueAttributesResult c = sqsClient.getQueueAttributes(req);
                setQueue.add(c.getAttributes().get(QueueAttributeName.QueueArn.name()));
            }
        }
        return Optional.of(MetaDataBuilder.on(getCamelContext()).withAttribute(MetaData.CONTENT_TYPE, "text/plain").withAttribute(MetaData.JAVA_TYPE, String.class)
            .withPayload(setQueue).build());
    } catch (Exception e) {
        throw new IllegalStateException("Get information about existing queues with has failed.", e);
    }
}
 
Example #8
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Bean
AmazonSQSAsync amazonSQS() {
	AmazonSQSAsync mockAmazonSQS = mock(AmazonSQSAsync.class,
			withSettings().stubOnly());
	mockGetQueueUrl(mockAmazonSQS, "testQueue", "http://testQueue.amazonaws.com");
	when(mockAmazonSQS.receiveMessage(any(ReceiveMessageRequest.class)))
			.thenReturn(new ReceiveMessageResult());
	when(mockAmazonSQS.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());
	return mockAmazonSQS;
}
 
Example #9
Source File: AwsGlacierInventoryRetriever.java    From core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * For retrieving vault inventory. For initializing SQS for determining when
 * job completed. Does nothing if member snsTopicName is null. Sets members
 * sqsQueueURL, sqsQueueARN, and sqsClient.
 */
   private void setupSQS() {
	// If no sqsQueueName setup then simply return
	if (sqsQueueName == null)
		return;

	CreateQueueRequest request = new CreateQueueRequest()
			.withQueueName(sqsQueueName);
	CreateQueueResult result = sqsClient.createQueue(request);
	sqsQueueURL = result.getQueueUrl();

	GetQueueAttributesRequest qRequest = new GetQueueAttributesRequest()
			.withQueueUrl(sqsQueueURL).withAttributeNames("QueueArn");

	GetQueueAttributesResult qResult = sqsClient
			.getQueueAttributes(qRequest);
	sqsQueueARN = qResult.getAttributes().get("QueueArn");

	Policy sqsPolicy = new Policy().withStatements(new Statement(
			Effect.Allow).withPrincipals(Principal.AllUsers)
			.withActions(SQSActions.SendMessage)
			.withResources(new Resource(sqsQueueARN)));
	Map<String, String> queueAttributes = new HashMap<String, String>();
	queueAttributes.put("Policy", sqsPolicy.toJson());
	sqsClient.setQueueAttributes(new SetQueueAttributesRequest(sqsQueueURL,
			queueAttributes));
}
 
Example #10
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private static void mockGetQueueAttributesWithRedrivePolicy(AmazonSQSAsync sqs,
		String queueUrl) {
	when(sqs.getQueueAttributes(new GetQueueAttributesRequest(queueUrl)
			.withAttributeNames(QueueAttributeName.RedrivePolicy)))
					.thenReturn(new GetQueueAttributesResult().addAttributesEntry(
							QueueAttributeName.RedrivePolicy.toString(),
							"{\"some\": \"JSON\"}"));
}
 
Example #11
Source File: MessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveMessageRequests_withOneElement_created() throws Exception {
	AbstractMessageListenerContainer container = new StubAbstractMessageListenerContainer();

	AmazonSQSAsync mock = mock(AmazonSQSAsync.class, withSettings().stubOnly());
	QueueMessageHandler messageHandler = new QueueMessageHandler();
	container.setAmazonSqs(mock);
	container.setMessageHandler(mock(QueueMessageHandler.class));
	container.setMessageHandler(messageHandler);
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("messageListener", MessageListener.class);
	container.setMaxNumberOfMessages(11);
	container.setVisibilityTimeout(22);
	container.setWaitTimeOut(33);

	messageHandler.setApplicationContext(applicationContext);

	when(mock.getQueueUrl(new GetQueueUrlRequest().withQueueName("testQueue")))
			.thenReturn(new GetQueueUrlResult()
					.withQueueUrl("http://testQueue.amazonaws.com"));
	when(mock.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());

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

	Map<String, QueueAttributes> registeredQueues = container.getRegisteredQueues();
	assertThat(registeredQueues.get("testQueue").getReceiveMessageRequest()
			.getQueueUrl()).isEqualTo("http://testQueue.amazonaws.com");
	assertThat(registeredQueues.get("testQueue").getReceiveMessageRequest()
			.getMaxNumberOfMessages().longValue()).isEqualTo(11L);
	assertThat(registeredQueues.get("testQueue").getReceiveMessageRequest()
			.getVisibilityTimeout().longValue()).isEqualTo(22L);
	assertThat(registeredQueues.get("testQueue").getReceiveMessageRequest()
			.getWaitTimeSeconds().longValue()).isEqualTo(33L);
}
 
Example #12
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testWithDefaultTaskExecutorAndOneHandler() throws Exception {
	int testedMaxNumberOfMessages = 10;

	Map<QueueMessageHandler.MappingInformation, HandlerMethod> messageHandlerMethods = Collections
			.singletonMap(new QueueMessageHandler.MappingInformation(
					Collections.singleton("testQueue"),
					SqsMessageDeletionPolicy.ALWAYS), null);

	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();

	QueueMessageHandler mockedHandler = mock(QueueMessageHandler.class);
	AmazonSQSAsync mockedSqs = mock(AmazonSQSAsync.class, withSettings().stubOnly());

	when(mockedSqs.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());
	when(mockedSqs.getQueueUrl(any(GetQueueUrlRequest.class)))
			.thenReturn(new GetQueueUrlResult().withQueueUrl("testQueueUrl"));
	when(mockedHandler.getHandlerMethods()).thenReturn(messageHandlerMethods);

	container.setMaxNumberOfMessages(testedMaxNumberOfMessages);
	container.setAmazonSqs(mockedSqs);
	container.setMessageHandler(mockedHandler);

	container.afterPropertiesSet();

	int expectedPoolMaxSize = messageHandlerMethods.size()
			* (testedMaxNumberOfMessages + 1);

	ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) container
			.getTaskExecutor();
	assertThat(taskExecutor).isNotNull();
	assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(expectedPoolMaxSize);
}
 
Example #13
Source File: AmazonSQSIdleQueueDeletingClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
@Override
public GetQueueAttributesResult getQueueAttributes(GetQueueAttributesRequest request) {
    QueueMetadata metadata = queues.get(request.getQueueUrl());
    if (metadata != null) {
        Map<String, String> filteredAttributes = new HashMap<>(metadata.attributes);
        filteredAttributes.keySet().retainAll(request.getAttributeNames());
        return new GetQueueAttributesResult().withAttributes(filteredAttributes);
    }

    return super.getQueueAttributes(request);
}
 
Example #14
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Override
public GetQueueAttributesResult getQueueAttributes(
		GetQueueAttributesRequest getQueueAttributesRequest)
		throws AmazonClientException {
	return new GetQueueAttributesResult();
}
 
Example #15
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void listener_withMultipleMessageHandlers_shouldBeCalled() throws Exception {
	CountDownLatch countDownLatch = new CountDownLatch(2);
	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer() {

		@Override
		protected void executeMessage(
				org.springframework.messaging.Message<String> stringMessage) {
			countDownLatch.countDown();
			super.executeMessage(stringMessage);
		}
	};
	AmazonSQSAsync sqs = mock(AmazonSQSAsync.class, withSettings().stubOnly());
	container.setAmazonSqs(sqs);

	QueueMessageHandler messageHandler = new QueueMessageHandler();
	container.setMessageHandler(messageHandler);
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("testMessageListener",
			TestMessageListener.class);
	applicationContext.registerSingleton("anotherTestMessageListener",
			AnotherTestMessageListener.class);

	mockGetQueueUrl(sqs, "testQueue",
			"https://listener_withMultipleMessageHandlers_shouldBeCalled.amazonaws.com");
	mockGetQueueAttributesWithEmptyResult(sqs,
			"https://listener_withMultipleMessageHandlers_shouldBeCalled.amazonaws.com");
	mockGetQueueUrl(sqs, "anotherTestQueue",
			"https://listener_withMultipleMessageHandlers_shouldBeCalled.another.amazonaws.com");
	mockGetQueueAttributesWithEmptyResult(sqs,
			"https://listener_withMultipleMessageHandlers_shouldBeCalled.another.amazonaws.com");

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

	when(sqs.receiveMessage(new ReceiveMessageRequest(
			"https://listener_withMultipleMessageHandlers_shouldBeCalled.amazonaws.com")
					.withAttributeNames("All").withMessageAttributeNames("All")
					.withMaxNumberOfMessages(10).withWaitTimeSeconds(20)))
							.thenReturn(new ReceiveMessageResult().withMessages(
									new Message().withBody("messageContent")))
							.thenReturn(new ReceiveMessageResult());
	when(sqs.receiveMessage(new ReceiveMessageRequest(
			"https://listener_withMultipleMessageHandlers_shouldBeCalled.another.amazonaws.com")
					.withAttributeNames("All").withMessageAttributeNames("All")
					.withMaxNumberOfMessages(10).withWaitTimeSeconds(20)))
							.thenReturn(new ReceiveMessageResult().withMessages(
									new Message().withBody("anotherMessageContent")))
							.thenReturn(new ReceiveMessageResult());
	when(sqs.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());

	container.start();

	assertThat(countDownLatch.await(2L, TimeUnit.SECONDS)).isTrue();
	container.stop();
	assertThat(applicationContext.getBean(TestMessageListener.class).getMessage())
			.isEqualTo("messageContent");
	assertThat(
			applicationContext.getBean(AnotherTestMessageListener.class).getMessage())
					.isEqualTo("anotherMessageContent");
}
 
Example #16
Source File: MessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void receiveMessageRequests_withMultipleElements_created() throws Exception {
	AbstractMessageListenerContainer container = new StubAbstractMessageListenerContainer();

	AmazonSQSAsync mock = mock(AmazonSQSAsync.class, withSettings().stubOnly());
	container.setAmazonSqs(mock);
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	QueueMessageHandler messageHandler = new QueueMessageHandler();
	messageHandler.setApplicationContext(applicationContext);
	container.setMessageHandler(messageHandler);
	applicationContext.registerSingleton("messageListener", MessageListener.class);
	applicationContext.registerSingleton("anotherMessageListener",
			AnotherMessageListener.class);

	container.setMaxNumberOfMessages(11);
	container.setVisibilityTimeout(22);
	container.setWaitTimeOut(33);

	when(mock.getQueueUrl(new GetQueueUrlRequest().withQueueName("testQueue")))
			.thenReturn(new GetQueueUrlResult()
					.withQueueUrl("http://testQueue.amazonaws.com"));
	when(mock.getQueueUrl(new GetQueueUrlRequest().withQueueName("anotherTestQueue")))
			.thenReturn(new GetQueueUrlResult()
					.withQueueUrl("https://anotherTestQueue.amazonaws.com"));
	when(mock.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());

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

	Map<String, QueueAttributes> registeredQueues = container.getRegisteredQueues();
	assertThat(registeredQueues.get("testQueue").getReceiveMessageRequest()
			.getQueueUrl()).isEqualTo("http://testQueue.amazonaws.com");
	assertThat(registeredQueues.get("testQueue").getReceiveMessageRequest()
			.getMaxNumberOfMessages().longValue()).isEqualTo(11L);
	assertThat(registeredQueues.get("testQueue").getReceiveMessageRequest()
			.getVisibilityTimeout().longValue()).isEqualTo(22L);
	assertThat(registeredQueues.get("testQueue").getReceiveMessageRequest()
			.getWaitTimeSeconds().longValue()).isEqualTo(33L);
	assertThat(registeredQueues.get("anotherTestQueue").getReceiveMessageRequest()
			.getQueueUrl()).isEqualTo("https://anotherTestQueue.amazonaws.com");
	assertThat(registeredQueues.get("anotherTestQueue").getReceiveMessageRequest()
			.getMaxNumberOfMessages().longValue()).isEqualTo(11L);
	assertThat(registeredQueues.get("anotherTestQueue").getReceiveMessageRequest()
			.getVisibilityTimeout().longValue()).isEqualTo(22L);
	assertThat(registeredQueues.get("anotherTestQueue").getReceiveMessageRequest()
			.getWaitTimeSeconds().longValue()).isEqualTo(33L);
}
 
Example #17
Source File: MessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void receiveMessageRequests_withDestinationResolverThrowingException_shouldLogWarningAndNotCreateRequest()
		throws Exception {
	// Arrange
	AbstractMessageListenerContainer container = new StubAbstractMessageListenerContainer();
	Logger loggerMock = container.getLogger();

	AmazonSQSAsync mock = mock(AmazonSQSAsync.class, withSettings().stubOnly());
	container.setAmazonSqs(mock);
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	QueueMessageHandler messageHandler = new QueueMessageHandler();
	messageHandler.setApplicationContext(applicationContext);
	container.setMessageHandler(messageHandler);
	applicationContext.registerSingleton("messageListener", MessageListener.class);
	applicationContext.registerSingleton("anotherMessageListener",
			AnotherMessageListener.class);

	String destinationResolutionExceptionMessage = "Queue not found";
	when(mock.getQueueUrl(new GetQueueUrlRequest().withQueueName("testQueue")))
			.thenThrow(new DestinationResolutionException(
					destinationResolutionExceptionMessage));
	when(mock.getQueueUrl(new GetQueueUrlRequest().withQueueName("anotherTestQueue")))
			.thenReturn(new GetQueueUrlResult()
					.withQueueUrl("https://anotherTestQueue.amazonaws.com"));
	when(mock.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());

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

	// Act
	container.start();

	// Assert
	ArgumentCaptor<String> logMsgArgCaptor = ArgumentCaptor.forClass(String.class);
	verify(loggerMock).warn(logMsgArgCaptor.capture());
	Map<String, QueueAttributes> registeredQueues = container.getRegisteredQueues();
	assertThat(registeredQueues.containsKey("testQueue")).isFalse();
	assertThat(logMsgArgCaptor.getValue())
			.isEqualTo("Ignoring queue with name 'testQueue': "
					+ destinationResolutionExceptionMessage);
	assertThat(registeredQueues.get("anotherTestQueue").getReceiveMessageRequest()
			.getQueueUrl()).isEqualTo("https://anotherTestQueue.amazonaws.com");
}
 
Example #18
Source File: QueueImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public boolean load(GetQueueAttributesRequest request) {
    return load(request, null);
}
 
Example #19
Source File: QueueImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public boolean load(GetQueueAttributesRequest request,
        ResultCapture<GetQueueAttributesResult> extractor) {

    return resource.load(request, extractor);
}
 
Example #20
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void receiveMessage_throwsAnException_operationShouldBeRetried() throws Exception {
	// Arrange
	Level previous = disableLogging();

	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class, withSettings().stubOnly());
	when(amazonSqs.receiveMessage(any(ReceiveMessageRequest.class)))
			.thenThrow(new RuntimeException("Boom!"))
			.thenReturn(new ReceiveMessageResult().withMessages(
					new Message().withBody("messageContent"),
					new Message().withBody("messageContent")));

	CountDownLatch countDownLatch = new CountDownLatch(1);
	QueueMessageHandler messageHandler = new QueueMessageHandler() {

		@Override
		public void handleMessage(org.springframework.messaging.Message<?> message)
				throws MessagingException {
			countDownLatch.countDown();
			assertThat(message.getPayload()).isEqualTo("messageContent");
		}
	};

	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("testMessageListener",
			TestMessageListener.class);
	messageHandler.setApplicationContext(applicationContext);

	mockGetQueueUrl(amazonSqs, "testQueue",
			"https://receiveMessage_throwsAnException_operationShouldBeRetried.amazonaws.com");
	messageHandler.afterPropertiesSet();

	when(amazonSqs.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());

	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
	container.setBackOffTime(0);
	container.setAmazonSqs(amazonSqs);
	container.setMessageHandler(messageHandler);
	container.setAutoStartup(false);
	container.afterPropertiesSet();

	// Act
	container.start();

	// Assert
	assertThat(countDownLatch.await(1, TimeUnit.SECONDS)).isTrue();
	container.stop();
	setLogLevel(previous);
}
 
Example #21
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void messageExecutor_messageWithMimeTypeMessageAttribute_shouldSetItAsHeader()
		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, withSettings().stubOnly());
	container.setAmazonSqs(sqs);

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

	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("testMessageListener",
			TestMessageListener.class);

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

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

	MimeType mimeType = new MimeType("text", "plain", Charset.forName("UTF-8"));
	when(sqs.receiveMessage(new ReceiveMessageRequest(
			"https://messageExecutor_messageWithMimeTypeMessageAttribute_shouldSetItAsHeader.amazonaws.com")
					.withAttributeNames("All").withMessageAttributeNames("All")
					.withMaxNumberOfMessages(10).withWaitTimeSeconds(20))).thenReturn(
							new ReceiveMessageResult().withMessages(new Message()
									.withBody("messageContent")
									.withAttributes(Collections
											.singletonMap("SenderId", "ID"))
									.withMessageAttributes(Collections
											.singletonMap(MessageHeaders.CONTENT_TYPE,
													new MessageAttributeValue()
															.withDataType("String")
															.withStringValue(mimeType
																	.toString())))))
							.thenReturn(new ReceiveMessageResult());
	when(sqs.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());

	// Act
	container.start();

	// Assert
	assertThat(countDownLatch.await(2L, TimeUnit.SECONDS)).isTrue();
	container.stop();

	verify(messageHandler).handleMessage(this.stringMessageCaptor.capture());
	assertThat(this.stringMessageCaptor.getValue().getHeaders()
			.get(MessageHeaders.CONTENT_TYPE)).isEqualTo(mimeType);
}
 
Example #22
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void messageExecutor_withMessageWithAttributes_shouldPassThemAsHeaders()
		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, withSettings().stubOnly());
	container.setAmazonSqs(sqs);

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

	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("testMessageListener",
			TestMessageListener.class);

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

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

	when(sqs.receiveMessage(new ReceiveMessageRequest(
			"https://messageExecutor_withMessageWithAttributes_shouldPassThemAsHeaders.amazonaws.com")
					.withAttributeNames("All").withMessageAttributeNames("All")
					.withMaxNumberOfMessages(10).withWaitTimeSeconds(20))).thenReturn(
							new ReceiveMessageResult().withMessages(new Message()
									.withBody("messageContent")
									.withAttributes(new HashMap<String, String>() {
										{
											put("SenderId", "ID");
											put("SentTimestamp", "1000");
											put("ApproximateFirstReceiveTimestamp",
													"2000");
										}
									})))
							.thenReturn(new ReceiveMessageResult());
	when(sqs.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());

	// Act
	container.start();

	// Assert
	assertThat(countDownLatch.await(2L, TimeUnit.SECONDS)).isTrue();
	container.stop();

	verify(messageHandler).handleMessage(this.stringMessageCaptor.capture());
	assertThat(this.stringMessageCaptor.getValue().getHeaders().get("SenderId"))
			.isEqualTo("ID");
	assertThat(this.stringMessageCaptor.getValue().getHeaders().getTimestamp())
			.isEqualTo(1000L);
	assertThat(this.stringMessageCaptor.getValue().getHeaders()
			.get("ApproximateFirstReceiveTimestamp")).isEqualTo("2000");

}
 
Example #23
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void testSimpleReceiveMessage() throws Exception {
	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();

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

	CountDownLatch countDownLatch = new CountDownLatch(1);
	QueueMessageHandler messageHandler = new QueueMessageHandler() {

		@Override
		public void handleMessage(org.springframework.messaging.Message<?> message)
				throws MessagingException {
			countDownLatch.countDown();
			assertThat(message.getPayload()).isEqualTo("messageContent");
		}
	};
	container.setMessageHandler(messageHandler);
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("testMessageListener",
			TestMessageListener.class);
	messageHandler.setApplicationContext(applicationContext);
	container.setBeanName("testContainerName");
	messageHandler.afterPropertiesSet();

	mockGetQueueUrl(sqs, "testQueue",
			"http://testSimpleReceiveMessage.amazonaws.com");
	mockGetQueueAttributesWithEmptyResult(sqs,
			"http://testSimpleReceiveMessage.amazonaws.com");

	container.afterPropertiesSet();

	when(sqs.receiveMessage(
			new ReceiveMessageRequest("http://testSimpleReceiveMessage.amazonaws.com")
					.withAttributeNames("All").withMessageAttributeNames("All")
					.withMaxNumberOfMessages(10).withWaitTimeSeconds(20)))
							.thenReturn(new ReceiveMessageResult().withMessages(
									new Message().withBody("messageContent"),
									new Message().withBody("messageContent")))
							.thenReturn(new ReceiveMessageResult());
	when(sqs.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());

	container.start();

	assertThat(countDownLatch.await(1, TimeUnit.SECONDS)).isTrue();

	container.stop();
}
 
Example #24
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
private static void mockGetQueueAttributesWithEmptyResult(AmazonSQSAsync sqs,
		String queueUrl) {
	when(sqs.getQueueAttributes(new GetQueueAttributesRequest(queueUrl)
			.withAttributeNames(QueueAttributeName.RedrivePolicy)))
					.thenReturn(new GetQueueAttributesResult());
}
 
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 getQueueAttributes() {
    assertWrappedMethod(AmazonSQS::getQueueAttributes, new GetQueueAttributesRequest());
}
 
Example #26
Source File: AbstractAmazonSQSClientWrapper.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 4 votes vote down vote up
@Override
public GetQueueAttributesResult getQueueAttributes(GetQueueAttributesRequest request) {
    request.getRequestClientOptions().appendUserAgent(userAgent);
    return amazonSqsToBeExtended.getQueueAttributes(request);
}
 
Example #27
Source File: AmazonSQSVirtualQueuesClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 4 votes vote down vote up
@Override
public GetQueueAttributesResult getQueueAttributes(GetQueueAttributesRequest request) {
    return getVirtualQueue(request.getQueueUrl())
            .map(virtualQueue -> virtualQueue.getQueueAttributes(request))
            .orElseGet(() -> amazonSqsToBeExtended.getQueueAttributes(request));
}
 
Example #28
Source File: AmazonSQSExtendedClientBase.java    From amazon-sqs-java-extended-client-lib with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Gets attributes for the specified queue. The following attributes are
 * supported:
 * <ul>
 * <li> <code>All</code> - returns all values.</li>
 * <li> <code>ApproximateNumberOfMessages</code> - returns the approximate
 * number of visible messages in a queue. For more information, see <a href=
 * "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ApproximateNumber.html"
 * > Resources Required to Process Messages </a> in the <i>Amazon SQS
 * Developer Guide</i> .</li>
 * <li> <code>ApproximateNumberOfMessagesNotVisible</code> - returns the
 * approximate number of messages that are not timed-out and not deleted.
 * For more information, see <a href=
 * "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ApproximateNumber.html"
 * > Resources Required to Process Messages </a> in the <i>Amazon SQS
 * Developer Guide</i> .</li>
 * <li> <code>VisibilityTimeout</code> - returns the visibility timeout for
 * the queue. For more information about visibility timeout, see <a href=
 * "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html"
 * > Visibility Timeout </a> in the <i>Amazon SQS Developer Guide</i> .</li>
 * <li> <code>CreatedTimestamp</code> - returns the time when the queue was
 * created (epoch time in seconds).</li>
 * <li> <code>LastModifiedTimestamp</code> - returns the time when the queue
 * was last changed (epoch time in seconds).</li>
 * <li> <code>Policy</code> - returns the queue's policy.</li>
 * <li> <code>MaximumMessageSize</code> - returns the limit of how many bytes
 * a message can contain before Amazon SQS rejects it.</li>
 * <li> <code>MessageRetentionPeriod</code> - returns the number of seconds
 * Amazon SQS retains a message.</li>
 * <li> <code>QueueArn</code> - returns the queue's Amazon resource name
 * (ARN).</li>
 * <li> <code>ApproximateNumberOfMessagesDelayed</code> - returns the
 * approximate number of messages that are pending to be added to the queue.
 * </li>
 * <li> <code>DelaySeconds</code> - returns the default delay on the queue in
 * seconds.</li>
 * <li> <code>ReceiveMessageWaitTimeSeconds</code> - returns the time for
 * which a ReceiveMessage call will wait for a message to arrive.</li>
 * <li> <code>RedrivePolicy</code> - returns the parameters for dead letter
 * queue functionality of the source queue. For more information about
 * RedrivePolicy and dead letter queues, see <a href=
 * "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSDeadLetterQueue.html"
 * > Using Amazon SQS Dead Letter Queues </a> in the <i>Amazon SQS Developer
 * Guide</i> .</li>
 * 
 * </ul>
 * 
 * </p>
 * <p>
 * <b>NOTE:</b>Going forward, new attributes might be added. If you are
 * writing code that calls this action, we recommend that you structure your
 * code so that it can handle new attributes gracefully.
 * </p>
 * <p>
 * <b>NOTE:</b>Some API actions take lists of parameters. These lists are
 * specified using the param.n notation. Values of n are integers starting
 * from 1. For example, a parameter list with two elements looks like this:
 * </p>
 * <p>
 * <code>&Attribute.1=this</code>
 * </p>
 * <p>
 * <code>&Attribute.2=that</code>
 * </p>
 *
 * @param getQueueAttributesRequest
 *            Container for the necessary parameters to execute the
 *            GetQueueAttributes service method on AmazonSQS.
 * 
 * @return The response from the GetQueueAttributes service method, as
 *         returned by AmazonSQS.
 * 
 * @throws InvalidAttributeNameException
 *
 * @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 GetQueueAttributesResult getQueueAttributes(GetQueueAttributesRequest getQueueAttributesRequest)
		throws AmazonServiceException, AmazonClientException {

	return amazonSqsToBeExtended.getQueueAttributes(getQueueAttributesRequest);
}
 
Example #29
Source File: Queue.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Makes a call to the service to load this resource's attributes if they
 * are not loaded yet.
 * The following request parameters will be populated from the data of this
 * <code>Queue</code> resource, and any conflicting parameter value set in
 * the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>QueueUrl</code></b>
 *         - mapped from the <code>Url</code> identifier.
 *   </li>
 *   <li>
 *     <b><code>AttributeNames.0</code></b>
 *         - constant value <code>All</code>.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return Returns {@code true} if the resource is not yet loaded when this
 *         method was invoked, which indicates that a service call has been
 *         made to retrieve the attributes.
 * @see GetQueueAttributesRequest
 */
boolean load(GetQueueAttributesRequest request);
 
Example #30
Source File: Queue.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Makes a call to the service to load this resource's attributes if they
 * are not loaded yet, and use a ResultCapture to retrieve the low-level
 * client response
 * The following request parameters will be populated from the data of this
 * <code>Queue</code> resource, and any conflicting parameter value set in
 * the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>QueueUrl</code></b>
 *         - mapped from the <code>Url</code> identifier.
 *   </li>
 *   <li>
 *     <b><code>AttributeNames.0</code></b>
 *         - constant value <code>All</code>.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return Returns {@code true} if the resource is not yet loaded when this
 *         method was invoked, which indicates that a service call has been
 *         made to retrieve the attributes.
 * @see GetQueueAttributesRequest
 */
boolean load(GetQueueAttributesRequest request,
        ResultCapture<GetQueueAttributesResult> extractor);