List of usage examples for com.amazonaws.services.sqs.model Message getReceiptHandle
public String getReceiptHandle()
An identifier associated with the act of receiving the message.
From source file:TweetSQS.java
License:Open Source License
public static void main(String[] args) throws Exception { /*//from w ww .j a va 2 s .c o m * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (). */ AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( TweetSQS.class.getResourceAsStream("AwsCredentials.properties")); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (/Users/aohong/.aws/credentials), and is in valid format.", e); } AmazonSQS sqs = new AmazonSQSClient(credentials); Region usEast1 = Region.getRegion(Regions.US_EAST_1); sqs.setRegion(usEast1); System.out.println("==========================================="); System.out.println("Getting Started with Amazon SQS"); System.out.println("===========================================\n"); try { // Create a queue System.out.println("Creating a new SQS queue called MyQueue.\n"); CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue"); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); // List queues System.out.println("Listing all queues in your account.\n"); for (String queueUrl : sqs.listQueues().getQueueUrls()) { System.out.println(" QueueUrl: " + queueUrl); } System.out.println(); // Send a message System.out.println("Sending a message to MyQueue.\n"); sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my first message text.")); // Receive messages System.out.println("Receiving messages from MyQueue.\n"); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { System.out.println(" Message"); System.out.println(" MessageId: " + message.getMessageId()); System.out.println(" ReceiptHandle: " + message.getReceiptHandle()); System.out.println(" MD5OfBody: " + message.getMD5OfBody()); System.out.println(" Body: " + message.getBody()); for (Entry<String, String> entry : message.getAttributes().entrySet()) { System.out.println(" Attribute"); System.out.println(" Name: " + entry.getKey()); System.out.println(" Value: " + entry.getValue()); } } System.out.println(); // Delete a message System.out.println("Deleting a message.\n"); String messageRecieptHandle = messages.get(0).getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle)); // Delete a queue System.out.println("Deleting the test queue.\n"); 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()); } }
From source file:sqsAlertCache.java
License:Open Source License
public static void main(String[] args) throws Exception { // get credentials String user = "jreilly"; AWSCredentials credentials = whgHelper.getCred(user); // use credentials to set access to SQS AmazonSQS sqs = whgHelper.setQueueAccess(credentials); // define queue that messages will be retrieved from String thisQueue = "alertCache"; String nextQueue = "alertStream"; while (1 > 0) { // pull list of current messages (up to 10) in the queue List<Message> messages = whgHelper.getMessagesFromQueue(thisQueue, sqs); System.out.println("Count of messages in " + thisQueue + ": " + messages.size()); try {/*from w ww . j av a 2 s. c om*/ for (Message message : messages) { whgHelper.printMessage(message); for (Entry<String, String> entry : message.getAttributes().entrySet()) { whgHelper.printMessageEntry(entry); } String configEndpoint = "alertsbrdregrol-001.tiluxk.0001.use1.cache.amazonaws.com"; Integer clusterPort = 6379; MemcachedClient client = new MemcachedClient( new InetSocketAddress(configEndpoint, clusterPort)); // The client will connect to the other cache nodes automatically // Store a data item for an hour. The client will decide which cache client.set(message.getMessageId(), 360000, message.getBody()); // then send message to cache queue System.out.println("Sending messages to next queue."); sqs.sendMessage(new SendMessageRequest(nextQueue, message.getBody())); // delete message after sending to persist queue System.out.println("Deleting message from this queue.\n"); String messageRecieptHandle = message.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(thisQueue, messageRecieptHandle)); } Thread.sleep(20000); // do nothing for 1000 miliseconds (1 second) } catch (AmazonServiceException ase) { whgHelper.errorMessagesAse(ase); } catch (AmazonClientException ace) { whgHelper.errorMessagesAce(ace); } } }
From source file:sqsAlertPersist.java
License:Open Source License
public static void main(String[] args) throws Exception { // get credentials String user = "jreilly"; AWSCredentials credentials = whgHelper.getCred(user); // use credentials to set access to SQS AmazonSQS sqs = whgHelper.setQueueAccess(credentials); // define queue that messages will be retrieved from String thisQueue = "alertPersist"; String nextQueue = "alertCache"; // set access to database with credentials dynamoDB = new AmazonDynamoDBClient(credentials); Region usEast1 = Region.getRegion(Regions.US_EAST_1); dynamoDB.setRegion(usEast1);/*from w w w.j a v a 2s . c o m*/ // check for table, create one if missing String tableName = "alerts"; whgHelper.setTable(dynamoDB, tableName); while (1 > 0) { // pull list of current messages (up to 10) in the queue List<Message> messages = whgHelper.getMessagesFromQueue(thisQueue, sqs); System.out.println("Count of messages in " + thisQueue + ": " + messages.size()); try { for (Message message : messages) { whgHelper.printMessage(message); for (Entry<String, String> entry : message.getAttributes().entrySet()) { whgHelper.printMessageEntry(entry); } // Add an item to DynamoDB table Map<String, AttributeValue> item = whgHelper.newAlert(message.getBody()); PutItemRequest putItemRequest = new PutItemRequest(tableName, item); PutItemResult putItemResult = dynamoDB.putItem(putItemRequest); System.out.println(); System.out.println("Result: " + putItemResult); // then send message to cache queue System.out.println("Sending messages to next queue."); sqs.sendMessage(new SendMessageRequest(nextQueue, message.getBody())); // delete message after sending to persist queue System.out.println("Deleting message from this queue.\n"); String messageRecieptHandle = message.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(thisQueue, messageRecieptHandle)); } Thread.sleep(20000); // do nothing for 2000 miliseconds (2 second) } catch (AmazonServiceException ase) { whgHelper.errorMessagesAse(ase); } catch (AmazonClientException ace) { whgHelper.errorMessagesAce(ace); } } }
From source file:aws.example.sqs.SendReceiveMessages.java
License:Open Source License
public static void main(String[] args) { final AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient(); try {/*ww w . ja v a2 s .c o m*/ CreateQueueResult create_result = sqs.createQueue(QUEUE_NAME); } catch (AmazonSQSException e) { if (!e.getErrorCode().equals("QueueAlreadyExists")) { throw e; } } String queueUrl = sqs.getQueueUrl(QUEUE_NAME).getQueueUrl(); SendMessageRequest send_msg_request = new SendMessageRequest().withQueueUrl(queueUrl) .withMessageBody("hello world").withDelaySeconds(5); sqs.sendMessage(send_msg_request); // Send multiple messages to the queue SendMessageBatchRequest send_batch_request = new SendMessageBatchRequest().withQueueUrl(queueUrl) .withEntries(new SendMessageBatchRequestEntry("msg_1", "Hello from message 1"), new SendMessageBatchRequestEntry("msg_2", "Hello from message 2").withDelaySeconds(10)); sqs.sendMessageBatch(send_batch_request); // receive messages from the queue List<Message> messages = sqs.receiveMessage(queueUrl).getMessages(); // delete messages from the queue for (Message m : messages) { sqs.deleteMessage(queueUrl, m.getReceiptHandle()); } }
From source file:aws.sample.SimpleQueueServiceSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*/*from ww w . ja v a 2 s . co m*/ * Important: Be sure to fill in your AWS access credentials in the AwsCredentials.properties file before you try to run this sample. http://aws.amazon.com/security-credentials */ AmazonSQS sqs = new AmazonSQSClient(new PropertiesCredentials( SimpleQueueServiceSample.class.getResourceAsStream("/AwsCredentials.properties"))); System.out.println("==========================================="); System.out.println("Getting Started with Amazon SQS"); System.out.println("===========================================\n"); try { // Create a queue System.out.println("Creating a new SQS queue called MyQueue.\n"); CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue"); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); // List queues System.out.println("Listing all queues in your account.\n"); for (String queueUrl : sqs.listQueues().getQueueUrls()) { System.out.println(" QueueUrl: " + queueUrl); } System.out.println(); // Send a message System.out.println("Sending a message to MyQueue.\n"); sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text.")); // Receive messages System.out.println("Receiving messages from MyQueue.\n"); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { System.out.println(" Message"); System.out.println(" MessageId: " + message.getMessageId()); System.out.println(" ReceiptHandle: " + message.getReceiptHandle()); System.out.println(" MD5OfBody: " + message.getMD5OfBody()); System.out.println(" Body: " + message.getBody()); for (Entry<String, String> entry : message.getAttributes().entrySet()) { System.out.println(" Attribute"); System.out.println(" Name: " + entry.getKey()); System.out.println(" Value: " + entry.getValue()); } } System.out.println(); // Delete a message System.out.println("Deleting a message.\n"); String messageRecieptHandle = messages.get(0).getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle)); // Delete a queue System.out.println("Deleting the test queue.\n"); // 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()); } }
From source file:awslabs.lab31.Lab31.java
License:Open Source License
private static void PrintAndRemoveMessagesInResponse(AmazonSQSClient sqsClient, List<Message> messages, String queueUrl) {/* w w w. ja v a 2 s. c o m*/ for (Message message : messages) { System.out.println("\nQueue Message:"); System.out.println("\tMessageId : " + message.getMessageId()); System.out.println("\tMD5OfBody : " + message.getMD5OfBody()); System.out.println("\tBody : " + message.getBody()); if (message.getAttributes().size() > 0) { System.out.println("\tMessage Attributes"); for (Entry<String, String> entry : message.getAttributes().entrySet()) { System.out.println("\t\t" + entry.getKey() + " : " + entry.getValue()); } } System.out.println("\nDeleting message."); labCode.removeMessage(sqsClient, queueUrl, message.getReceiptHandle()); System.out.println("Message deleted."); } }
From source file:Cloud.Tweets.SimpleQueueServiceSample.java
License:Open Source License
public void getTweets(AmazonSQS abc) { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = abc.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { System.out.println(" Message"); System.out.println(" MessageId: " + message.getMessageId()); System.out.println(" ReceiptHandle: " + message.getReceiptHandle()); System.out.println(" MD5OfBody: " + message.getMD5OfBody()); System.out.println(" Body: " + message.getBody()); for (Entry<String, String> entry : message.getAttributes().entrySet()) { System.out.println(" Attribute"); System.out.println(" Name: " + entry.getKey()); System.out.println(" Value: " + entry.getValue()); }/*from w ww. j a va 2s . c o m*/ String messageRecieptHandle = messages.get(0).getBody(); System.out.println(messageRecieptHandle); getSentiment(messageRecieptHandle); } }
From source file:cloudworker.RemoteWorker.java
License:Apache License
public static void main(String[] args) throws Exception { //Command interpreter CommandLineInterface cmd = new CommandLineInterface(args); final int poolSize = Integer.parseInt(cmd.getOptionValue("s")); long idle_time = Long.parseLong(cmd.getOptionValue("i")); //idle time = 60 sec init();/*from w w w . j a va 2s . c o m*/ System.out.println("Initialized one remote worker.\n"); //Create thread pool ExecutorService threadPool = Executors.newFixedThreadPool(poolSize); BlockingExecutor blockingPool = new BlockingExecutor(threadPool, poolSize); //Get queue url GetQueueUrlResult urlResult = sqs.getQueueUrl("JobQueue"); String jobQueueUrl = urlResult.getQueueUrl(); // Receive messages //System.out.println("Receiving messages from JobQueue.\n"); //...Check idle state boolean terminate = false; boolean startClock = true; long start_time = 0, end_time; JSONParser parser = new JSONParser(); Runtime runtime = Runtime.getRuntime(); String task_id = null; boolean runAnimoto = false; while (!terminate || idle_time == 0) { while (getQueueSize(sqs, jobQueueUrl) > 0) { //Batch retrieving messages ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest().withQueueUrl(jobQueueUrl) .withMaxNumberOfMessages(10); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { //System.out.println(" Message"); // System.out.println(" MessageId: " + message.getMessageId()); // System.out.println(" ReceiptHandle: " + message.getReceiptHandle()); // System.out.println(" MD5OfBody: " + message.getMD5OfBody()); //System.out.println(" Body: " + message.getBody()); //Get task String messageBody = message.getBody(); JSONObject json = (JSONObject) parser.parse(messageBody); task_id = json.get("task_id").toString(); String task = json.get("task").toString(); try { //Check duplicate task dynamoDB.addTask(task_id, task); //Execute task, will be blocked if no more thread is currently available blockingPool.submitTask(new Animoto(task_id, task, sqs)); // Delete the message String messageRecieptHandle = message.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(jobQueueUrl, messageRecieptHandle)); } catch (ConditionalCheckFailedException ccf) { //DO something... } } startClock = true; } //Start clock to measure idle time if (startClock) { startClock = false; start_time = System.currentTimeMillis(); } else { end_time = System.currentTimeMillis(); long elapsed_time = (end_time - start_time) / 1000; if (elapsed_time > idle_time) { terminate = true; } } } //System.out.println(); threadPool.shutdown(); // Wait until all threads are finished while (!threadPool.isTerminated()) { } //Terminate running instance cleanUpInstance(); }
From source file:com.amazon.sqs.javamessaging.AcknowledgerCommon.java
License:Open Source License
public void populateMessage(int populateMessageSize) throws JMSException { String queueUrl = baseQueueUrl + 0; for (int i = 0; i < populateMessageSize; i++) { // Change queueUrl depending on how many messages there are. if (i == 11) { queueUrl = baseQueueUrl + 1; } else if (i == 22) { queueUrl = baseQueueUrl + 2; } else if (i == 33) { queueUrl = baseQueueUrl + 3; } else if (i == 44) { queueUrl = baseQueueUrl + 4; }/*www .j a va2 s.com*/ Message sqsMessage = mock(Message.class); when(sqsMessage.getReceiptHandle()).thenReturn("ReceiptHandle" + i); when(sqsMessage.getMessageId()).thenReturn("MessageId" + i); // Add mock Attributes Map<String, String> mockAttributes = new HashMap<String, String>(); mockAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "2"); when(sqsMessage.getAttributes()).thenReturn(mockAttributes); SQSMessage message = (SQSMessage) new SQSTextMessage(acknowledger, queueUrl, sqsMessage); populatedMessages.add(message); acknowledger.notifyMessageReceived(message); } Assert.assertEquals(populateMessageSize, acknowledger.getUnAckMessages().size()); }
From source file:com.amazon.sqs.javamessaging.AmazonSQSExtendedClient.java
License:Open Source License
/** * <p>//from www . j a va 2s . c o m * 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; }