List of usage examples for com.amazonaws.services.sqs.model Message getBody
public String getBody()
The message's contents (not URL-encoded).
From source file:com.amazon.sqs.javamessaging.AmazonSQSExtendedClient.java
License:Open Source License
/** * <p>/*w w w. java 2s . c om*/ * Retrieves one or more messages, with a maximum limit of 10 messages, from * the specified queue. Downloads the message payloads from Amazon S3 when * necessary. Long poll support is enabled by using the * <code>WaitTimeSeconds</code> parameter. For more information, see <a * href= * "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html" * > Amazon SQS Long Poll </a> in the <i>Amazon SQS Developer Guide</i> . * </p> * <p> * Short poll is the default behavior where a weighted random set of * machines is sampled on a <code>ReceiveMessage</code> call. This means * only the messages on the sampled machines are returned. If the number of * messages in the queue is small (less than 1000), it is likely you will * get fewer messages than you requested per <code>ReceiveMessage</code> * call. If the number of messages in the queue is extremely small, you * might not receive any messages in a particular * <code>ReceiveMessage</code> response; in which case you should repeat the * request. * </p> * <p> * For each message returned, the response includes the following: * </p> * * <ul> * <li> * <p> * Message body * </p> * </li> * <li> * <p> * MD5 digest of the message body. For information about MD5, go to <a * href="http://www.faqs.org/rfcs/rfc1321.html"> * http://www.faqs.org/rfcs/rfc1321.html </a> . * </p> * </li> * <li> * <p> * Message ID you received when you sent the message to the queue. * </p> * </li> * <li> * <p> * Receipt handle. * </p> * </li> * <li> * <p> * Message attributes. * </p> * </li> * <li> * <p> * MD5 digest of the message attributes. * </p> * </li> * * </ul> * <p> * The receipt handle is the identifier you must provide when deleting the * message. For more information, see <a href= * "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ImportantIdentifiers.html" * > Queue and Message Identifiers </a> in the <i>Amazon SQS Developer * Guide</i> . * </p> * <p> * You can provide the <code>VisibilityTimeout</code> parameter in your * request, which will be applied to the messages that Amazon SQS returns in * the response. If you do not include the parameter, the overall visibility * timeout for the queue is used for the returned messages. For more * information, see <a href= * "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html" * > Visibility Timeout </a> in the <i>Amazon SQS Developer Guide</i> . * </p> * <p> * <b>NOTE:</b> Going forward, new attributes might be added. If you are * writing code that calls this action, we recommend that you structure your * code so that it can handle new attributes gracefully. * </p> * * @param receiveMessageRequest * Container for the necessary parameters to execute the * ReceiveMessage service method on AmazonSQS. * * @return The response from the ReceiveMessage service method, as returned * by AmazonSQS. * * @throws OverLimitException * * @throws AmazonClientException * If any internal errors are encountered inside the client * while attempting to make the request or handle the response. * For example if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonSQS indicating * either a problem with the data in the request, or a server * side issue. */ public ReceiveMessageResult receiveMessage(ReceiveMessageRequest receiveMessageRequest) { if (receiveMessageRequest == null) { String errorMessage = "receiveMessageRequest cannot be null."; LOG.error(errorMessage); throw new AmazonClientException(errorMessage); } receiveMessageRequest.getRequestClientOptions() .appendUserAgent(SQSExtendedClientConstants.USER_AGENT_HEADER); if (!clientConfiguration.isLargePayloadSupportEnabled()) { return super.receiveMessage(receiveMessageRequest); } receiveMessageRequest.getMessageAttributeNames().add(SQSExtendedClientConstants.RESERVED_ATTRIBUTE_NAME); ReceiveMessageResult receiveMessageResult = super.receiveMessage(receiveMessageRequest); List<Message> messages = receiveMessageResult.getMessages(); for (Message message : messages) { // for each received message check if they are stored in S3. MessageAttributeValue largePayloadAttributeValue = message.getMessageAttributes() .get(SQSExtendedClientConstants.RESERVED_ATTRIBUTE_NAME); if (largePayloadAttributeValue != null) { String messageBody = message.getBody(); // read the S3 pointer from the message body JSON string. MessageS3Pointer s3Pointer = readMessageS3PointerFromJSON(messageBody); String s3MsgBucketName = s3Pointer.getS3BucketName(); String s3MsgKey = s3Pointer.getS3Key(); String origMsgBody = getTextFromS3(s3MsgBucketName, s3MsgKey); LOG.info("S3 object read, Bucket name: " + s3MsgBucketName + ", Object key: " + s3MsgKey + "."); message.setBody(origMsgBody); // remove the additional attribute before returning the message // to user. message.getMessageAttributes().remove(SQSExtendedClientConstants.RESERVED_ATTRIBUTE_NAME); // Embed s3 object pointer in the receipt handle. String modifiedReceiptHandle = embedS3PointerInReceiptHandle(message.getReceiptHandle(), s3MsgBucketName, s3MsgKey); message.setReceiptHandle(modifiedReceiptHandle); } } return receiveMessageResult; }
From source file:com.amazon.sqs.javamessaging.message.SQSBytesMessage.java
License:Open Source License
/** * Convert received SQSMessage into BytesMessage. */// w ww . j a v a2s.c o m public SQSBytesMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException { super(acknowledger, queueUrl, sqsMessage); try { /** Bytes is set by the reset() */ dataOut.write(Base64.decode(sqsMessage.getBody())); /** Makes it read-only */ reset(); } catch (IOException e) { LOG.error("IOException: Message cannot be written", e); throw convertExceptionToJMSException(e); } catch (Exception e) { LOG.error("Unexpected exception: ", e); throw convertExceptionToJMSException(e); } }
From source file:com.amazon.sqs.javamessaging.message.SQSObjectMessage.java
License:Open Source License
/** * Convert received SQSMessage into ObjectMessage *///from w w w. j av a2 s . c o m public SQSObjectMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException { super(acknowledger, queueUrl, sqsMessage); body = sqsMessage.getBody(); }
From source file:com.amazon.sqs.javamessaging.message.SQSTextMessage.java
License:Open Source License
/** * Convert received SQSMessage into TextMessage. *//*from w w w .j a va2s . co m*/ public SQSTextMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException { super(acknowledger, queueUrl, sqsMessage); this.text = sqsMessage.getBody(); }
From source file:com.amediamanager.scheduled.ElasticTranscoderTasks.java
License:Apache License
protected void handleMessage(final Message message) { try {/* w w w . ja v a2 s.c om*/ LOG.info("Handling message received from checkStatus"); ObjectNode snsMessage = (ObjectNode) mapper.readTree(message.getBody()); ObjectNode notification = (ObjectNode) mapper.readTree(snsMessage.get("Message").asText()); String state = notification.get("state").asText(); String jobId = notification.get("jobId").asText(); String pipelineId = notification.get("pipelineId").asText(); Video video = videoService.findByTranscodeJobId(jobId); if (video == null) { LOG.warn("Unable to process result for job {} because it does not exist.", jobId); Instant msgTime = Instant.parse(snsMessage.get("Timestamp").asText()); if (Minutes.minutesBetween(msgTime, new Instant()).getMinutes() > 20) { LOG.error("Job {} has not been found for over 20 minutes, deleting message from queue", jobId); deleteMessage(message); } // Leave it on the queue for now. return; } if ("ERROR".equals(state)) { LOG.warn("Job {} for pipeline {} failed to complete. Body: \n{}", jobId, pipelineId, notification.get("messageDetails").asText()); video.setThumbnailKey(videoService.getDefaultVideoPosterKey()); videoService.save(video); } else { // Construct our url prefix: https://bucketname.s3.amazonaws.com/output/key/ String prefix = notification.get("outputKeyPrefix").asText(); if (!prefix.endsWith("/")) { prefix += "/"; } ObjectNode output = ((ObjectNode) ((ArrayNode) notification.get("outputs")).get(0)); String previewFilename = prefix + output.get("key").asText(); String thumbnailFilename = prefix + output.get("thumbnailPattern").asText().replaceAll("\\{count\\}", "00002") + ".png"; video.setPreviewKey(previewFilename); video.setThumbnailKey(thumbnailFilename); videoService.save(video); } deleteMessage(message); } catch (JsonProcessingException e) { LOG.error("JSON exception handling notification: {}", message.getBody(), e); } catch (IOException e) { LOG.error("IOException handling notification: {}", message.getBody(), e); } }
From source file:com.athena.sqs.MessageReceiver.java
License:Apache License
public void doReceive(String queueName) throws Exception { String queueUrl = messageContext.getQueue(queueName); logger.debug("Receiving a message to [" + queueName + "][" + queueUrl); // Receive messages ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl); while (true) { List<com.amazonaws.services.sqs.model.Message> messages = client .receiveMessage(receiveMessageRequest.withMaxNumberOfMessages(10)).getMessages(); logger.debug(new Date() + " : message count : " + messages.size()); if (messages.size() > 0) { for (com.amazonaws.services.sqs.model.Message message : messages) { // logger.debug(" Message"); // logger.debug(" MessageId: " + message.getMessageId()); // logger.debug(" ReceiptHandle: " + message.getReceiptHandle()); // logger.debug(" MD5OfBody: " + message.getMD5OfBody()); // logger.debug(" Body: " + message.getBody()); // for (Entry<String, String> entry : message.getAttributes().entrySet()) { // logger.debug(" Attribute"); // logger.debug(" Name: " + entry.getKey()); // logger.debug(" Value: " + entry.getValue()); // } logger.debug(" Message"); String body = message.getBody(); aggregator.aggregate(body); client.deleteMessage(new DeleteMessageRequest(queueUrl, message.getReceiptHandle())); }// ww w. j a v a 2 s .c o m } else { logger.debug("Nothing found, trying again in 3 seconds"); Thread.sleep(pollingFrequency); } } }
From source file:com.blacklocus.qs.worker.aws.AmazonSQSTaskService.java
License:Apache License
@Override public QSTaskModel getAvailableTask() { QSTaskModel task = null;// w w w . ja v a 2 s . c om while (task == null) { ReceiveMessageResult result = sqs .receiveMessage(new ReceiveMessageRequest(queueUrl).withMaxNumberOfMessages(1)); assert result.getMessages().size() <= 1; if (result.getMessages().size() == 1) { Message message = result.getMessages().get(0); try { task = objectMapper.readValue(message.getBody(), QSTaskModel.class); receiptHandles.put(task, message.getReceiptHandle()); } catch (IOException e) { LOG.error("Failed to parse message from " + queueUrl + "\n\t" + message); } } else { sleep(); } } return task; }
From source file:com.boundary.aws.sqs.Sample.java
License:Open Source License
public static void main(String[] args) throws Exception { String queueName = "boundary-sqs-demo-queue"; /*//w w w.java 2s . c o m * The ProfileCredentialsProvider will return your [default] credential * profile by reading from the credentials file located at * (HOME/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. ", e); } AmazonSQS sqs = new AmazonSQSClient(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); sqs.setRegion(usWest2); try { // Create a queue System.out.printf("Creating queue: %s.\n", queueName); CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); int messageCount = 100; // Send a messages for (int count = 1; count <= messageCount; count++) { System.out.printf("Sending message %3d to %s.\n", count, queueName); sqs.sendMessage(new SendMessageRequest(myQueueUrl, new Date() + ": This is my message text.")); } for (int count = 1; count <= messageCount; count++) { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message msg : messages) { System.out.printf("Received message: %s queue: %s body: %s\n", msg.getMessageId(), queueName, msg.getBody()); System.out.printf("Deleting message: %s queue: %s\n", msg.getMessageId(), queueName); String messageRecieptHandle = msg.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle)); } } System.out.printf("Deleting queue: %s\n", queueName); sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SQS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with SQS, such as not " + "being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } sqs.shutdown(); }
From source file:com.clicktravel.infrastructure.messaging.aws.sqs.SqsBasicMessageQueue.java
License:Apache License
@Override protected BasicMessage toMessage(final Message sqsMessage) { return new SimpleBasicMessage(sqsMessage.getBody(), sqsMessage.getReceiptHandle()); }
From source file:com.clicktravel.infrastructure.messaging.aws.sqs.SqsTypedMessageQueue.java
License:Apache License
@Override protected TypedMessage toMessage(final com.amazonaws.services.sqs.model.Message sqsMessage) { final String receiptHandle = sqsMessage.getReceiptHandle(); try {/*from w w w . j a va 2 s.c om*/ final ObjectMapper mapper = new ObjectMapper(); final JsonNode jsonNode = mapper.readTree(sqsMessage.getBody()); final String messageType = jsonNode.get("Subject").textValue(); final String messagePayload = jsonNode.get("Message").textValue(); return new SimpleMessage(messageType, messagePayload, receiptHandle); } catch (final Exception e) { return new InvalidTypedMessage(receiptHandle, new MessageParseException("Could not parse message from SQS message: " + sqsMessage.getBody())); } }