software.amazon.awssdk.services.sqs.SqsClient Java Examples

The following examples show how to use software.amazon.awssdk.services.sqs.SqsClient. 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: SQSExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static String createQueue(SqsClient sqsClient,String queueName ) {

        System.out.println("\nCreate queue");
        // snippet-start:[sqs.java2.sqs_example.create_queue]

        CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()
                .queueName(queueName)
                .build();

        sqsClient.createQueue(createQueueRequest);
        // snippet-end:[sqs.java2.sqs_example.create_queue]

        System.out.println("\nGet queue URL");
        // snippet-start:[sqs.java2.sqs_example.get_queue]
        GetQueueUrlResponse getQueueUrlResponse =
                sqsClient.getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());
        String queueUrl = getQueueUrlResponse.queueUrl();
        return queueUrl;
        // snippet-end:[sqs.java2.sqs_example.get_queue]
    }
 
Example #2
Source File: SqsIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testRead() {
  final SqsClient client = EmbeddedSqsServer.getClient();
  final String queueUrl = EmbeddedSqsServer.getQueueUrl();

  final PCollection<SqsMessage> output =
      pipeline.apply(
          SqsIO.read()
              .withSqsClientProvider(SqsClientProviderMock.of(client))
              .withQueueUrl(queueUrl)
              .withMaxNumRecords(100));

  PAssert.thatSingleton(output.apply(Count.globally())).isEqualTo(100L);

  for (int i = 0; i < 100; i++) {
    SendMessageRequest sendMessageRequest =
        SendMessageRequest.builder().queueUrl(queueUrl).messageBody("This is a test").build();
    client.sendMessage(sendMessageRequest);
  }
  pipeline.run();
}
 
Example #3
Source File: EmbeddedSqsServer.java    From beam with Apache License 2.0 6 votes vote down vote up
static void start() {
  sqsRestServer = SQSRestServerBuilder.withPort(port).start();

  client =
      SqsClient.builder()
          .credentialsProvider(
              StaticCredentialsProvider.create(AwsBasicCredentials.create("x", "x")))
          .endpointOverride(URI.create(endPoint))
          .region(Region.US_WEST_2)
          .build();

  CreateQueueRequest createQueueRequest =
      CreateQueueRequest.builder().queueName(queueName).build();
  final CreateQueueResponse queue = client.createQueue(createQueueRequest);
  queueUrl = queue.queueUrl();
}
 
Example #4
Source File: DeleteQueue.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void deleteSQSQueue(SqsClient sqsClient, String queueName) {

        try {

            GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
                    .queueName(queueName)
                    .build();

            String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();

            DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder()
                    .queueUrl(queueUrl)
                    .build();

            sqsClient.deleteQueue(deleteQueueRequest);

        } catch (QueueNameExistsException e) {
            e.printStackTrace();
            System.exit(1);
        }
        // snippet-end:[sqs.java2.sqs_example.delete_queue]
    }
 
Example #5
Source File: SendMessages.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void sendMessage(SqsClient sqsClient, String queueName, String message) {

        try {
            CreateQueueRequest request = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .build();
            CreateQueueResponse createResult = sqsClient.createQueue(request);

            GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
                .queueName(queueName)
                .build();

            String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();

            SendMessageRequest sendMsgRequest = SendMessageRequest.builder()
                .queueUrl(queueUrl)
                .messageBody(message)
                .delaySeconds(5)
                .build();
            sqsClient.sendMessage(sendMsgRequest);

        } catch (QueueNameExistsException e) {
            throw e;
        }
    }
 
Example #6
Source File: SendMessages.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE = "\n" +
                "SendMessages - send a message\n\n" +
                "Usage: SendMessages <queueName> <message>\n\n" +
                "Where:\n" +
                "  queueName - the name of the queue\n\n" +
                "  message - the message to send\n\n";

        if (args.length < 2) {
            System.out.println(USAGE);
            System.exit(1);
        }

        SqsClient sqsClient = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();

        String queueName = args[0];
        String message = args[1];

        sendMessage(sqsClient, queueName, message);
    }
 
Example #7
Source File: DeleteQueue.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE = "\n" +
                "DeleteQueue - delete a queue\n\n" +
                "Usage: DeleteQueue <queueName>\n\n" +
                "Where:\n" +
                "  queueName - the name of the queue\n\n" ;

        if (args.length < 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String queueName = args[0];

        SqsClient sqs = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();

        deleteSQSQueue(sqs, queueName);
    }
 
Example #8
Source File: VisibilityTimeout.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void changeMessageVisibilitySingle(
        String queueName, int timeout) {
    SqsClient sqs = SqsClient.builder().build();

    // Get the receipt handle for the first message in the queue
    ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder()
            .queueUrl(queueName)
            .build();
    String receipt = sqs.receiveMessage(receiveRequest)
            .messages()
            .get(0)
            .receiptHandle();

    ChangeMessageVisibilityRequest visibilityRequest = ChangeMessageVisibilityRequest.builder()
            .queueUrl(queueName)
            .receiptHandle(receipt)
            .visibilityTimeout(timeout)
            .build();
    sqs.changeMessageVisibility(visibilityRequest);
}
 
Example #9
Source File: SQSExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void listQueuesFilter(SqsClient sqsClient, String queueUrl ) {
    // List queues with filters
    String namePrefix = "queue";
    ListQueuesRequest filterListRequest = ListQueuesRequest.builder()
            .queueNamePrefix(namePrefix).build();

    ListQueuesResponse listQueuesFilteredResponse = sqsClient.listQueues(filterListRequest);
    System.out.println("Queue URLs with prefix: " + namePrefix);
    for (String url : listQueuesFilteredResponse.queueUrls()) {
        System.out.println(url);
    }

    System.out.println("\nSend message");
    // snippet-start:[sqs.java2.sqs_example.send_message]
    sqsClient.sendMessage(SendMessageRequest.builder()
            .queueUrl(queueUrl)
            .messageBody("Hello world!")
            .delaySeconds(10)
            .build());
    // snippet-end:[sqs.java2.sqs_example.send_message]
}
 
Example #10
Source File: VisibilityTimeout.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    final String queueName = "testQueue" + new Date().getTime();
    SqsClient sqs = SqsClient.builder().build();

    // First, create a queue (unless it already exists)
    CreateQueueRequest createRequest = CreateQueueRequest.builder()
            .queueName(queueName)
            .build();
    try {
        CreateQueueResponse cqResult = sqs.createQueue(createRequest);
    } catch (QueueNameExistsException e) {
        throw e;
    }

    GetQueueUrlRequest getRequest = GetQueueUrlRequest.builder()
            .queueName(queueName)
            .build();
    final String queue_url = sqs.getQueueUrl(getRequest).queueUrl();

    // Send some messages to the queue
    for (int i = 0; i < 20; i++) {
        SendMessageRequest sendRequest = SendMessageRequest.builder()
                .queueUrl(queueName)
                .messageBody("This is message " + i)
                .build();
        sqs.sendMessage(sendRequest);
    }

    // Change visibility timeout (single)
    changeMessageVisibilitySingle(queueName, 3600);

    // Change visibility timeout (multiple)
    changeMessageVisibilityMultiple(queueName, 2000);
}
 
Example #11
Source File: SQSExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void listQueues(SqsClient sqsClient) {

        System.out.println("\nList Queues");
        // snippet-start:[sqs.java2.sqs_example.list_queues]
        String prefix = "que";
        ListQueuesRequest listQueuesRequest = ListQueuesRequest.builder().queueNamePrefix(prefix).build();
        ListQueuesResponse listQueuesResponse = sqsClient.listQueues(listQueuesRequest);
        for (String url : listQueuesResponse.queueUrls()) {
            System.out.println(url);
        }
        // snippet-end:[sqs.java2.sqs_example.list_queues]
    }
 
Example #12
Source File: SQSExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void sendBatchMessages(SqsClient sqsClient, String queueUrl) {

        System.out.println("\nSend multiple messages");
        // snippet-start:[sqs.java2.sqs_example.send__multiple_messages]
        SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
                .queueUrl(queueUrl)
                .entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("Hello from msg 1").build(),
                        SendMessageBatchRequestEntry.builder().id("id2").messageBody("msg 2").delaySeconds(10).build())
                .build();
        sqsClient.sendMessageBatch(sendMessageBatchRequest);
        // snippet-end:[sqs.java2.sqs_example.send__multiple_messages]
    }
 
Example #13
Source File: SQSExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static  List<Message> receiveMessages(SqsClient sqsClient, String queueUrl) {


        System.out.println("\nReceive messages");
        // snippet-start:[sqs.java2.sqs_example.retrieve_messages]
        ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
                .queueUrl(queueUrl)
                .maxNumberOfMessages(5)
                .build();
        List<Message> messages = sqsClient.receiveMessage(receiveMessageRequest).messages();

        return messages;
        // snippet-end:[sqs.java2.sqs_example.retrieve_messages]
    }
 
Example #14
Source File: SQSExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void changeMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) {

        System.out.println("\nChange message visibility");
        for (Message message : messages) {
            ChangeMessageVisibilityRequest req = ChangeMessageVisibilityRequest.builder()
                    .queueUrl(queueUrl)
                    .receiptHandle(message.receiptHandle())
                    .visibilityTimeout(100)
                    .build();
            sqsClient.changeMessageVisibility(req);
        }

    }
 
Example #15
Source File: SQSExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void deleteMessages(SqsClient sqsClient, String queueUrl,  List<Message> messages) {
     System.out.println("\nDelete messages");
     // snippet-start:[sqs.java2.sqs_example.delete_message]
     for (Message message : messages) {
         DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
                 .queueUrl(queueUrl)
                 .receiptHandle(message.receiptHandle())
                 .build();
         sqsClient.deleteMessage(deleteMessageRequest);
     }
     // snippet-end:[sqs.java2.sqs_example.delete_message]
}
 
Example #16
Source File: SqsIOTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrite() {
  final SqsClient client = EmbeddedSqsServer.getClient();
  final String queueUrl = EmbeddedSqsServer.getQueueUrl();

  List<SendMessageRequest> messages = new ArrayList<>();
  for (int i = 0; i < 100; i++) {
    final SendMessageRequest request =
        SendMessageRequest.builder()
            .queueUrl(queueUrl)
            .messageBody("This is a test " + i)
            .build();
    messages.add(request);
  }

  pipeline
      .apply(Create.of(messages))
      .apply(SqsIO.write().withSqsClientProvider(SqsClientProviderMock.of(client)));
  pipeline.run().waitUntilFinish();

  List<String> received = new ArrayList<>();
  while (received.size() < 100) {
    ReceiveMessageRequest receiveMessageRequest =
        ReceiveMessageRequest.builder().queueUrl(queueUrl).build();
    final ReceiveMessageResponse receiveMessageResponse =
        client.receiveMessage(receiveMessageRequest);

    if (receiveMessageResponse != null) {
      for (Message message : receiveMessageResponse.messages()) {
        received.add(message.body());
      }
    }
  }

  assertEquals(100, received.size());
  for (int i = 0; i < 100; i++) {
    received.contains("This is a test " + i);
  }
}
 
Example #17
Source File: VisibilityTimeout.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void changeMessageVisibilityMultiple(String queue_url, int timeout) {
    SqsClient sqs = SqsClient.builder().build();

    List<ChangeMessageVisibilityBatchRequestEntry> entries =
            new ArrayList<ChangeMessageVisibilityBatchRequestEntry>();

    ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder()
            .queueUrl(queue_url)
            .build();

    String receipt = sqs.receiveMessage(receiveRequest)
            .messages()
            .get(0)
            .receiptHandle();

    entries.add(ChangeMessageVisibilityBatchRequestEntry.builder()
            .id("unique_id_msg1")
            .receiptHandle(receipt)
            .visibilityTimeout(timeout)
            .build());

    entries.add(ChangeMessageVisibilityBatchRequestEntry.builder()
            .id("unique_id_msg2")
            .receiptHandle(receipt)
            .visibilityTimeout(timeout + 200)
            .build());

    ChangeMessageVisibilityBatchRequest batchRequest = ChangeMessageVisibilityBatchRequest.builder()
            .queueUrl(queue_url)
            .entries(entries)
            .build();
    sqs.changeMessageVisibilityBatch(batchRequest);
}
 
Example #18
Source File: SQSServiceIntegrationTest.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void setUp() throws IOException {

    sqsClient = SqsClient.builder()
            .region(Region.US_WEST_2)
            .build();

    try (InputStream input = SQSServiceIntegrationTest.class.getClassLoader().getResourceAsStream("config.properties")) {

        Properties prop = new Properties();

        if (input == null) {
            System.out.println("Sorry, unable to find config.properties");
            return;
        }

        //load a properties file from class path, inside static method
        prop.load(input);

        // Populate the data members required for all tests
        queueName = prop.getProperty("QueueName");
        message = prop.getProperty("Message");
        dlqueueName=prop.getProperty("DLQueueName");


    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example #19
Source File: BasicSqsClientProvider.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public SqsClient getSqsClient() {
  SqsClientBuilder builder =
      SqsClient.builder().credentialsProvider(awsCredentialsProvider).region(Region.of(region));

  if (serviceEndpoint != null) {
    builder.endpointOverride(serviceEndpoint);
  }

  return builder.build();
}
 
Example #20
Source File: AwsSqsScanner.java    From clouditor with Apache License 2.0 5 votes vote down vote up
public AwsSqsScanner() {
  super(
      SqsClient::builder,
      queue ->
          ARN_PREFIX_SQS
              + ARN_SEPARATOR
              + ARN_RESOURCE_TYPE_QUEUE
              + RESOURCE_TYPE_SEPARATOR
              + queue.url(),
      Queue::url);
}
 
Example #21
Source File: DeadLetterQueues.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        SqsClient sqs = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();

        setDeadLetterQueue(sqs);
    }
 
Example #22
Source File: AwsSqsScannerTest.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void setUpOnce() throws IOException {
  discoverAssets(
      SqsClient.class,
      AwsSqsScanner::new,
      api -> {
        when(api.listQueues())
            .thenReturn(
                ListQueuesResponse.builder()
                    .queueUrls("123456789012/MyQueue1", "123456789012/MyQueue2")
                    .build());

        when(api.getQueueAttributes(
                GetQueueAttributesRequest.builder()
                    .queueUrl("123456789012/MyQueue1")
                    .attributeNames(QueueAttributeName.ALL)
                    .build()))
            .thenReturn(
                GetQueueAttributesResponse.builder()
                    .attributesWithStrings(Map.of("VisibilityTimeout", "30"))
                    .build());

        when(api.getQueueAttributes(
                GetQueueAttributesRequest.builder()
                    .queueUrl("123456789012/MyQueue2")
                    .attributeNames(QueueAttributeName.ALL)
                    .build()))
            .thenReturn(
                GetQueueAttributesResponse.builder()
                    .attributesWithStrings(Map.of("VisibilityTimeout", "60"))
                    .build());
      });
}
 
Example #23
Source File: SqsResource.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> start() {
    DockerClientFactory.instance().client();
    String queueUrl;
    try {
        services = new LocalStackContainer("0.11.1").withServices(Service.SQS);
        services.start();
        StaticCredentialsProvider staticCredentials = StaticCredentialsProvider
            .create(AwsBasicCredentials.create("accesskey", "secretKey"));

        client = SqsClient.builder()
            .endpointOverride(new URI(endpoint()))
            .credentialsProvider(staticCredentials)
            .httpClientBuilder(UrlConnectionHttpClient.builder())
            .region(Region.US_EAST_1).build();

        queueUrl = client.createQueue(q -> q.queueName(QUEUE_NAME)).queueUrl();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Could not start localstack server", e);
    }

    Map<String, String> properties = new HashMap<>();
    properties.put("quarkus.sqs.endpoint-override", endpoint());
    properties.put("quarkus.sqs.aws.region", "us-east-1");
    properties.put("quarkus.sqs.aws.credentials.type", "static");
    properties.put("quarkus.sqs.aws.credentials.static-provider.access-key-id", "accessKey");
    properties.put("quarkus.sqs.aws.credentials.static-provider.secret-access-key", "secretKey");
    properties.put("queue.url", queueUrl);

    return properties;
}
 
Example #24
Source File: SqsRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public RuntimeValue<AwsClientBuilder> createSyncBuilder(SqsConfig config, RuntimeValue<Builder> transport) {
    SqsClientBuilder builder = SqsClient.builder();

    if (transport != null) {
        builder.httpClientBuilder(transport.getValue());
    }
    return new RuntimeValue<>(builder);
}
 
Example #25
Source File: SqsRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public RuntimeValue<SqsClient> buildClient(RuntimeValue<? extends AwsClientBuilder> builder,
        BeanContainer beanContainer,
        ShutdownContext shutdown) {
    SqsClientProducer producer = beanContainer.instance(SqsClientProducer.class);
    producer.setSyncConfiguredBuilder((SqsClientBuilder) builder.getValue());
    shutdown.addShutdownTask(producer::destroy);
    return new RuntimeValue<>(producer.client());
}
 
Example #26
Source File: IntegrationTestBase.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the AWS account info for the integration tests and creates SNS and SQS clients for
 * tests to use.
 */
@BeforeClass
public static void setUp() throws FileNotFoundException, IOException {
    sns = SnsClient.builder()
            .credentialsProvider(StaticCredentialsProvider.create(getCredentials()))
            .region(Region.US_WEST_2)
            .build();

    sqs = SqsClient.builder()
            .credentialsProvider(StaticCredentialsProvider.create(getCredentials()))
            .region(Region.US_WEST_2)
            .build();
}
 
Example #27
Source File: SQSExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    String queueName = "queue" + System.currentTimeMillis();

    SqsClient sqsClient = SqsClient.builder()
            .region(Region.US_WEST_2)
            .build();

    // Create a queue
    String queueUrl= createQueue(sqsClient, queueName );
    listQueues(sqsClient);
    listQueuesFilter(sqsClient, queueUrl);
    List<Message> messages = receiveMessages(sqsClient, queueUrl);
    changeMessages(sqsClient, queueUrl, messages);
    deleteMessages(sqsClient, queueUrl,  messages) ;
}
 
Example #28
Source File: LongPolling.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        // Create an SqsClient object
        SqsClient sqsClient = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();

        setLongPoll(sqsClient) ;
    }
 
Example #29
Source File: LongPolling.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void setLongPoll( SqsClient sqsClient) {

        // Enable long polling when creating a queue
        HashMap<QueueAttributeName, String> attributes = new HashMap<QueueAttributeName, String>();
        attributes.put(QueueAttributeName.RECEIVE_MESSAGE_WAIT_TIME_SECONDS, "20");

        CreateQueueRequest createRequest = CreateQueueRequest.builder()
                .queueName(QueueName)
                .attributes(attributes)
                .build();

        try {
            sqsClient.createQueue(createRequest);

            GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
                .queueName(QueueName)
                .build();

            String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();

           // Enable long polling on an existing queue
           SetQueueAttributesRequest setAttrsRequest = SetQueueAttributesRequest.builder()
                .queueUrl(queueUrl)
                .attributes(attributes)
                .build();

           sqsClient.setQueueAttributes(setAttrsRequest);

            // Enable long polling on a message receipt
            ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder()
                .queueUrl(queueUrl)
                .waitTimeSeconds(20)
                .build();

            sqsClient.receiveMessage(receiveRequest);

        } catch (QueueNameExistsException e) {
            throw e;
        }
    }
 
Example #30
Source File: SqsUnboundedSource.java    From beam with Apache License 2.0 4 votes vote down vote up
public SqsClient getSqs() {
  return sqs.get();
}