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

The following examples show how to use com.amazonaws.services.sqs.model.CreateQueueRequest. 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: 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 #2
Source File: AmazonSQSRequesterClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Message> sendMessageAndGetResponseAsync(SendMessageRequest request, int timeout, TimeUnit unit) {
    String queueName = queuePrefix + UUID.randomUUID().toString();
    CreateQueueRequest createQueueRequest = new CreateQueueRequest()
            .withQueueName(queueName)
            .withAttributes(queueAttributes);
    String responseQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

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

    CompletableFuture<Message> future = new CompletableFuture<>();
    
    // TODO-RS: accept an AmazonSQSAsync instead and use its threads instead of our own.
    // TODO-RS: complete the future exceptionally, for the right set of SQS exceptions
    SQSMessageConsumer consumer = new ResponseListener(responseQueueUrl, future);
    responseConsumers.add(consumer);
    consumer.runFor(timeout, unit);
    return future;
}
 
Example #3
Source File: AmazonSQSTemporaryQueuesClientBuilderIT.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
@Test
public void supportsBothFeatures() {
    AmazonSQS sqs = AmazonSQSTemporaryQueuesClientBuilder.standard()
            .withQueuePrefix(queueNamePrefix)
            .build();
    String hostQueueUrl = sqs.createQueue(new CreateQueueRequest()
            .withQueueName(queueNamePrefix + "Host")
            .addAttributesEntry("IdleQueueRetentionPeriodSeconds", "300")).getQueueUrl();
    GetQueueAttributesResult result = sqs.getQueueAttributes(hostQueueUrl, Collections.singletonList("IdleQueueRetentionPeriodSeconds"));
    assertEquals("300", result.getAttributes().get("IdleQueueRetentionPeriodSeconds"));
    
    String virtualQueueUrl = sqs.createQueue(new CreateQueueRequest()
            .withQueueName(queueNamePrefix + "VirtualQueue")
            .addAttributesEntry("HostQueueUrl", hostQueueUrl)
            .addAttributesEntry("IdleQueueRetentionPeriodSeconds", "300")).getQueueUrl();
    
    result = sqs.getQueueAttributes(virtualQueueUrl, 
            Arrays.asList("HostQueueUrl", "IdleQueueRetentionPeriodSeconds"));
    assertEquals(hostQueueUrl, result.getAttributes().get("HostQueueUrl"));
    assertEquals("300", result.getAttributes().get("IdleQueueRetentionPeriodSeconds"));
    
}
 
Example #4
Source File: AmazonSQSTemporaryQueuesClientBuilderIT.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
@Test
public void supportsTurningOffIdleQueueSweeping() {
    AmazonSQS sqs = AmazonSQSTemporaryQueuesClientBuilder.standard()
            .withQueuePrefix(queueNamePrefix)
            .withIdleQueueSweepingPeriod(0, TimeUnit.MINUTES)
            .build();
    String hostQueueUrl = sqs.createQueue(new CreateQueueRequest()
            .withQueueName(queueNamePrefix + "Host")
            .addAttributesEntry("IdleQueueRetentionPeriodSeconds", "300")).getQueueUrl();
    GetQueueAttributesResult result = sqs.getQueueAttributes(hostQueueUrl, Collections.singletonList("IdleQueueRetentionPeriodSeconds"));
    assertEquals("300", result.getAttributes().get("IdleQueueRetentionPeriodSeconds"));
    
    String virtualQueueUrl = sqs.createQueue(new CreateQueueRequest()
            .withQueueName(queueNamePrefix + "VirtualQueue")
            .addAttributesEntry("HostQueueUrl", hostQueueUrl)
            .addAttributesEntry("IdleQueueRetentionPeriodSeconds", "300")).getQueueUrl();
    
    result = sqs.getQueueAttributes(virtualQueueUrl, 
            Arrays.asList("HostQueueUrl", "IdleQueueRetentionPeriodSeconds"));
    assertEquals(hostQueueUrl, result.getAttributes().get("HostQueueUrl"));
    assertEquals("300", result.getAttributes().get("IdleQueueRetentionPeriodSeconds"));
}
 
Example #5
Source File: AmazonSQSVirtualQueuesClientIT.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
@Test
public void ReceiveMessageWaitTimeSecondsNull() {
    CreateQueueRequest request = new CreateQueueRequest()
            .withQueueName("ReceiveMessageWaitTimeSecondsNull")
            .addAttributesEntry(AmazonSQSVirtualQueuesClient.VIRTUAL_QUEUE_HOST_QUEUE_ATTRIBUTE, hostQueueUrl)
            .addAttributesEntry(AmazonSQSIdleQueueDeletingClient.IDLE_QUEUE_RETENTION_PERIOD, "5");
    String virtualQueueUrl = client.createQueue(request).getQueueUrl();

    // Do Receive message request with null WaitTimeSeconds.
    ReceiveMessageRequest receiveRequest = new ReceiveMessageRequest()
            .withQueueUrl(virtualQueueUrl);
    try {
        assertEquals(0, client.receiveMessage(receiveRequest).getMessages().size());
    } catch (NullPointerException npe) {
        fail("NPE not expected with null WaitTimeSeconds on ReceiveMessageRequest");
    }
}
 
Example #6
Source File: SQSScanWorkflow.java    From emodb with Apache License 2.0 5 votes vote down vote up
private String queryQueueUrl(String queueName) {
    try {
        return _sqs.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl();
    } catch (QueueDoesNotExistException e) {
        // Create the queue
        int visibilityTimeout = queueName.equals(_pendingScanRangeQueue) ?
                DEFAULT_TASK_CLAIM_VISIBILITY_TIMEOUT : DEFAULT_TASK_COMPLETE_VISIBILITY_TIMEOUT;
        return _sqs.createQueue(
                new CreateQueueRequest(queueName)
                        .withAttributes(ImmutableMap.<String, String>of(
                                "VisibilityTimeout", String.valueOf(visibilityTimeout)))
        ).getQueueUrl();
    }
}
 
Example #7
Source File: AmazonSQSStubTest.java    From aws-java-sdk-stubs with Apache License 2.0 5 votes vote down vote up
@Test
public void createQueue() {
  final String queueName = "bizo";

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

  final ListQueuesResult listQueuesResult = sqs.listQueues();
  assertThat(listQueuesResult.getQueueUrls(), hasItem(containsString(queueName)));
}
 
Example #8
Source File: SQSTestBase.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
/**
 * create a queue we can use for testing
 *
 * @throws Exception
 */
@Before
public void beforTest() throws Exception
{
  validateAssumption();
  // Create a queue
  CreateQueueRequest createQueueRequest = new CreateQueueRequest().withQueueName(getCurrentQueueName());
  currentQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();
}
 
Example #9
Source File: AWSSQSClient.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
public String getQueue(String queue) {
    final Map<String, String> queueAttributes = new HashMap<>();

    final CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest(queue)
            .withAttributes(queueAttributes);

    return sqs.createQueue(createFifoQueueRequest)
            .getQueueUrl();
}
 
Example #10
Source File: AmazonSQSStubTest.java    From aws-java-sdk-stubs with Apache License 2.0 5 votes vote down vote up
@Test
public void getQueueUrl() {
  final String queueName = "bizo";

  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();
  assertThat(queueUrl, containsString(queueName));
}
 
Example #11
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 #12
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 #13
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 #14
Source File: DynamicQueueUrlDestinationResolver.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
public String resolveDestination(String name) throws DestinationResolutionException {
	String queueName = name;

	if (this.resourceIdResolver != null) {
		queueName = this.resourceIdResolver.resolveToPhysicalResourceId(name);
	}

	if (isValidQueueUrl(queueName)) {
		return queueName;
	}

	if (this.autoCreate) {
		// Auto-create is fine to be called even if the queue exists.
		CreateQueueResult createQueueResult = this.amazonSqs
				.createQueue(new CreateQueueRequest(queueName));
		return createQueueResult.getQueueUrl();
	}
	else {
		try {
			GetQueueUrlResult getQueueUrlResult = this.amazonSqs
					.getQueueUrl(new GetQueueUrlRequest(queueName));
			return getQueueUrlResult.getQueueUrl();
		}
		catch (QueueDoesNotExistException e) {
			throw toDestinationResolutionException(e);
		}
	}
}
 
Example #15
Source File: DynamicQueueUrlDestinationResolverTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testAutoCreate() throws Exception {
	AmazonSQS amazonSqs = mock(AmazonSQS.class);
	String queueUrl = "https://foo/bar";
	when(amazonSqs.createQueue(new CreateQueueRequest("foo")))
			.thenReturn(new CreateQueueResult().withQueueUrl(queueUrl));

	DynamicQueueUrlDestinationResolver dynamicQueueDestinationResolver = new DynamicQueueUrlDestinationResolver(
			amazonSqs);
	dynamicQueueDestinationResolver.setAutoCreate(true);
	assertThat(dynamicQueueDestinationResolver.resolveDestination("foo"))
			.isEqualTo(queueUrl);
}
 
Example #16
Source File: TemporarySQSQueue.java    From front50 with Apache License 2.0 5 votes vote down vote up
private TemporaryQueue createQueue(String snsTopicArn, String sqsQueueArn, String sqsQueueName) {
  String sqsQueueUrl =
      amazonSQS
          .createQueue(
              new CreateQueueRequest()
                  .withQueueName(sqsQueueName)
                  .withAttributes(
                      Collections.singletonMap(
                          "MessageRetentionPeriod", "60")) // 60s message retention
              )
          .getQueueUrl();
  log.info("Created Temporary S3 Notification Queue: {}", value("queue", sqsQueueUrl));

  String snsTopicSubscriptionArn =
      amazonSNS.subscribe(snsTopicArn, "sqs", sqsQueueArn).getSubscriptionArn();

  Statement snsStatement =
      new Statement(Statement.Effect.Allow).withActions(SQSActions.SendMessage);
  snsStatement.setPrincipals(Principal.All);
  snsStatement.setResources(Collections.singletonList(new Resource(sqsQueueArn)));
  snsStatement.setConditions(
      Collections.singletonList(
          new Condition()
              .withType("ArnEquals")
              .withConditionKey("aws:SourceArn")
              .withValues(snsTopicArn)));

  Policy allowSnsPolicy = new Policy("allow-sns", Collections.singletonList(snsStatement));

  HashMap<String, String> attributes = new HashMap<>();
  attributes.put("Policy", allowSnsPolicy.toJson());
  amazonSQS.setQueueAttributes(sqsQueueUrl, attributes);

  return new TemporaryQueue(snsTopicArn, sqsQueueArn, sqsQueueUrl, snsTopicSubscriptionArn);
}
 
Example #17
Source File: SQSImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public Queue createQueue(CreateQueueRequest request,
        ResultCapture<CreateQueueResult> extractor) {

    ActionResult result = service.performAction("CreateQueue", request,
            extractor);

    if (result == null) return null;
    return new QueueImpl(result.getResource());
}
 
Example #18
Source File: SQSImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public Queue createQueue(String queueName, ResultCapture<CreateQueueResult>
        extractor) {

    CreateQueueRequest request = new CreateQueueRequest()
        .withQueueName(queueName);
    return createQueue(request, extractor);
}
 
Example #19
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 testCreateQueueWithNameThrowAmazonClientException() throws JMSException {

    doThrow(new AmazonClientException("ace"))
            .when(amazonSQSClient).createQueue(eq(new CreateQueueRequest(QUEUE_NAME)));

    wrapper.createQueue(QUEUE_NAME);
}
 
Example #20
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 testCreateQueueWithNameThrowAmazonServiceException() throws JMSException {

    doThrow(new AmazonServiceException("ase"))
            .when(amazonSQSClient).createQueue(eq(new CreateQueueRequest(QUEUE_NAME)));

    wrapper.createQueue(QUEUE_NAME);
}
 
Example #21
Source File: AmazonSQSMessagingClientWrapperTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateQueue() throws JMSException {

    CreateQueueRequest createQueueRequest = new CreateQueueRequest(QUEUE_NAME);

    wrapper.createQueue(createQueueRequest);
    verify(amazonSQSClient).createQueue(createQueueRequest);
}
 
Example #22
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 testCreateQueueThrowAmazonClientException() throws JMSException {

    CreateQueueRequest createQueueRequest = new CreateQueueRequest(QUEUE_NAME);
    doThrow(new AmazonClientException("ace"))
            .when(amazonSQSClient).createQueue(eq(createQueueRequest));

    wrapper.createQueue(createQueueRequest);
}
 
Example #23
Source File: SqsExecutor.java    From spring-integration-aws with MIT License 5 votes vote down vote up
private void createQueueIfNotExists() {
	for (String qUrl : sqsClient.listQueues().getQueueUrls()) {
		if (qUrl.contains(queueName)) {
			queueUrl = qUrl;
			break;
		}
	}
	if (queueUrl == null) {
		CreateQueueRequest request = new CreateQueueRequest(queueName);
		Map<String, String> queueAttributes = new HashMap<String, String>();
		queueAttributes.put("ReceiveMessageWaitTimeSeconds", Integer
				.valueOf(receiveMessageWaitTimeout).toString());
		if (messageDelay != null) {
			queueAttributes.put("DelaySeconds", messageDelay.toString());
		}
		if (maximumMessageSize != null) {
			queueAttributes.put("MaximumMessageSize",
					maximumMessageSize.toString());
		}
		if (messageRetentionPeriod != null) {
			queueAttributes.put("MessageRetentionPeriod",
					messageRetentionPeriod.toString());
		}
		if (visibilityTimeout != null) {
			queueAttributes.put("VisibilityTimeout",
					visibilityTimeout.toString());
		}
		request.setAttributes(queueAttributes);
		CreateQueueResult result = sqsClient.createQueue(request);
		queueUrl = result.getQueueUrl();
		log.debug("New queue available at: " + queueUrl);
	} else {
		log.debug("Queue already exists: " + queueUrl);
	}

	resolveQueueArn();
}
 
Example #24
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 #25
Source File: SpringLocalstackDockerRunnerTest.java    From spring-localstack with Apache License 2.0 5 votes vote down vote up
@Test
public void testSQS() throws Exception {
    AmazonSQS client = amazonDockerClientsHolder.amazonSQS();

    Map<String, String> attributeMap = new HashMap<>();
    attributeMap.put("DelaySeconds", "0");
    attributeMap.put("MaximumMessageSize", "262144");
    attributeMap.put("MessageRetentionPeriod", "1209600");
    attributeMap.put("ReceiveMessageWaitTimeSeconds", "20");
    attributeMap.put("VisibilityTimeout", "30");

    CreateQueueRequest createQueueRequest = new CreateQueueRequest("test-queue").withAttributes(attributeMap);
    client.createQueue(createQueueRequest);

    ListQueuesResult listQueuesResult = client.listQueues();
    assertThat(listQueuesResult.getQueueUrls().size(), is(1));

    SQSConnection connection = createSQSConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    Queue queue = session.createQueue("test-queue");

    MessageProducer producer = session.createProducer(queue);
    TextMessage message = session.createTextMessage("Hello World!");
    producer.send(message);

    MessageConsumer consumer = session.createConsumer(queue);
    TextMessage received = (TextMessage) consumer.receive();
    assertThat(received.getText(), is("Hello World!"));
}
 
Example #26
Source File: AmazonSQSTemporaryQueuesClient.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) {
    // Check for unsupported queue attributes first
    Set<String> unsupportedQueueAttributes = new HashSet<>(request.getAttributes().keySet());
    unsupportedQueueAttributes.removeAll(SUPPORTED_QUEUE_ATTRIBUTES);
    if (!unsupportedQueueAttributes.isEmpty()) {
        throw new IllegalArgumentException("Cannot create a temporary queue with the following attributes: "
                + String.join(", ", unsupportedQueueAttributes));
    }

    Map<String, String> extraQueueAttributes = new HashMap<>();
    // Add the retention period to both the host queue and each virtual queue
    extraQueueAttributes.put(AmazonSQSIdleQueueDeletingClient.IDLE_QUEUE_RETENTION_PERIOD, QUEUE_RETENTION_PERIOD_SECONDS);
    String hostQueueUrl = hostQueueUrls.computeIfAbsent(request.getAttributes(), attributes -> {
        CreateQueueRequest hostQueueCreateRequest = SQSQueueUtils.copyWithExtraAttributes(request, extraQueueAttributes);
        hostQueueCreateRequest.setQueueName(prefix + '-' + hostQueueUrls.size());
        return amazonSqsToBeExtended.createQueue(hostQueueCreateRequest).getQueueUrl();
    });

    extraQueueAttributes.put(AmazonSQSVirtualQueuesClient.VIRTUAL_QUEUE_HOST_QUEUE_ATTRIBUTE, hostQueueUrl);
    // The host queue takes care of all the other queue attributes, so don't specify them when creating the virtual
    // queue or else the client may think we're trying to set them independently!
    CreateQueueRequest createVirtualQueueRequest = new CreateQueueRequest()
            .withQueueName(request.getQueueName())
            .withAttributes(extraQueueAttributes);
    return amazonSqsToBeExtended.createQueue(createVirtualQueueRequest);
}
 
Example #27
Source File: AmazonSQSIdleQueueDeletingClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
private String createOrUpdateQueue(String name, Map<String, String> attributes) {
    try {
        return super.createQueue(new CreateQueueRequest()
                .withQueueName(name)
                .withAttributes(attributes)).getQueueUrl();
    } catch (QueueNameExistsException e) {
        String queueUrl = super.getQueueUrl(name).getQueueUrl();
        super.setQueueAttributes(new SetQueueAttributesRequest()
                .withQueueUrl(queueUrl)
                .withAttributes(attributes));
        return queueUrl;
    }
}
 
Example #28
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 #29
Source File: AmazonSQSVirtualQueuesClient.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) {
    String hostQueueUrl = request.getAttributes().get(VIRTUAL_QUEUE_HOST_QUEUE_ATTRIBUTE);
    if (hostQueueUrl == null) {
        return amazonSqsToBeExtended.createQueue(request);
    }

    Map<String, String> attributes = new HashMap<>(request.getAttributes());
    attributes.remove(VIRTUAL_QUEUE_HOST_QUEUE_ATTRIBUTE);

    Optional<Long> retentionPeriod = AmazonSQSIdleQueueDeletingClient.getRetentionPeriod(attributes);

    if (!attributes.isEmpty()) {
        throw new IllegalArgumentException("Virtual queues do not support setting these queue attributes independently of their host queues: "
                + attributes.keySet());
    }

    HostQueue host = hostQueues.computeIfAbsent(hostQueueUrl, HostQueue::new);
    VirtualQueue virtualQueue = new VirtualQueue(host, request.getQueueName(), retentionPeriod);

    // There is clearly a race condition here between checking the size and
    // adding to the map, but that's fine since this is just a loose upper bound
    // and it avoids synchronizing all calls on something like an AtomicInteger.
    // The worse case scenario is that the map has X entries more than the maximum
    // where X is the number of threads concurrently creating queues.
    if (virtualQueues.size() > MAXIMUM_VIRTUAL_QUEUES_COUNT) {
        throw new IllegalStateException("Cannot create virtual queue: the number of virtual queues would exceed the maximum of "
                + MAXIMUM_VIRTUAL_QUEUES_COUNT);
    }
    virtualQueues.put(virtualQueue.getID().getVirtualQueueName(), virtualQueue);

    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Total Virtual Queue Created is %s and Queue Name is %s", virtualQueues.size(), virtualQueue.getID().getVirtualQueueName()));
    }

    return new CreateQueueResult().withQueueUrl(virtualQueue.getID().getQueueUrl());
}
 
Example #30
Source File: SQSQueueUtils.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
public static CreateQueueRequest copyWithExtraAttributes(CreateQueueRequest request, Map<String, String> extraAttrs) {
    Map<String, String> newAttributes = new HashMap<>(request.getAttributes());
    newAttributes.putAll(extraAttrs);

    // Clone to create a shallow copy that includes the superclass properties.
    return request.clone()
            .withQueueName(request.getQueueName())
            .withAttributes(newAttributes);
}