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

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

Introduction

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

Prototype


public String getBody() 

Source Link

Document

The message's contents (not URL-encoded).

Usage

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

License:Open Source License

private JobStatusNotification parseNotification(Message message) throws IOException {
    SNSNotification<JobStatusNotification> notification = mapper.readValue(message.getBody(),
            new TypeReference<SNSNotification<JobStatusNotification>>() {
            });//from   ww  w .j a  va2  s  . c om
    return notification.getMessage();
}

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//from  w w w.  java2s  .co 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.transitime.maintenance.AwsGlacierInventoryRetriever.java

License:Open Source License

/**
 * For retrieving vault inventory. //from w ww . j a  va 2 s.  c  o  m
 * 
 * @param jobId
 * @param sqsQueueUrl
 * @return
 * @throws JsonParseException
 * @throws IOException
 */
private Boolean waitForJobToComplete(String jobId, String sqsQueueUrl) throws JsonParseException, IOException {
    logger.info("Waiting for job to complete. jobId={}", jobId);

    Boolean messageFound = false;
    Boolean jobSuccessful = false;
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();

    while (!messageFound) {
        List<Message> msgs = sqsClient
                .receiveMessage(new ReceiveMessageRequest(sqsQueueUrl).withMaxNumberOfMessages(10))
                .getMessages();

        if (msgs.size() > 0) {
            for (Message m : msgs) {
                @SuppressWarnings("deprecation")
                JsonParser jpMessage = factory.createJsonParser(m.getBody());
                JsonNode jobMessageNode = mapper.readTree(jpMessage);
                String jobMessage = jobMessageNode.get("Message").textValue();

                @SuppressWarnings("deprecation")
                JsonParser jpDesc = factory.createJsonParser(jobMessage);
                JsonNode jobDescNode = mapper.readTree(jpDesc);
                String retrievedJobId = jobDescNode.get("JobId").textValue();
                String statusCode = jobDescNode.get("StatusCode").textValue();
                if (retrievedJobId.equals(jobId)) {
                    messageFound = true;
                    if (statusCode.equals("Succeeded")) {
                        jobSuccessful = true;
                    }
                }
            }

        } else {
            Time.sleep(sleepTimeMsec);
        }
    }
    return (messageFound && jobSuccessful);
}

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.  j av  a2 s.  c om*/
 */
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 ww.ja  v  a2s . c o  m

    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();//from  w  w  w  . j a va  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  ww.j  a  va  2s  .  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  ava2  s .  co  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;//  w w  w . j av a 2s.  co  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;
}

From source file:Server.aws.yulei.SQSOperation.java

License:Open Source License

public static void receiveSQS() {
    AWSCredentials credentials = null;// ww w  .  j  a v a 2s  .  c o m
    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 usWest2 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usWest2);

    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 = "https://sqs.us-east-1.amazonaws.com/659322195879/MyQueue";

        // List queues

        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        for (Message message : messages) {
            String realData = message.getBody();
            AlchemyAPI alchemyObj = AlchemyAPI
                    .GetInstanceFromString("a47635756e657c0dac0bc2d282dbde377de01513");
            JSONParser parser = new JSONParser();
            JSONObject decodeObj = (JSONObject) parser.parse(realData);
            String content = (String) decodeObj.get("content");

            // load text
            String text = content;

            // analyze text
            Document doc = alchemyObj.TextGetTextSentiment(text);
            String score = "0.00000";
            // parse XML result
            //              String sentiment = doc.getElementsByTagName("type").item(0).getTextContent();
            //                score = doc.getElementsByTagName("score").item(0).getTextContent();
            decodeObj.put("score", score);
            decodeObj.put("sentiment", "Positive");
            StringWriter sw = new StringWriter();
            decodeObj.writeJSONString(sw);

            String jsonText = sw.toString();
            SNSPushToGCM.push(jsonText);
        }

    } catch (Exception e) {
        Thread.currentThread().interrupt();
    }

}