software.amazon.awssdk.services.sqs.model.SendMessageRequest Java Examples

The following examples show how to use software.amazon.awssdk.services.sqs.model.SendMessageRequest. 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: MessageMD5ChecksumInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Throw an exception if the MD5 checksums returned in the SendMessageResponse do not match the
 * client-side calculation based on the original message in the SendMessageRequest.
 */
private static void sendMessageOperationMd5Check(SendMessageRequest sendMessageRequest,
                                                 SendMessageResponse sendMessageResult) {
    String messageBodySent = sendMessageRequest.messageBody();
    String bodyMd5Returned = sendMessageResult.md5OfMessageBody();
    String clientSideBodyMd5 = calculateMessageBodyMd5(messageBodySent);
    if (!clientSideBodyMd5.equals(bodyMd5Returned)) {
        throw SdkClientException.builder()
                                .message(String.format(MD5_MISMATCH_ERROR_MESSAGE, MESSAGE_BODY, clientSideBodyMd5,
                                                      bodyMd5Returned))
                                .build();
    }

    Map<String, MessageAttributeValue> messageAttrSent = sendMessageRequest.messageAttributes();
    if (messageAttrSent != null && !messageAttrSent.isEmpty()) {
        String clientSideAttrMd5 = calculateMessageAttributesMd5(messageAttrSent);
        String attrMd5Returned = sendMessageResult.md5OfMessageAttributes();
        if (!clientSideAttrMd5.equals(attrMd5Returned)) {
            throw SdkClientException.builder()
                                    .message(String.format(MD5_MISMATCH_ERROR_MESSAGE, MESSAGE_ATTRIBUTES,
                                                          clientSideAttrMd5, attrMd5Returned))
                                    .build();
        }
    }
}
 
Example #2
Source File: MessageAttributesIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void sendMessage_InvalidMd5_ThrowsException() {
    try (SqsClient tamperingClient = SqsClient.builder()
                                              .credentialsProvider(getCredentialsProvider())
                                              .overrideConfiguration(ClientOverrideConfiguration
                                                                             .builder()
                                                                             .addExecutionInterceptor(
                                                                                     new TamperingInterceptor())
                                                                             .build())
                                              .build()) {
        tamperingClient.sendMessage(
                SendMessageRequest.builder()
                                  .queueUrl(queueUrl)
                                  .messageBody(MESSAGE_BODY)
                                  .messageAttributes(createRandomAttributeValues(10))
                                  .build());
        fail("Expected SdkClientException");
    } catch (SdkClientException e) {
        assertThat(e.getMessage(), containsString("MD5 returned by SQS does not match"));
    }
}
 
Example #3
Source File: MessageAttributesIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Makes sure we don't modify the state of ByteBuffer backed attributes in anyway internally
 * before returning the result to the customer. See https://github.com/aws/aws-sdk-java/pull/459
 * for reference
 */
@Test
public void receiveMessage_WithBinaryAttributeValue_DoesNotChangeStateOfByteBuffer() {
    byte[] bytes = new byte[]{1, 1, 1, 0, 0, 0};
    String byteBufferAttrName = "byte-buffer-attr";
    Map<String, MessageAttributeValue> attrs = ImmutableMap.of(byteBufferAttrName,
                                                               MessageAttributeValue.builder().dataType("Binary").binaryValue(SdkBytes.fromByteArray(bytes)).build());

    sqsAsync.sendMessage(SendMessageRequest.builder().queueUrl(queueUrl).messageBody("test")
            .messageAttributes(attrs)
            .build());
    // Long poll to make sure we get the message back
    List<Message> messages = sqsAsync.receiveMessage(
            ReceiveMessageRequest.builder().queueUrl(queueUrl).messageAttributeNames("All").waitTimeSeconds(20).build()).join()
            .messages();

    ByteBuffer actualByteBuffer = messages.get(0).messageAttributes().get(byteBufferAttrName).binaryValue().asByteBuffer();
    assertEquals(bytes.length, actualByteBuffer.remaining());
}
 
Example #4
Source File: MessageMD5ChecksumInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) {
    SdkResponse response = context.response();
    SdkRequest originalRequest = context.request();
    if (response != null) {
        if (originalRequest instanceof SendMessageRequest) {
            SendMessageRequest sendMessageRequest = (SendMessageRequest) originalRequest;
            SendMessageResponse sendMessageResult = (SendMessageResponse) response;
            sendMessageOperationMd5Check(sendMessageRequest, sendMessageResult);

        } else if (originalRequest instanceof ReceiveMessageRequest) {
            ReceiveMessageResponse receiveMessageResult = (ReceiveMessageResponse) response;
            receiveMessageResultMd5Check(receiveMessageResult);

        } else if (originalRequest instanceof SendMessageBatchRequest) {
            SendMessageBatchRequest sendMessageBatchRequest = (SendMessageBatchRequest) originalRequest;
            SendMessageBatchResponse sendMessageBatchResult = (SendMessageBatchResponse) response;
            sendMessageBatchOperationMd5Check(sendMessageBatchRequest, sendMessageBatchResult);
        }
    }
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: AbstractSender.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
@Override public Call<Void> sendSpans(List<byte[]> list) {
  if (closeCalled) throw new IllegalStateException("closed");

  byte[] encodedSpans = BytesMessageEncoder.forEncoding(encoding()).encode(list);
  String body =
      encoding() == Encoding.JSON && isAscii(encodedSpans)
          ? new String(encodedSpans, StandardCharsets.UTF_8)
          : Base64.getEncoder().encodeToString(encodedSpans);

  return call(SendMessageRequest.builder().messageBody(body).queueUrl(queueUrl).build());
}
 
Example #11
Source File: MessageMD5ChecksumInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void sendMessageFailsInvalidAttributeChecksum() {
    SendMessageRequest request = SendMessageRequest.builder()
                                                   .messageBody(messageBody())
                                                   .messageAttributes(messageAttributes())
                                                   .build();

    SendMessageResponse response = SendMessageResponse.builder()
                                                      .md5OfMessageBody(messageBodyChecksum())
                                                      .md5OfMessageAttributes("bad")
                                                      .build();

    assertFailure(request, response);
}
 
Example #12
Source File: MessageMD5ChecksumInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void sendMessageFailsInvalidBodyChecksum() {
    SendMessageRequest request = SendMessageRequest.builder()
                                                   .messageBody(messageBody())
                                                   .messageAttributes(messageAttributes())
                                                   .build();

    SendMessageResponse response = SendMessageResponse.builder()
                                                      .md5OfMessageBody("bad")
                                                      .md5OfMessageAttributes(messageAttributesChecksum())
                                                      .build();

    assertFailure(request, response);
}
 
Example #13
Source File: MessageMD5ChecksumInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void sendMessagePassesValidChecksums() {
    SendMessageRequest request = SendMessageRequest.builder()
                                                   .messageBody(messageBody())
                                                   .messageAttributes(messageAttributes())
                                                   .build();

    SendMessageResponse response = SendMessageResponse.builder()
                                                      .md5OfMessageBody(messageBodyChecksum())
                                                      .md5OfMessageAttributes(messageAttributesChecksum())
                                                      .build();

    assertSuccess(request, response);
}
 
Example #14
Source File: SQSSender.java    From zipkin-aws with Apache License 2.0 4 votes vote down vote up
SQSCall(SendMessageRequest message) {
  this.message = message;
}
 
Example #15
Source File: SQSAsyncSender.java    From zipkin-aws with Apache License 2.0 4 votes vote down vote up
@Override protected Call<Void> call(SendMessageRequest request) {
  return new SQSCall(request);
}
 
Example #16
Source File: SQSAsyncSender.java    From zipkin-aws with Apache License 2.0 4 votes vote down vote up
SQSCall(SendMessageRequest message) {
  this.message = message;
}
 
Example #17
Source File: SQSSender.java    From zipkin-aws with Apache License 2.0 4 votes vote down vote up
@Override
protected Call<Void> call(SendMessageRequest request) {
  return new SQSCall(request);
}
 
Example #18
Source File: SendReceiveMessages.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

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

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

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

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

            SendMessageRequest sendMsgRequest = SendMessageRequest.builder()
                .queueUrl(queueUrl)
                .messageBody("hello world")
                .delaySeconds(5)
                .build();
            sqsClient.sendMessage(sendMsgRequest);

             // Send multiple messages to the queue
            SendMessageBatchRequest sendBatchRequest = SendMessageBatchRequest.builder()
                .queueUrl(queueUrl)
                .entries(
                        SendMessageBatchRequestEntry.builder()
                                .messageBody("Hello from message 1")
                                .id("msg_1")
                                .build()
                        ,
                        SendMessageBatchRequestEntry.builder()
                                .messageBody("Hello from message 2")
                                .delaySeconds(10)
                                .id("msg_2")
                                .build())
                .build();
             sqsClient.sendMessageBatch(sendBatchRequest);

            // Receive messages from the queue
            ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder()
                .queueUrl(queueUrl)
                .build();
            List<Message> messages = sqsClient.receiveMessage(receiveRequest).messages();

            // Print out the messages
             for (Message m : messages) {
                System.out.println("\n" +m.body());
            }
        } catch (QueueNameExistsException e) {
            throw e;
        }
    }
 
Example #19
Source File: SendMessageRequestCoder.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public void encode(SendMessageRequest value, OutputStream outStream) throws IOException {
  StringUtf8Coder.of().encode(value.queueUrl(), outStream);
  StringUtf8Coder.of().encode(value.messageBody(), outStream);
}
 
Example #20
Source File: SendMessageRequestCoder.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public SendMessageRequest decode(InputStream inStream) throws IOException {
  final String queueUrl = StringUtf8Coder.of().decode(inStream);
  final String message = StringUtf8Coder.of().decode(inStream);
  return SendMessageRequest.builder().queueUrl(queueUrl).messageBody(message).build();
}
 
Example #21
Source File: SqsIO.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public PDone expand(PCollection<SendMessageRequest> input) {
  input.apply(ParDo.of(new SqsWriteFn(this)));
  return PDone.in(input.getPipeline());
}
 
Example #22
Source File: SendMessageRequestCoderRegistrar.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public List<CoderProvider> getCoderProviders() {
  return ImmutableList.of(
      CoderProviders.forCoder(
          TypeDescriptor.of(SendMessageRequest.class), SendMessageRequestCoder.of()));
}
 
Example #23
Source File: MessageAttributesIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private SendMessageResponse sendTestMessage() {
    SendMessageResponse sendMessageResult = sqsAsync.sendMessage(SendMessageRequest.builder().queueUrl(queueUrl).messageBody(MESSAGE_BODY)
            .messageAttributes(createRandomAttributeValues(10)).build()).join();
    return sendMessageResult;
}
 
Example #24
Source File: AbstractSender.java    From zipkin-aws with Apache License 2.0 votes vote down vote up
abstract protected Call<Void> call(SendMessageRequest request);