Example usage for com.amazonaws.services.sqs.model Message getReceiptHandle

List of usage examples for com.amazonaws.services.sqs.model Message getReceiptHandle

Introduction

In this page you can find the example usage for com.amazonaws.services.sqs.model Message getReceiptHandle.

Prototype


public String getReceiptHandle() 

Source Link

Document

An identifier associated with the act of receiving the message.

Usage

From source file:org.mule.modules.sqs.SQSConnector.java

License:Open Source License

/**
 * Attempts to receive a message from the queue. Every attribute of the incoming
 * message will be added as an inbound property. Also the following properties
 * will also be added:/*from  ww w  .  j a va2  s . c om*/
 * <p/>
 * sqs.message.id = containing the message identification
 * sqs.message.receipt.handle = containing the message identification
 * <p/>
 * {@sample.xml ../../../doc/mule-module-sqs.xml.sample sqs:receive-messages}
 *
 * @param callback          Callback to call when a new message is available.
 * @param visibilityTimeout the duration (in seconds) the retrieved message is hidden from
 *                          subsequent calls to retrieve.
 * @param preserveMessages    Flag that indicates if you want to preserve the messages
 *                            in the queue. False by default, so the messages are
 *                            going to be deleted.
 * @param pollPeriod        time in milliseconds to wait between polls (when no messages were retrieved). 
 *                          Default period is 1000 ms.
 * @param numberOfMessages  the number of messages to be retrieved on each call (10 messages max). 
 *                      By default, 1 message will be retrieved.                                 
 * @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.
 */
@Source
@InvalidateConnectionOn(exception = AmazonClientException.class)
public void receiveMessages(SourceCallback callback, @Optional @Default("30") Integer visibilityTimeout,
        @Optional @Default("false") Boolean preserveMessages, @Optional @Default("1000") Long pollPeriod,
        @Optional @Default("1") Integer numberOfMessages) throws AmazonServiceException {

    List<Message> messages;
    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
    receiveMessageRequest.setQueueUrl(getQueueUrl());

    if (visibilityTimeout != null) {
        receiveMessageRequest.setVisibilityTimeout(visibilityTimeout);
    }
    receiveMessageRequest.setMaxNumberOfMessages(numberOfMessages);

    while (!Thread.interrupted()) {
        messages = msgQueue.receiveMessage(receiveMessageRequest).getMessages();
        try {
            if (messages.size() == 0) {
                Thread.sleep(pollPeriod);
                continue;
            }
            for (Message msg : messages) {
                callback.process(msg.getBody(), createProperties(msg));
                if (!preserveMessages) {
                    msgQueue.deleteMessage(new DeleteMessageRequest(getQueueUrl(), msg.getReceiptHandle()));
                }
            }
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        } catch (Exception e) {
            throw new AmazonClientException("Error while processing message.", e);
        }
    }
}

From source file:org.mule.modules.sqs.SQSConnector.java

License:Open Source License

/**
 * @param msg Message to extract properties from.
 * @return map with properties//from w ww  .  ja  v  a  2  s  .  c  om
 */
public Map<String, Object> createProperties(Message msg) {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.putAll(msg.getAttributes());
    properties.put("sqs.message.id", msg.getMessageId());
    properties.put("sqs.message.receipt.handle", msg.getReceiptHandle());
    return properties;
}

From source file:org.nuxeo.aws.elastictranscoder.notification.SqsQueueNotificationWorker.java

License:Open Source License

@Override
public void run() {
    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest().withQueueUrl(queueUrl)
            .withMaxNumberOfMessages(MAX_NUMBER_OF_MESSAGES).withVisibilityTimeout(VISIBILITY_TIMEOUT)
            .withWaitTimeSeconds(WAIT_TIME_SECONDS);

    while (!shutdown) {
        // Long pole the SQS queue. This will return as soon as a message
        // is received, or when WAIT_TIME_SECONDS has elapsed.
        List<Message> messages = amazonSqs.receiveMessage(receiveMessageRequest).getMessages();
        if (messages == null) {
            // If there were no messages during this poll period, SQS
            // will return this list as null. Continue polling.
            continue;
        }//from w ww.jav a 2s. c om

        synchronized (handlers) {
            for (Message message : messages) {
                try {
                    // Parse notification and call handlers.
                    JobStatusNotification notification = parseNotification(message);
                    for (JobStatusNotificationHandler handler : handlers) {
                        handler.handle(notification);
                    }
                } catch (IOException e) {
                    System.out.println("Failed to convert notification: " + e.getMessage());
                }

                // Delete the message from the queue.
                amazonSqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(queueUrl)
                        .withReceiptHandle(message.getReceiptHandle()));
            }
        }
    }
}

From source file:org.springframework.integration.aws.sqs.core.AmazonSQSOperationsImpl.java

License:Apache License

/**
 * Extracts the payload from the SQS message and builds the AmazonSQSMessage
 * after transforming the message payload
 * @param response//  www. ja va 2  s . c o  m
 * @param message
 */
private void buildSQSMessage(Collection<AmazonSQSMessage> response, Message message) {
    AmazonSQSMessage sqsMessage = messageTransformer.deserialize(message.getBody());
    response.add(sqsMessage);
    sqsMessage.setMD5OfBody(message.getMD5OfBody());
    sqsMessage.setMessageId(message.getMessageId());
    sqsMessage.setReceiptHandle(message.getReceiptHandle());
}

From source file:org.wso2.carbon.inbound.amazonsqs.AmazonSQSPollingConsumer.java

License:Open Source License

/**
 * Create connection with broker and retrieve the messages. Then inject
 * according to the registered handler./* w  w  w .ja v  a 2s . c o m*/
 */
public Message poll() {
    if (logger.isDebugEnabled()) {
        logger.debug("Polling AmazonSQS messages for " + name);
    }
    try {
        if (!isConnected) {
            sqsClient = new AmazonSQSClient(this.credentials);
            isConnected = true;
        }
        if (sqsClient == null) {
            logger.error("AmazonSQS Inbound endpoint " + name + " unable to get a connection.");
            isConnected = false;
            return null;
        }
        List<Message> messages;
        receiveMessageRequest.setMessageAttributeNames(attributeNames);
        messages = sqsClient.receiveMessage(receiveMessageRequest).getMessages();
        if (!messages.isEmpty()) {
            for (Message message : messages) {
                boolean commitOrRollbacked;
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Injecting AmazonSQS message to the sequence : " + injectingSeq + " of " + name);
                }
                //Get the content type of the message.
                if (message.getMessageAttributes().containsKey(AmazonSQSConstants.CONTENT_TYPE)) {
                    contentType = message.getMessageAttributes().get(AmazonSQSConstants.CONTENT_TYPE)
                            .getStringValue();
                    if (contentType.trim().equals("") || contentType.equals("null")) {
                        contentType = AmazonSQSConstants.DEFAULT_CONTENT_TYPE;
                    }
                } else {
                    contentType = properties.getProperty(AmazonSQSConstants.CONTENT_TYPE);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Loading the Content-type : " + contentType + " for " + name);
                }
                commitOrRollbacked = injectMessage(message.getBody(), contentType);
                if (commitOrRollbacked) {
                    messageReceiptHandle = message.getReceiptHandle();
                    sqsClient.deleteMessage(new DeleteMessageRequest(destination, messageReceiptHandle));
                }
            }
        } else {
            return null;
        }
    } catch (AmazonServiceException e) {
        throw new SynapseException("Caught an AmazonServiceException, which means your "
                + "request made it to Amazon SQS, but was rejected with an" + "error response for some reason.",
                e);
    } catch (AmazonClientException e) {
        throw new SynapseException("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.", e);
    }
    return null;
}

From source file:pa3.RemoteClientSQS.java

License:Open Source License

public static void main(String[] args) throws Exception {

    initSQSandDynamoDB();// w w  w.j  a  v  a  2s.  c  om

    double startTime, endTime, totalTime;

    // String fileName =
    // "C:/Cloud/Assignment/LocalQueueAsst3/src/cloud/asst3/queue/10KSleepTasks.txt";
    // int noOfThreads = 16 ;
    // String localOrRemote = "REMOTE";
    // String clientOrWorker = "CLIENT";

    String fileName = args[4];
    String requestQueueName = "MyRequestQueue" + args[2];
    String responseQueueName = "MyResponseQueue" + args[2];
    String clientOrWorker = args[0];

    System.out.println("===========================================");
    System.out.println("Lets get started with Amazon SQS");
    System.out.println("===========================================\n");

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called MyRequestQueue.\n");
        CreateQueueRequest createRequestQueue = new CreateQueueRequest(requestQueueName);
        String myRequestQueueUrl = sqs.createQueue(createRequestQueue).getQueueUrl();

        System.out.println("Creating a new SQS queue called MyResponseQueue.\n");
        CreateQueueRequest createResponseQueue = new CreateQueueRequest(responseQueueName);
        String myResponseQueueUrl = sqs.createQueue(createResponseQueue).getQueueUrl();

        // List queues
        System.out.println("Listing all queues in your account.\n");
        for (String queueUrl : sqs.listQueues().getQueueUrls()) {
            System.out.println("  QueueUrl: " + queueUrl);
        }

        // Send a message
        System.out.println("Sending a message to " + requestQueueName);

        int taskID = 1;
        FileReader fileReader;
        BufferedReader bufferedReader = null;
        startTime = System.nanoTime();
        try {
            fileReader = new FileReader(fileName);
            bufferedReader = new BufferedReader(fileReader);
            String eachTaskLine = null;
            mySubmittedTasks = new ConcurrentHashMap<Integer, String>();

            while ((eachTaskLine = bufferedReader.readLine()) != null) {
                sqs.sendMessage(new SendMessageRequest(myRequestQueueUrl, taskID + " " + eachTaskLine));
                mySubmittedTasks.put(taskID, eachTaskLine);
                taskID++;
            }
            bufferedReader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Sent all the messages to " + requestQueueName);

        try {
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myResponseQueueUrl);
            receiveMessageRequest.setVisibilityTimeout(900);
            receiveMessageRequest.setWaitTimeSeconds(20);

            while (!mySubmittedTasks.isEmpty()) {
                List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
                for (Message message : messages) {
                    if (mySubmittedTasks.containsKey(Integer.parseInt(message.getBody().toString()))) {
                        mySubmittedTasks.remove(Integer.parseInt(message.getBody().toString()));
                        String messageReceiptHandle = message.getReceiptHandle();
                        sqs.deleteMessage(new DeleteMessageRequest(myResponseQueueUrl, messageReceiptHandle));
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (!mySubmittedTasks.isEmpty()) {
            System.out.println("Some tasks have failed");
        }
        endTime = System.nanoTime();
        totalTime = (endTime - startTime) / 1000000000.0;
        System.out.println("This is " + clientOrWorker.toUpperCase() + " running with workers.");
        System.out.println("Total time taken: " + totalTime);

        System.out.println("Received all the messages from MyResponseQueue.\n");

    } 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:pa3.RemoteWorkerSQS.java

License:Open Source License

public static void main(String[] args) throws Exception {

    initSQSandDynamoDB();/*  w w w.j a  v a  2  s.c  o m*/
    try {

        String tableName = "PA3" + args[2];
        // Create table if it does not exist yet
        if (Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is already ACTIVE");
        } else {
            // Create a table with a primary hash key named 'name', which
            // holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(new KeySchemaElement().withAttributeName("taskID").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("taskID")
                            .withAttributeType(ScalarAttributeType.S))
                    .withProvisionedThroughput(
                            new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
            TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                    .getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.awaitTableToBecomeActive(dynamoDB, tableName);
        }

        String noOfWorkers = args[4];
        String requestQueueName = "TaskQueue" + args[2];
        String responseQueueName = "TaskResponseQueue" + args[2];
        String clientOrWorker = args[0];

        // Create a queue
        //System.out.println("Accessing SQS queue: "+requestQueueName);
        String myRequestQueueUrl = sqs.createQueue(requestQueueName).getQueueUrl();

        //System.out.println("Creating a new SQS queue called MyResponseQueue.\n");
        String myResponseQueueUrl = sqs.createQueue(responseQueueName).getQueueUrl();

        // Receive the messages
        try {
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myRequestQueueUrl);
            receiveMessageRequest.setVisibilityTimeout(900);
            receiveMessageRequest.setWaitTimeSeconds(20);
            while (true) {
                List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
                // Throw exception when queue gets empty
                if (messages.isEmpty()) {
                    break;
                }
                for (Message message : messages) {
                    try {
                        String[] splitTask = message.getBody().split(" ");
                        //DynamoDB
                        Map<String, AttributeValue> item = newItem(splitTask[0]);
                        PutItemRequest putItemRequest = new PutItemRequest(tableName, item)
                                .withConditionExpression("attribute_not_exists(taskID)");
                        dynamoDB.putItem(putItemRequest);

                        //System.out.println(splitTask[0]+" : "+splitTask[2]);
                        // Execute Task
                        Thread.sleep(Long.parseLong(splitTask[2]));
                        sqs.sendMessage(new SendMessageRequest(myResponseQueueUrl, splitTask[0]));
                        // Delete the message
                        String messageReceiptHandle = message.getReceiptHandle();
                        sqs.deleteMessage(new DeleteMessageRequest(myRequestQueueUrl, messageReceiptHandle));

                    } catch (ConditionalCheckFailedException e) {
                        //e.printStackTrace();
                    }
                }
            }
        } catch (Exception ex) {
            //ex.printStackTrace();
        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, 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 AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }

}

From source file:Reference.SimpleQueueServiceSample.java

License:Open Source License

public static void main(String[] args) throws Exception {

    /*/*from w  w w. j ava  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 ProfileCredentialsProvider("default").getCredentials();
    } 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/daniel/.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 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:scheduler.ServerThread.java

License:Apache License

@SuppressWarnings("unchecked")
public void remoteBatchReceive(PrintWriter out) throws ParseException {
    JSONArray responseList = new JSONArray();
    JSONParser parser = new JSONParser();

    while (msg_cnt > 0) {
        while (resQ.getQueueSize() > 0) {
            //Get up to 10 messages
            List<Message> messages = resQ.batchReceive();

            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 resp = (JSONObject) parser.parse(messageBody);
                responseList.add(resp);/*from   w  w w  .j ava2s. c  o m*/

                msg_cnt--;
                // Delete the message
                String messageRecieptHandle = message.getReceiptHandle();
                resQ.deleteMessage(messageRecieptHandle);

            }
            if (!responseList.isEmpty()) {
                out.println(responseList.toString());
                responseList.clear();
            }

        }
    }
}

From source file:se252.jan15.calvinandhobbes.project0.IIScCampusMapGETProxyService.java

License:Open Source License

private static String getCategoryData(String category) {
    AmazonSQS queueClient = Queues.getQueue();
    String resp = null;/*from   ww w  .  ja  v a  2 s  .c  o m*/
    try {
        // Send a message
        queueClient.sendMessage(new SendMessageRequest(Queues.req, category));

        // Receive messages
        Boolean flag = true;
        while (flag) {
            ReceiveMessageRequest receiveReq = new ReceiveMessageRequest(Queues.resp);
            receiveReq.setWaitTimeSeconds(10);
            List<Message> messages = queueClient.receiveMessage(receiveReq).getMessages();
            for (Message message : messages) {
                String[] strs = message.getBody().split("\\$");
                if (strs[0].equals(category)) {
                    flag = false;
                    resp = strs[1];
                    queueClient
                            .deleteMessage(new DeleteMessageRequest(Queues.resp, message.getReceiptHandle()));
                    break;
                }
            }
        }
    } 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());
    }
    return resp;
}