Java Code Examples for com.amazonaws.services.sqs.model.Message#getBody()

The following examples show how to use com.amazonaws.services.sqs.model.Message#getBody() . 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: SqsConsumerWorkerCallable.java    From datacollector with Apache License 2.0 7 votes vote down vote up
private void setSqsAttributesOnRecord(Message message, Record record, String queueUrl, String queueNamePrefix) {
  final Record.Header header = record.getHeader();

  switch (sqsAttributesOption) {
    case ALL:
      header.setAttribute(SQS_QUEUE_URL_ATTRIBUTE, queueUrl);
      Optional.of(message.getMessageAttributes()).ifPresent(attrs -> {
        attrs.forEach((name, val) -> {
          final String stringValue = val.getStringValue();
          if (stringValue != null) {
            header.setAttribute(SQS_MESSAGE_ATTRIBUTE_PREFIX + name, stringValue);
          }
        });
      });
      final String body = message.getBody();
      if (body != null) {
        header.setAttribute(SQS_MESSAGE_BODY_ATTRIBUTE, body);
      }
      final String bodyMd5 = message.getMD5OfBody();
      if (bodyMd5 != null) {
        header.setAttribute(SQS_MESSAGE_BODY_MD5_ATTRIBUTE, bodyMd5);
      }
      final String attrsMd5 = message.getMD5OfMessageAttributes();
      if (attrsMd5 != null) {
        header.setAttribute(SQS_MESSAGE_ATTRIBUTE_MD5_ATTRIBUTE, attrsMd5);
      }
      // fall through
    case BASIC:
      header.setAttribute(SQS_MESSAGE_ID_ATTRIBUTE, message.getMessageId());
      header.setAttribute(SQS_QUEUE_NAME_PREFIX_ATTRIBUTE, queueNamePrefix);
      header.setAttribute(SQS_REGION_ATTRIBUTE, awsRegionLabel);
      break;
    case NONE:
      // empty block
      break;
  }
}
 
Example 2
Source File: CodeCommitMessageParser.java    From aws-codecommit-trigger-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public List<Event> parseMessage(final Message message) {
    List<Event> events = Collections.emptyList();

    try {
        log.info("Retrieved message-id: %s", message.getMessageId());
        log.debug("Parse Message:\n%s", message.toString());

        String messageBody = message.getBody();
        log.debug("Retrieved message-body: %s", messageBody);

        MessageBody body = gson.fromJson(messageBody, MessageBody.class);
        String recordsJson = body.getMessage();

        if (StringUtils.isBlank(recordsJson)) {
            log.warning("Message contains no text => Try to parse message-body instead");
            recordsJson = messageBody;
        }

        events = this.parseEvents(StringUtils.defaultString(recordsJson));
    } catch (final JsonSyntaxException e) {
        log.error("JSON syntax exception, cannot parse message: %s", e);
    }

    return events;
}
 
Example 3
Source File: HerdApiClientOperations.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Gets BusinessObjectDataKey from SQS message
 *
 * @param client the AWS SQS client
 * @param queueUrl the AWS SQS queue url
 *
 * @return BusinessObjectDataKey
 * @throws IOException if fails to retrieve BusinessObjectDataKey from SQS message
 * @throws ApiException if fails to make API call
 */
@Retryable(value = ApiException.class, backoff = @Backoff(delay = 2000, multiplier = 2))
BusinessObjectDataKey getBdataKeySqs(AmazonSQS client, String queueUrl) throws IOException, ApiException
{
    ReceiveMessageRequest receiveMessageRequest =
        new ReceiveMessageRequest().withMaxNumberOfMessages(MAX_NUM_MESSAGES).withQueueUrl(queueUrl).withWaitTimeSeconds(WAIT_TIME_SECS)
            .withVisibilityTimeout(VISIBILITY_TIMEOUT_SECS);

    LOGGER.info("Checking queue");
    ReceiveMessageResult receiveMessageResult = client.receiveMessage(receiveMessageRequest);
    if (receiveMessageResult != null && receiveMessageResult.getMessages() != null && receiveMessageResult.getMessages().size() > 0)
    {
        List<Message> sqsMessageList = receiveMessageResult.getMessages();

        LOGGER.info("Scanning {} messages for {} and {}", sqsMessageList.size(), SEARCH_KEYWORD_1, SEARCH_KEYWORD_2);
        // Get message type BUS_OBJCT_DATA_STTS_CHG
        for (Message sqsMessage : sqsMessageList)
        {
            String receivedMessageBody = sqsMessage.getBody();
            if (receivedMessageBody.contains(SEARCH_KEYWORD_1) && receivedMessageBody.contains(SEARCH_KEYWORD_2))
            {
                LOGGER.info("Received Message: {}", receivedMessageBody);
                return mapJsontoBdataKey(receivedMessageBody).getBusinessObjectDataKey();
            }
        }
    }
    throw new ApiException("No SQS message found in queue: " + queueUrl);
}
 
Example 4
Source File: MessageContent.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
public static MessageContent fromMessage(Message message) {
    return new MessageContent(message.getBody(), message.getMessageAttributes());
}
 
Example 5
Source File: SQSSpanProcessor.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
private void process(final List<Message> messages) {
  if (messages.size() == 0) return;

  final List<DeleteMessageBatchRequestEntry> toDelete = new ArrayList<>();
  int count = 0;
  for (Message message : messages) {
    final String deleteId = String.valueOf(count++);
    try {
      String stringBody = message.getBody();
      if (stringBody.isEmpty() || stringBody.equals("[]")) continue;
      // allow plain-text json, but permit base64 encoded thrift or json
      byte[] serialized =
          stringBody.charAt(0) == '[' ? stringBody.getBytes(UTF_8) : Base64.decode(stringBody);
      metrics.incrementMessages();
      metrics.incrementBytes(serialized.length);
      collector.acceptSpans(
          serialized,
          new Callback<Void>() {
            @Override
            public void onSuccess(Void value) {
              toDelete.add(
                  new DeleteMessageBatchRequestEntry(deleteId, message.getReceiptHandle()));
            }

            @Override
            public void onError(Throwable t) {
              logger.log(Level.WARNING, "collector accept failed", t);
              // for cases that are not recoverable just discard the message,
              // otherwise ignore so processing can be retried.
              if (t instanceof IllegalArgumentException) {
                toDelete.add(
                    new DeleteMessageBatchRequestEntry(deleteId, message.getReceiptHandle()));
              }
            }
          });
    } catch (RuntimeException | Error e) {
      logger.log(Level.WARNING, "message decoding failed", e);
      toDelete.add(new DeleteMessageBatchRequestEntry(deleteId, message.getReceiptHandle()));
    }
  }

  if (!toDelete.isEmpty()) {
    delete(toDelete);
  }
}
 
Example 6
Source File: rekognition-video-stored-video.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args)  throws Exception{


        sqs = AmazonSQSClientBuilder.defaultClient();
        rek = AmazonRekognitionClientBuilder.defaultClient();
        
        //Change active start function for the desired analysis. Also change the GetResults function later in this code.
        //=================================================
        StartLabels(bucket, video);
        //StartFaces(bucket,video);
        //StartFaceSearchCollection(bucket,video);
        //StartPersons(bucket,video);
        //StartCelebrities(bucket,video);
        //StartModerationLabels(bucket,video);
        //=================================================
        System.out.println("Waiting for job: " + startJobId);
        //Poll queue for messages
        List<Message> messages=null;
        int dotLine=0;
        boolean jobFound=false;

        //loop until the job status is published. Ignore other messages in queue.
        do{
            messages = sqs.receiveMessage(queueUrl).getMessages();
            if (dotLine++<20){
                System.out.print(".");
            }else{
                System.out.println();
                dotLine=0;
            }

            if (!messages.isEmpty()) {
                //Loop through messages received.
                for (Message message: messages) {
                    String notification = message.getBody();

                    // Get status and job id from notification.
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode jsonMessageTree = mapper.readTree(notification);
                    JsonNode messageBodyText = jsonMessageTree.get("Message");
                    ObjectMapper operationResultMapper = new ObjectMapper();
                    JsonNode jsonResultTree = operationResultMapper.readTree(messageBodyText.textValue());
                    JsonNode operationJobId = jsonResultTree.get("JobId");
                    JsonNode operationStatus = jsonResultTree.get("Status");
                    System.out.println("Job found was " + operationJobId);
                    // Found job. Get the results and display.
                    if(operationJobId.asText().equals(startJobId)){
                        jobFound=true;
                        System.out.println("Job id: " + operationJobId );
                        System.out.println("Status : " + operationStatus.toString());
                        if (operationStatus.asText().equals("SUCCEEDED")){
                            //Change to match the start function earlier in this code.
                            //============================================
                            GetResultsLabels();
                            //GetResultsFaces();
                            //GetResultsFaceSearchCollection();
                            //GetResultsPersons();
                            //GetResultsCelebrities();
                            //GetResultsModerationLabels();
                            //============================================
                        }
                        else{
                            System.out.println("Video analysis failed");
                        }

                        sqs.deleteMessage(queueUrl,message.getReceiptHandle());
                    }

                    else{
                        System.out.println("Job received was not job " +  startJobId);
                        //Delete unknown message. Consider moving message to dead letter queue
                        sqs.deleteMessage(queueUrl,message.getReceiptHandle());
                    }
                }
            }
        } while (!jobFound);


        System.out.println("Done!");
    }
 
Example 7
Source File: SqsBasicMessageQueue.java    From Cheddar with Apache License 2.0 4 votes vote down vote up
@Override
protected BasicMessage toMessage(final Message sqsMessage) {
    return new SimpleBasicMessage(sqsMessage.getBody(), sqsMessage.getMessageId(), sqsMessage.getReceiptHandle());
}
 
Example 8
Source File: SQSTextMessage.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Convert received SQSMessage into TextMessage.
 */
public SQSTextMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException{
    super(acknowledger, queueUrl, sqsMessage);
    this.text = sqsMessage.getBody();
}
 
Example 9
Source File: SQSObjectMessage.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Convert received SQSMessage into ObjectMessage
 */
public SQSObjectMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException {
    super(acknowledger, queueUrl, sqsMessage);
    body = sqsMessage.getBody();
}