Example usage for com.amazonaws.services.sqs.model CreateQueueRequest CreateQueueRequest

List of usage examples for com.amazonaws.services.sqs.model CreateQueueRequest CreateQueueRequest

Introduction

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

Prototype

public CreateQueueRequest(String queueName) 

Source Link

Document

Constructs a new CreateQueueRequest object.

Usage

From source file:com.comcast.cqs.controller.CQSUserPageServlet.java

License:Apache License

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (redirectUnauthenticatedUser(request, response)) {
        return;//from   ww  w  .  java 2 s  .  c o m
    }

    boolean showQueueAttributes = false;
    boolean showQueuesWithMessagesOnly = false;

    CMBControllerServlet.valueAccumulator.initializeAllCounters();
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    Map<?, ?> parameters = request.getParameterMap();
    String userId = request.getParameter("userId");
    String queueName = request.getParameter("queueName");
    String queueNamePrefix = request.getParameter("queueNamePrefix");
    String queueUrl = request.getParameter("qUrl");

    if (request.getParameter("ShowMessagesOnly") != null) {
        showQueuesWithMessagesOnly = true;
    }

    if (request.getParameter("ShowAttributes") != null) {
        showQueueAttributes = true;
    }

    List<String> queueUrls = new ArrayList<String>();

    connect(request);

    if (parameters.containsKey("Search")) {
    }

    try {

        String url = cqsServiceBaseUrl + "?Action=ListQueues&AWSAccessKeyId=" + user.getAccessKey();

        if (queueNamePrefix != null && !queueNamePrefix.equals("")) {
            url += "&QueueNamePrefix=" + queueNamePrefix;
        }

        if (showQueuesWithMessagesOnly) {
            url += "&ContainingMessagesOnly=true";
        }

        AWSCredentials awsCredentials = new BasicAWSCredentials(user.getAccessKey(), user.getAccessSecret());
        String apiStateXml = httpPOST(cqsServiceBaseUrl, url, awsCredentials);
        Element root = XmlUtil.buildDoc(apiStateXml);
        List<Element> resultList = XmlUtil.getCurrentLevelChildNodes(root, "ListQueuesResult");

        for (Element resultElement : resultList) {
            List<Element> urls = XmlUtil.getCurrentLevelChildNodes(resultElement, "QueueUrl");
            for (Element urlElement : urls) {
                queueUrls.add(urlElement.getTextContent().trim());
            }
        }

    } catch (Exception ex) {
        logger.error("event=list_queues user_id= " + userId, ex);
        throw new ServletException(ex);
    }

    if (parameters.containsKey("Create")) {

        try {
            CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
            CreateQueueResult createQueueResult = sqs.createQueue(createQueueRequest);
            queueUrl = createQueueResult.getQueueUrl();
            queueUrls.add(queueUrl);
            logger.debug("event=create_queue queue_url=" + queueUrl + " user_id= " + userId);
        } catch (Exception ex) {
            logger.error("event=create_queue queue_url=" + queueUrl + " user_id= " + userId, ex);
            throw new ServletException(ex);
        }

    } else if (parameters.containsKey("Delete")) {

        try {
            DeleteQueueRequest deleteQueueRequest = new DeleteQueueRequest(queueUrl);
            sqs.deleteQueue(deleteQueueRequest);
            queueUrls.remove(queueUrl);
            logger.debug("event=delete_queue queue_url=" + queueUrl + " user_id= " + userId);
        } catch (Exception ex) {
            logger.error("event=delete_queue queue_url=" + queueUrl + " user_id= " + userId, ex);
            throw new ServletException(ex);
        }

    } else if (parameters.containsKey("DeleteAll")) {

        for (int i = 0; queueUrls != null && i < queueUrls.size(); i++) {

            try {
                DeleteQueueRequest deleteQueueRequest = new DeleteQueueRequest(queueUrls.get(i));
                sqs.deleteQueue(deleteQueueRequest);
                logger.debug("event=delete_queue queue_url=" + queueUrls.get(i) + " user_id= " + userId);
            } catch (Exception ex) {
                logger.error("event=delete_queue queue_url=" + queueUrls.get(i) + " user_id= " + userId, ex);
            }
        }

        queueUrls = new ArrayList<String>();

    } else if (parameters.containsKey("ClearQueue")) {

        String qName = Util.getNameForAbsoluteQueueUrl(queueUrl);
        String qUserId = Util.getUserIdForAbsoluteQueueUrl(queueUrl);

        try {
            String url = cqsServiceBaseUrl;
            if (!url.endsWith("/")) {
                url += "/";
            }
            url += qUserId + "/" + qName + "?Action=ClearQueue&AWSAccessKeyId=" + user.getAccessKey();
            httpGet(url);
            logger.debug("event=clear_queue url=" + url + " user_id= " + userId);
        } catch (Exception ex) {
            logger.error("event=clear_queue queue_name=" + qName + " user_id= " + userId, ex);
            throw new ServletException(ex);
        }

    } else if (parameters.containsKey("ClearAllQueues")) {

        for (int i = 0; queueUrls != null && i < queueUrls.size(); i++) {

            String qName = Util.getNameForAbsoluteQueueUrl(queueUrls.get(i));
            String qUserId = Util.getUserIdForAbsoluteQueueUrl(queueUrls.get(i));

            try {
                String url = cqsServiceBaseUrl;
                if (!url.endsWith("/")) {
                    url += "/";
                }
                url += qUserId + "/" + qName + "?Action=ClearQueue&AWSAccessKeyId=" + user.getAccessKey();
                httpGet(url);
                logger.debug("event=clear_queue url=" + url + " user_id= " + userId);
            } catch (Exception ex) {
                logger.error("event=clear_queue queue_name=" + qName + " user_id= " + userId, ex);
            }
        }
    }

    out.println("<html>");

    header(request, out, "Queues");

    out.println("<body>");

    out.println("<h2>Queues</h2>");

    long numQueues = 0;

    try {
        numQueues = PersistenceFactory.getUserPersistence().getNumUserQueues(userId);
    } catch (PersistenceException ex) {
        logger.warn("event=queue_count_failure", ex);
    }

    if (user != null) {
        out.println("<table><tr><td><b>User Name:</b></td><td>" + user.getUserName() + "</td></tr>");
        out.println("<tr><td><b>User ID:</b></td><td>" + user.getUserId() + "</td></tr>");
        out.println("<tr><td><b>Access Key:</b></td><td>" + user.getAccessKey() + "</td></tr>");
        out.println("<tr><td><b>Access Secret:</b></td><td>" + user.getAccessSecret() + "</td>");
        out.println("<tr><td><b>Queue Count</b></td><td>" + numQueues + "</td></tr></table>");
    }

    out.println("<p><table>");

    out.println("<tr><td>Search queues with name prefix:</td><td></td></tr>");
    out.println("<tr><form action=\"/webui/cqsuser?userId=" + user.getUserId() + "\" method=POST>");
    out.println("<td><input type='text' name='queueNamePrefix' value='"
            + (queueNamePrefix != null ? queueNamePrefix : "") + "'/><input type='hidden' name='userId' value='"
            + userId + "'/>");
    out.println("<input type='checkbox' " + (showQueueAttributes ? "checked='true' " : "")
            + "name='ShowAttributes' value='ShowAttributes'>Show Attributes</input>");
    out.println("<input type='checkbox' " + (showQueuesWithMessagesOnly ? "checked='true' " : "")
            + " name='ShowMessagesOnly' value='ShowMessagesOnly'>Only Queues With Messages</input></td>");
    out.println("<td><input type='submit' value='Search' name='Search' /></td></form></tr>");

    out.println("<tr><td>Create queue with name:</td><td></td></tr>");
    out.println("<tr><form action=\"/webui/cqsuser?userId=" + user.getUserId() + "\" method=POST>");
    out.println("<td><input type='text' name='queueName' /><input type='hidden' name='userId' value='" + userId
            + "'></td>");
    out.println("<input type='hidden' name='queueNamePrefix' value='"
            + (queueNamePrefix != null ? queueNamePrefix : "") + "'/>");
    if (showQueuesWithMessagesOnly) {
        out.println("<input type='hidden' name='ShowMessagesOnly' value='true'/>");
    }
    if (showQueueAttributes) {
        out.println("<input type='hidden' name='ShowAttributes' value='true'/>");
    }
    out.println("<td><input type='submit' value='Create' name='Create' /></td></form></tr>");

    out.println("<tr><td>Delete all queues:</td><td></td></tr>");
    out.println("<tr><form action=\"/webui/cqsuser?userId=" + user.getUserId() + "\" "
            + "method=POST><td><input type='hidden' name='userId' value='" + userId + "'/>");
    out.println("<input type='hidden' name='queueNamePrefix' value='"
            + (queueNamePrefix != null ? queueNamePrefix : "") + "'/></td>");
    if (showQueuesWithMessagesOnly) {
        out.println("<input type='hidden' name='ShowMessagesOnly' value='true'/>");
    }
    if (showQueueAttributes) {
        out.println("<input type='hidden' name='ShowAttributes' value='true'/>");
    }
    out.println(
            "<td><input type='submit' value='Delete All' name='DeleteAll' onclick=\"return confirm('Are you sure you want to delete all?')\" /></td></form></tr>");

    out.println("<tr><td>Clear all queues:</td><td></td></tr>");
    out.println("<tr><form action=\"/webui/cqsuser?userId=" + user.getUserId() + "\" "
            + "method=POST><td><input type='hidden' name='userId' value='" + userId + "'/>");
    out.println("<input type='hidden' name='queueNamePrefix' value='"
            + (queueNamePrefix != null ? queueNamePrefix : "") + "'/></td>");
    if (showQueuesWithMessagesOnly) {
        out.println("<input type='hidden' name='ShowMessagesOnly' value='true'/>");
    }
    if (showQueueAttributes) {
        out.println("<input type='hidden' name='ShowAttributes' value='true'/>");
    }
    out.println("<td><input type='submit' value='Clear All' name='ClearAllQueues'/></td></form></tr>");

    out.println("</table></p>");

    out.println("<p><hr width='100%' align='left' /></p>");

    if ((queueUrls != null) && (queueUrls.size() >= 1000)) {
        out.println("Warning: Only first 1000 queues listed.  Use the search prefix method to find queues");
    }
    out.println("<p><table class = 'alternatecolortable' border='1'>");
    out.println("<tr><th>&nbsp;</th>");
    out.println("<th>Queue Url</th>");
    out.println("<th>Queue Arn</th>");
    out.println("<th>Queue Name</th>");
    out.println("<th>User Id</th>");
    out.println("<th>Region</th>");
    out.println("<th>Visibility TO</th>");
    out.println("<th>Max Msg Size</th>");
    out.println("<th>Msg Rention Period</th>");
    out.println("<th>Delay Seconds</th>");
    out.println("<th>Wait Time Seconds</th>");
    out.println("<th>Num Partitions</th>");
    out.println("<th>Num Shards</th>");
    out.println("<th>Compressed</th>");
    out.println("<th>Approx Num Msg</th>");
    out.println("<th>Approx Num Msg Not Visible</th>");
    out.println("<th>Approx Num Msg Delayed</th>");
    out.println("<th>&nbsp;</th><th>&nbsp;</th><th>&nbsp;</th><th>&nbsp;</th></tr>");

    for (int i = 0; queueUrls != null && i < queueUrls.size(); i++) {

        Map<String, String> attributes = new HashMap<String, String>();

        if (showQueueAttributes) {
            try {
                GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(
                        queueUrls.get(i));
                getQueueAttributesRequest.setAttributeNames(Arrays.asList("VisibilityTimeout",
                        "MaximumMessageSize", "MessageRetentionPeriod", "DelaySeconds",
                        "ApproximateNumberOfMessages", "ApproximateNumberOfMessagesNotVisible",
                        "ApproximateNumberOfMessagesDelayed", "ReceiveMessageWaitTimeSeconds",
                        "NumberOfPartitions", "NumberOfShards", "IsCompressed"));
                GetQueueAttributesResult getQueueAttributesResult = sqs
                        .getQueueAttributes(getQueueAttributesRequest);
                attributes = getQueueAttributesResult.getAttributes();
            } catch (Exception ex) {
                logger.error("event=get_queue_attributes url=" + queueUrls.get(i));
            }
        }

        out.println("<tr>");
        out.println("<form action=\"/webui/cqsuser?userId=" + user.getUserId() + "\" method=POST>");
        out.println("<td>" + i + "</td>");
        out.println("<td>" + queueUrls.get(i) + "<input type='hidden' name='qUrl' value=" + queueUrls.get(i)
                + "><input type='hidden' name='qName' value="
                + Util.getNameForAbsoluteQueueUrl(queueUrls.get(i)) + "></td>");
        out.println("<td>" + Util.getArnForAbsoluteQueueUrl(queueUrls.get(i))
                + "<input type='hidden' name='arn' value=" + Util.getArnForAbsoluteQueueUrl(queueUrls.get(i))
                + "></td>");
        out.println("<td>" + Util.getNameForAbsoluteQueueUrl(queueUrls.get(i)) + "</td>");
        out.println("<td>" + user.getUserId() + "<input type='hidden' name='userId' value=" + user.getUserId()
                + "></td>");
        out.println("<td>" + CMBProperties.getInstance().getRegion() + "</td>");

        out.println("<td>"
                + (attributes.get("VisibilityTimeout") != null ? attributes.get("VisibilityTimeout") : "")
                + "</td>");
        out.println("<td>"
                + (attributes.get("MaximumMessageSize") != null ? attributes.get("MaximumMessageSize") : "")
                + "</td>");
        out.println("<td>"
                + (attributes.get("MessageRetentionPeriod") != null ? attributes.get("MessageRetentionPeriod")
                        : "")
                + "</td>");
        out.println("<td>" + (attributes.get("DelaySeconds") != null ? attributes.get("DelaySeconds") : "")
                + "</td>");
        out.println("<td>" + (attributes.get("ReceiveMessageWaitTimeSeconds") != null
                ? attributes.get("ReceiveMessageWaitTimeSeconds")
                : "") + "</td>");
        out.println("<td>"
                + (attributes.get("NumberOfPartitions") != null ? attributes.get("NumberOfPartitions") : "")
                + "</td>");
        out.println("<td>" + (attributes.get("NumberOfShards") != null ? attributes.get("NumberOfShards") : "")
                + "</td>");
        out.println("<td>" + (attributes.get("IsCompressed") != null ? attributes.get("IsCompressed") : "")
                + "</td>");
        out.println("<td>" + (attributes.get("ApproximateNumberOfMessages") != null
                ? attributes.get("ApproximateNumberOfMessages")
                : "") + "</td>");
        out.println("<td>" + (attributes.get("ApproximateNumberOfMessagesNotVisible") != null
                ? attributes.get("ApproximateNumberOfMessagesNotVisible")
                : "") + "</td>");
        out.println("<td>" + (attributes.get("ApproximateNumberOfMessagesDelayed") != null
                ? attributes.get("ApproximateNumberOfMessagesDelayed")
                : "") + "</td>");

        out.println("<td><a href='/webui/cqsuser/message?userId=" + user.getUserId() + "&queueName="
                + Util.getNameForAbsoluteQueueUrl(queueUrls.get(i)) + "'>Messages</a></td>");
        out.println("<td><a href='/webui/cqsuser/permissions?userId=" + user.getUserId() + "&queueName="
                + Util.getNameForAbsoluteQueueUrl(queueUrls.get(i)) + "'>Permissions</a></td>");
        out.println("<td><a href='' onclick=\"window.open('/webui/cqsuser/editqueueattributes?queueName="
                + Util.getNameForAbsoluteQueueUrl(queueUrls.get(i)) + "&userId=" + userId
                + "', 'EditQueueAttributes', 'height=630,width=580,toolbar=no')\">Attributes</a></td>");

        out.println("<input type='hidden' name='queueNamePrefix' value='"
                + (queueNamePrefix != null ? queueNamePrefix : "") + "'/>");
        if (showQueuesWithMessagesOnly) {
            out.println("<input type='hidden' name='ShowMessagesOnly' value='true'/>");
        }
        if (showQueueAttributes) {
            out.println("<input type='hidden' name='ShowAttributes' value='true'/>");
        }

        out.println(
                "<td><input type='submit' value='Clear' name='ClearQueue'/> <br/><input type='submit' value='Delete' name='Delete' onclick=\"return confirm('Are you sure you want to delete queue "
                        + Util.getNameForAbsoluteQueueUrl(queueUrls.get(i)) + "?')\" /></td></form></tr>");

    }

    out.println("</table></p>");
    out.println("<h5 style='text-align:center;'><a href='/webui'>ADMIN HOME</a></h5>");
    out.println("</body></html>");

    CMBControllerServlet.valueAccumulator.deleteAllCounters();
}

From source file:com.dxc.temp.SimpleQueueServiceSample.java

License:Open Source License

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

    BasicConfigurator.configure();/*from w  ww  . j ava 2  s.c o  m*/

    /*
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().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 (~/.aws/credentials), and is in valid format.", e);
    }
    System.out.println(String.format("Found AWSAccessKeyId: %s", credentials.getAWSAccessKeyId()));
    System.out.println(String.format("Found AWSAccessSecretKey: %s", credentials.getAWSSecretKey()));

    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, "Message body 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 messageReceiptHandle = messages.get(0).getReceiptHandle();
        //            sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));

        // Delete a queue
        // You must wait 60 seconds after deleting a queue before you can create another with the same name
        //            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:com.erudika.para.queue.AWSQueueUtils.java

License:Apache License

/**
 * Creates a new SQS queue on AWS./* w w w  .jav  a 2s . c o  m*/
 * @param name queue name
 * @return the queue URL or null
 */
public static String createQueue(String name) {
    if (StringUtils.isBlank(name)) {
        return null;
    }
    String queueURL = getQueueURL(name);
    if (queueURL == null) {
        try {
            queueURL = getClient().createQueue(new CreateQueueRequest(name)).getQueueUrl();
        } catch (AmazonServiceException ase) {
            logException(ase);
        } catch (AmazonClientException ace) {
            logger.error("Could not reach SQS. {0}", ace.toString());
        }
    }
    return queueURL;
}

From source file:com.espressologic.aws.sqs.SqsAmazonService.java

License:Open Source License

public static String createQueue(String queueName) {
    // Create a queue
    AmazonSQS sqs = createAWSCredentials();
    assert queueName != null;
    System.out.println("Creating a new SQS queue called " + queueName + ".\n");
    CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
    return sqs.createQueue(createQueueRequest).getQueueUrl();
}

From source file:com.jktsoftware.amazondownloader.queuemanager.DownloaderQueueManager.java

License:Open Source License

public void CreateQueues() {
    AWSCredentials awscredentials = new BasicAWSCredentials(this._credentials.getAccessKey(),
            this._credentials.getSecretAccessKey());

    _sqs = new AmazonSQSClient(awscredentials);
    Region euWest1 = Region.getRegion(Regions.EU_WEST_1);
    _sqs.setRegion(euWest1);//  w  w w  .  j  a  v a 2  s. c  o  m

    System.out.println("Creating amazon download queues.\n");

    CreateQueueRequest createReceivedQueueRequest = new CreateQueueRequest(_receivedqueuename);

    this._receivedqueueurl = _sqs.createQueue(createReceivedQueueRequest).getQueueUrl();

    CreateQueueRequest createFailedQueueRequest = new CreateQueueRequest(_failedqueuename);

    this._failedqueueurl = _sqs.createQueue(createFailedQueueRequest).getQueueUrl();
}

From source file:com.kiribuki.queueservice.QueueService.java

License:Open Source License

public boolean CreateQueue(String QueueName) {
    if (swok == true) {
        try {/*w  w w .j ava  2  s. c o m*/
            CreateQueueRequest createQueueRequest = new CreateQueueRequest(QueueName);
            myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();
            return true;
        } 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());
            swok = false;
        }
    } else {
        System.out.println("NO ESTA OK L'OBJECTE");
        swok = false;
    }
    return swok;
}

From source file:com.pocketdealhunter.HotDealsMessagesUtil.java

License:Open Source License

private String createQueue() {
    try {/*from   ww  w  .j  a  va2 s . c om*/
        CreateQueueRequest cqr = new CreateQueueRequest(Constants.QUEUE_NAME);
        CreateQueueResult result = this.sqsClient.createQueue(cqr);

        String queueArn = this.getQueueArn(result.getQueueUrl());
        this.addPolicyToQueueForTopic(result.getQueueUrl(), queueArn);

        return result.getQueueUrl();
    } catch (Exception exception) {
        System.out.println("Exception = " + exception);
        return null;
    }
}

From source file:com.rodosaenz.samples.aws.sqs.AwsSqsSimpleExample.java

License:Open Source License

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

    /*/*w  w w.jav a 2s  . co  m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().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 (~/.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");

    String queue_name = "com-rodosaenz-examples-aws-sqs";

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called " + queue_name + ".\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(queue_name);
        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 " + queue_name + ".\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);
        receiveMessageRequest.setMaxNumberOfMessages(1);
        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 messageReceiptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));

        //Get attributes
        GetQueueAttributesRequest request = new GetQueueAttributesRequest(myQueueUrl).withAttributeNames("All");
        final Map<String, String> attributes = sqs.getQueueAttributes(request).getAttributes();

        System.out.println("  Policy: " + attributes.get("Policy"));
        System.out.println("  MessageRetentionPeriod: " + attributes.get("MessageRetentionPeriod"));
        System.out.println("  MaximumMessageSize: " + attributes.get("MaximumMessageSize"));
        System.out.println("  CreatedTimestamp: " + attributes.get("CreatedTimestamp"));
        System.out.println("  VisibilityTimeout: " + attributes.get("VisibilityTimeout"));
        System.out.println("  QueueArn: " + attributes.get("QueueArn"));
        System.out.println("  ApproximateNumberOfMessages: " + attributes.get("ApproximateNumberOfMessages"));
        System.out.println("  ApproximateNumberOfMessagesNotVisible: "
                + attributes.get("ApproximateNumberOfMessagesNotVisible"));
        System.out.println("  DelaySeconds: " + attributes.get("DelaySeconds"));

        // 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:com.rss.common.AWSDetails.java

License:Apache License

public static void main(String[] args) {
    String queueUrl = SQS.createQueue(new CreateQueueRequest(SQS_QUEUE_NAME)).getQueueUrl();
    System.out.println("Using Amazon SQS Queue: " + queueUrl);

    String publisherQueueUrl = SQS.createQueue(new CreateQueueRequest(SQS_PUBLISHER_QUEUE)).getQueueUrl();
    System.out.println("Using Amazon SQS Queue: " + publisherQueueUrl);

    String webserviceRequestQueueUrl = SQS.createQueue(new CreateQueueRequest(SQS_WEBSERVICE_REQUEST_QUEUE))
            .getQueueUrl();//from  w  ww. ja  v a 2 s  .  c  o  m
    System.out.println("Using Amazon SQS Queue: " + webserviceRequestQueueUrl);

    if (!Tables.doesTableExist(DYNAMODB, JOBREQUEST_TABLE_NAME)) {
        System.out.println("Creating job request table...");
        DYNAMODB.createTable(new CreateTableRequest().withTableName(JOBREQUEST_TABLE_NAME)
                .withKeySchema(new KeySchemaElement("id", KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition("id", ScalarAttributeType.S))
                .withProvisionedThroughput(new ProvisionedThroughput(50l, 50l)));
    }
    if (!Tables.doesTableExist(DYNAMODB, FEEDURL_REQUEST_TABLE_NAME)) {
        System.out.println("Creating feed url request table...");
        DYNAMODB.createTable(new CreateTableRequest().withTableName(FEEDURL_REQUEST_TABLE_NAME)
                .withKeySchema(new KeySchemaElement("id", KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition("id", ScalarAttributeType.S))
                .withProvisionedThroughput(new ProvisionedThroughput(50l, 50l)));
    }
    if (!Tables.doesTableExist(DYNAMODB, SUBSCRIBER_TABLE_NAME)) {
        System.out.println("Creating subscriber table...");
        DYNAMODB.createTable(new CreateTableRequest().withTableName(SUBSCRIBER_TABLE_NAME)
                .withKeySchema(new KeySchemaElement("id", KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition("id", ScalarAttributeType.S))
                .withProvisionedThroughput(new ProvisionedThroughput(50l, 50l)));
    }
    if (!Tables.doesTableExist(DYNAMODB, CHANNEL_TABLE_NAME)) {
        System.out.println("Creating channel table....");
        DYNAMODB.createTable(new CreateTableRequest().withTableName(CHANNEL_TABLE_NAME)
                .withKeySchema(new KeySchemaElement("id", KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition("id", ScalarAttributeType.S))
                .withProvisionedThroughput(new ProvisionedThroughput(50l, 50l)));
    }
    if (!Tables.doesTableExist(DYNAMODB, FEED_URL_TABLE_NAME)) {
        System.out.println("Creating feedurl table....");
        DYNAMODB.createTable(new CreateTableRequest().withTableName(FEED_URL_TABLE_NAME)
                .withKeySchema(new KeySchemaElement("id", KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition("id", ScalarAttributeType.S))
                .withProvisionedThroughput(new ProvisionedThroughput(50l, 50l)));
    }
    if (!Tables.doesTableExist(DYNAMODB, ARTICLE_TABLE_NAME)) {
        System.out.println("Creating article table....");
        DYNAMODB.createTable(new CreateTableRequest().withTableName(ARTICLE_TABLE_NAME)
                .withKeySchema(new KeySchemaElement("id", KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition("id", ScalarAttributeType.S))
                .withProvisionedThroughput(new ProvisionedThroughput(50l, 50l)));
    }
    Tables.waitForTableToBecomeActive(DYNAMODB, JOBREQUEST_TABLE_NAME);
    Tables.waitForTableToBecomeActive(DYNAMODB, FEEDURL_REQUEST_TABLE_NAME);
    Tables.waitForTableToBecomeActive(DYNAMODB, SUBSCRIBER_TABLE_NAME);
    Tables.waitForTableToBecomeActive(DYNAMODB, CHANNEL_TABLE_NAME);
    Tables.waitForTableToBecomeActive(DYNAMODB, FEED_URL_TABLE_NAME);
    Tables.waitForTableToBecomeActive(DYNAMODB, ARTICLE_TABLE_NAME);
    System.out.println("Using AWS DynamoDB Table: " + JOBREQUEST_TABLE_NAME + "," + SUBSCRIBER_TABLE_NAME + ","
            + CHANNEL_TABLE_NAME);
}

From source file:com.sjsu.cmpe281.team06.NovaMiaas.SimpleQueueServiceSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*//from   w  ww.  j  av  a 2 s.  c  o  m
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     *
     * 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 ClasspathPropertiesFileCredentialsProvider());
    Region usWest1 = Region.getRegion(Regions.US_WEST_1);
    sqs.setRegion(usWest1);

    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 new 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());
    }
}