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

The following examples show how to use com.amazonaws.services.sqs.model.QueueAttributeName. 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: 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 #2
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 #3
Source File: AmazonSQSIdleQueueDeletingClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
protected synchronized void startSweeper(AmazonSQSRequester requester, AmazonSQSResponder responder,
                                         long period, TimeUnit unit,
                                         Consumer<Exception> exceptionHandler) {
    if (this.idleQueueSweeper != null) {
        throw new IllegalStateException("Idle queue sweeper is already started!");
    }

    // Create the DLQ first so the primary queue can reference it
    // Note that SSE doesn't have to be enabled on this queue since the messages
    // will already be encrypted in the primary queue, and dead-lettering doesn't affect that.
    // The messages will still be receivable from the DLQ regardless.
    Map<String, String> dlqAttributes = new HashMap<>();
    dlqAttributes.put(QueueAttributeName.MessageRetentionPeriod.name(), Long.toString(DLQ_MESSAGE_RETENTION_PERIOD));
    deadLetterQueueUrl = createOrUpdateQueue(queueNamePrefix + SWEEPING_QUEUE_DLQ_SUFFIX, dlqAttributes);
    String deadLetterQueueArn = super.getQueueAttributes(deadLetterQueueUrl,
            Collections.singletonList(QueueAttributeName.QueueArn.name()))
                    .getAttributes().get(QueueAttributeName.QueueArn.name());

    Map<String, String> queueAttributes = new HashMap<>();
    // Server-side encryption is important here because we're putting
    // queue URLs into this queue.
    queueAttributes.put(QueueAttributeName.KmsMasterKeyId.toString(), "alias/aws/sqs");
    queueAttributes.put(QueueAttributeName.RedrivePolicy.toString(),
            "{\"maxReceiveCount\":\"5\", \"deadLetterTargetArn\":\"" + deadLetterQueueArn + "\"}");
    // TODO-RS: Configure a tight MessageRetentionPeriod! Put explicit thought
    // into other configuration as well.
    String sweepingQueueUrl = createOrUpdateQueue(queueNamePrefix, queueAttributes);

    this.idleQueueSweeper = new IdleQueueSweeper(requester, responder, sweepingQueueUrl, queueNamePrefix,
            period, unit, exceptionHandler);
}
 
Example #4
Source File: AmazonSQSIdleQueueDeletingClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
@Override
public CreateQueueResult createQueue(CreateQueueRequest request) {
    Map<String, String> attributes = new HashMap<>(request.getAttributes());
    Optional<Long> retentionPeriod = getRetentionPeriod(attributes);
    if (!retentionPeriod.isPresent()) {
        return super.createQueue(request);
    }

    String queueName = request.getQueueName();
    if (!queueName.startsWith(queueNamePrefix)) {
        throw new IllegalArgumentException();
    }

    CreateQueueRequest superRequest = request.clone()
            .withQueueName(queueName)
            .withAttributes(attributes);

    CreateQueueResult result = super.createQueue(superRequest);
    String queueUrl = result.getQueueUrl();

    String retentionPeriodString = retentionPeriod.get().toString();
    amazonSqsToBeExtended.tagQueue(queueUrl,
            Collections.singletonMap(IDLE_QUEUE_RETENTION_PERIOD_TAG, retentionPeriodString));

    // TODO-RS: Filter more carefully to all attributes valid for createQueue 
    List<String> attributeNames = Arrays.asList(QueueAttributeName.ReceiveMessageWaitTimeSeconds.toString(),
                                                QueueAttributeName.VisibilityTimeout.toString());
    Map<String, String> createdAttributes = amazonSqsToBeExtended.getQueueAttributes(queueUrl, attributeNames).getAttributes();
    createdAttributes.put(IDLE_QUEUE_RETENTION_PERIOD, retentionPeriodString);

    QueueMetadata metadata = new QueueMetadata(queueName, queueUrl, createdAttributes);
    queues.put(queueUrl, metadata);

    metadata.heartbeater = executor.scheduleAtFixedRate(() -> heartbeatToQueue(queueUrl), 
            0, heartbeatIntervalSeconds, TimeUnit.SECONDS);

    return result;
}
 
Example #5
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 #6
Source File: AmazonSQSTemporaryQueuesClientIT.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
@Test
public void createQueueWithUnsupportedAttributes() {
    try {
        client.createQueue(new CreateQueueRequest()
                .withQueueName(queueNamePrefix + "InvalidQueue")
                .withAttributes(Collections.singletonMap(QueueAttributeName.FifoQueue.name(), "true")));
        Assert.fail("Shouldn't be able to create a FIFO temporary queue");
    } catch (IllegalArgumentException e) {
        Assert.assertEquals("Cannot create a temporary queue with the following attributes: FifoQueue", e.getMessage());
    }
}
 
Example #7
Source File: AmazonSQSResponsesClientCrossAccountIT.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    // Use the secondary role for the responder
    sqsResponder = new AmazonSQSResponderClient(getBuddyPrincipalClient());

    String policyString = allowSendMessagePolicy(getBuddyRoleARN()).toJson();
    sqsRequester = new AmazonSQSRequesterClient(sqs, queueNamePrefix,
            Collections.singletonMap(QueueAttributeName.Policy.toString(), policyString),
            exceptionHandler);

    requestQueueUrl = sqs.createQueue("RequestQueue-" + UUID.randomUUID().toString()).getQueueUrl();
}
 
Example #8
Source File: AmazonSQSTemporaryQueuesClientCrossAccountIT.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
@Test
public void withAccess() {
    String policyString = allowSendMessagePolicy(getBuddyRoleARN()).toJson();
    CreateQueueRequest createQueueRequest = new CreateQueueRequest()
            .withQueueName(queueNamePrefix + "TestQueueWithAccess")
            .withAttributes(Collections.singletonMap(QueueAttributeName.Policy.toString(), policyString));

    String queueUrl = client.createQueue(createQueueRequest).getQueueUrl();
    try {
        otherAccountClient.sendMessage(queueUrl, "Hi there!");
    } finally {
        client.deleteQueue(queueUrl);
    }
}
 
Example #9
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 #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: 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());
}