Example usage for com.amazonaws.services.sqs.model CreateQueueResult getQueueUrl

List of usage examples for com.amazonaws.services.sqs.model CreateQueueResult getQueueUrl

Introduction

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

Prototype


public String getQueueUrl() 

Source Link

Document

The URL of the created Amazon SQS queue.

Usage

From source file:awslabs.lab31.SolutionCode.java

License:Open Source License

@Override
public String createQueue(AmazonSQSClient sqsClient, String queueName) {
    // TODO: Construct a CreateQueueRequest object using the provided queue name.
    CreateQueueRequest createQueueRequest = new CreateQueueRequest().withQueueName(queueName);

    // TODO: Submit the request using the createQueue method of the sqsClient object.
    CreateQueueResult createQueueResult = sqsClient.createQueue(createQueueRequest);

    // TODO: Return the queue URL from the request result.
    return createQueueResult.getQueueUrl();
}

From source file:com.comcast.cns.tools.CQSHandler.java

License:Apache License

public static synchronized void ensureQueuesExist(String queueNamePrefix, int numShards) {

    for (int i = 0; i < numShards; i++) {

        GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(queueNamePrefix + i);

        try {/*  www  . ja v  a 2s.  c o  m*/
            sqs.getQueueUrl(getQueueUrlRequest);
        } catch (AmazonServiceException ex) {

            if (ex.getStatusCode() == 400) {

                CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueNamePrefix + i);
                Map<String, String> attributes = new HashMap<String, String>();

                if (queueNamePrefix
                        .startsWith(CMBProperties.getInstance().getCNSEndpointPublishQueueNamePrefix())) {
                    attributes.put("VisibilityTimeout",
                            CMBProperties.getInstance().getCNSEndpointPublishJobVisibilityTimeout() + "");
                } else {
                    attributes.put("VisibilityTimeout",
                            CMBProperties.getInstance().getCNSPublishJobVisibilityTimeout() + "");
                }

                createQueueRequest.setAttributes(attributes);
                CreateQueueResult createQueueResponse = sqs.createQueue(createQueueRequest);

                if (createQueueResponse.getQueueUrl() == null) {
                    throw new IllegalStateException("Could not create queue with name " + queueNamePrefix + i);
                }

                logger.info("event=created_missing_queue name=" + queueNamePrefix + i + " url="
                        + createQueueResponse.getQueueUrl());

            } else {
                throw ex;
            }
        }
    }
}

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 w w w.j av  a  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.connexience.server.model.archive.glacier.SetupUtils.java

License:Open Source License

public static SQSInfo setupSQS(String accessKey, String secretKey, String domainName, String vaultName) {
    SQSInfo sqsInfo = null;/*from   w ww. j  a  v  a 2 s  . c o m*/
    try {
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);

        AmazonSQSClient amazonSQSClient = new AmazonSQSClient(awsCredentials);
        amazonSQSClient.setEndpoint("https://sqs." + domainName + ".amazonaws.com/");

        String queueName = vaultName + "-inkspot_glacier-queue";
        CreateQueueRequest createQueueRequest = new CreateQueueRequest();
        createQueueRequest.withQueueName(queueName);

        CreateQueueResult createQueueResult = amazonSQSClient.createQueue(createQueueRequest);
        if (createQueueResult != null) {
            String queueURL = createQueueResult.getQueueUrl();

            GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest();
            getQueueAttributesRequest.withQueueUrl(queueURL);
            getQueueAttributesRequest.withAttributeNames("QueueArn");

            GetQueueAttributesResult getQueueAttributesResult = amazonSQSClient
                    .getQueueAttributes(getQueueAttributesRequest);

            if (getQueueAttributesResult != null) {
                String queueARN = getQueueAttributesResult.getAttributes().get("QueueArn");

                Statement sqsStatement = new Statement(Effect.Allow);
                sqsStatement.withPrincipals(Principal.AllUsers);
                sqsStatement.withActions(SQSActions.SendMessage);
                sqsStatement.withResources(new Resource(queueARN));

                Policy sqsPolicy = new Policy();
                sqsPolicy.withStatements(sqsStatement);

                Map<String, String> sqsAttributes = new HashMap<>();
                sqsAttributes.put("Policy", sqsPolicy.toJson());

                SetQueueAttributesRequest setQueueAttributesRequest = new SetQueueAttributesRequest();
                setQueueAttributesRequest.withQueueUrl(queueURL);
                setQueueAttributesRequest.withAttributes(sqsAttributes);

                amazonSQSClient.setQueueAttributes(setQueueAttributesRequest);

                sqsInfo = new SQSInfo(queueARN, queueURL);
            } else
                logger.warn("Unable to get queue attributes: \"" + queueName + "\"");
        } else
            logger.warn("Unable to create queue: \"" + queueName + "\"");

        amazonSQSClient.shutdown();
    } catch (AmazonServiceException amazonServiceException) {
        logger.warn("AmazonServiceException: " + amazonServiceException);
        logger.debug(amazonServiceException);
    } catch (IllegalArgumentException illegalArgumentException) {
        logger.warn("IllegalArgumentException: " + illegalArgumentException);
        logger.debug(illegalArgumentException);
    } catch (AmazonClientException amazonClientException) {
        logger.warn("AmazonClientException: " + amazonClientException);
        logger.debug(amazonClientException);
    } catch (Throwable throwable) {
        logger.warn("Throwable: " + throwable);
        logger.debug(throwable);
    }

    return sqsInfo;
}

From source file:com.datatorrent.lib.io.jms.SQSTestBase.java

License:Apache License

public void produceMsg(String[] msgs, boolean purgeFirst) throws Exception {
    CreateQueueResult res = sqs.createQueue(getCurrentQueueName());
    if (purgeFirst) {
        PurgeQueueRequest purgeReq = new PurgeQueueRequest(res.getQueueUrl());
        sqs.purgeQueue(purgeReq);/*  w w  w  .jav a 2s  . c  o  m*/
    }
    for (String text : msgs) {
        sqs.sendMessage(res.getQueueUrl(), text);
    }
}

From source file:com.leverno.ysbos.archive.example.AmazonGlacierDownloadInventoryWithSQSPolling.java

License:Open Source License

private static void setupSQS() {
    CreateQueueRequest request = new CreateQueueRequest().withQueueName(sqsQueueName);
    CreateQueueResult result = sqsClient.createQueue(request);
    sqsQueueURL = result.getQueueUrl();

    GetQueueAttributesRequest qRequest = new GetQueueAttributesRequest().withQueueUrl(sqsQueueURL)
            .withAttributeNames("QueueArn");

    GetQueueAttributesResult qResult = sqsClient.getQueueAttributes(qRequest);
    sqsQueueARN = qResult.getAttributes().get("QueueArn");

    Policy sqsPolicy = new Policy()
            .withStatements(new Statement(Effect.Allow).withPrincipals(Principal.AllUsers)
                    .withActions(SQSActions.SendMessage).withResources(new Resource(sqsQueueARN)));
    Map<String, String> queueAttributes = new HashMap<String, String>();
    queueAttributes.put("Policy", sqsPolicy.toJson());
    sqsClient.setQueueAttributes(new SetQueueAttributesRequest(sqsQueueURL, queueAttributes));

}

From source file:com.netflix.conductor.contribs.queue.sqs.SQSObservableQueue.java

License:Apache License

@VisibleForTesting
String getOrCreateQueue() {/* w  w  w .ja  v  a2 s . c o  m*/
    List<String> queueUrls = listQueues(queueName);
    if (queueUrls == null || queueUrls.isEmpty()) {
        CreateQueueRequest createQueueRequest = new CreateQueueRequest().withQueueName(queueName);
        CreateQueueResult result = client.createQueue(createQueueRequest);
        return result.getQueueUrl();
    } else {
        return queueUrls.get(0);
    }
}

From source file:com.pocketdealhunter.HotDealsMessagesUtil.java

License:Open Source License

private String createQueue() {
    try {//w w  w. ja v  a 2s. c o m
        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:io.konig.maven.CreateAwsSqsQueueAction.java

License:Apache License

public AwsDeployment from(String path) throws Exception {
    String cfTemplatePresent = System.getProperty("cfTemplatePresent");
    if (cfTemplatePresent == null || cfTemplatePresent.equals("N")) {
        try {/*from ww  w.j  a v  a2  s . c o m*/
            File file = deployment.file(path);
            ObjectMapper mapper = new ObjectMapper();
            S3Bucket bucket = mapper.readValue(file, S3Bucket.class);
            deployment.verifyAWSCredentials();

            QueueConfiguration queueConfig = bucket.getNotificationConfiguration().getQueueConfiguration();

            if (queueConfig != null && queueConfig.getQueue() != null) {
                String accountId = "";
                if (System.getProperty("aws-account-id") != null) {
                    accountId = System.getProperty("aws-account-id");
                }

                Queue queue = queueConfig.getQueue();
                Regions regions = Regions.fromName(queue.getRegion());
                AmazonSQS sqs = AmazonSQSClientBuilder.standard().withCredentials(deployment.getCredential())
                        .withRegion(regions).build();
                AmazonSNS sns = AmazonSNSClientBuilder.standard().withCredentials(deployment.getCredential())
                        .withRegion(regions).build();

                CreateQueueResult result = sqs.createQueue(queue.getResourceName());

                String topicArn = StringUtils.replaceOnce(
                        bucket.getNotificationConfiguration().getTopicConfiguration().getTopicArn(),
                        "${aws-account-id}", accountId);
                String queueArn = StringUtils.replaceOnce(
                        bucket.getNotificationConfiguration().getQueueConfiguration().getQueueArn(),
                        "${aws-account-id}", accountId);

                deployment.setResponse("Queue  " + queueArn + " is created");

                Policy policy = new Policy()
                        .withStatements(new Statement(Effect.Allow).withPrincipals(Principal.AllUsers)
                                .withActions(SQSActions.SendMessage).withResources(new Resource(queueArn))
                                .withConditions(ConditionFactory.newSourceArnCondition(topicArn)));

                Map<String, String> queueAttributes = new HashMap<String, String>();
                queueAttributes.put(QueueAttributeName.Policy.toString(), policy.toJson());

                deployment.setResponse("Queue Policy Configured : " + policy.toJson());

                sqs.setQueueAttributes(new SetQueueAttributesRequest(result.getQueueUrl(), queueAttributes));

                Topics.subscribeQueue(sns, sqs, topicArn, result.getQueueUrl());

                deployment.setResponse(
                        "Subscription is created : Topic [" + topicArn + "], Queue [" + queueArn + "]");
            } else {
                deployment.setResponse("Queue Configuration Failed");
            }

        } catch (Exception e) {
            throw e;
        }
    } else {
        deployment.setResponse("Queue will be created through cloud formation template");
    }
    return deployment;
}

From source file:org.apache.camel.component.aws.sqs.SqsEndpoint.java

License:Apache License

protected void createQueue(AmazonSQS client) {
    LOG.trace("Queue '{}' doesn't exist. Will create it...", configuration.getQueueName());

    // creates a new queue, or returns the URL of an existing one
    CreateQueueRequest request = new CreateQueueRequest(configuration.getQueueName());
    if (getConfiguration().getDefaultVisibilityTimeout() != null) {
        request.getAttributes().put(QueueAttributeName.VisibilityTimeout.name(),
                String.valueOf(getConfiguration().getDefaultVisibilityTimeout()));
    }//  w w  w  .  j  av a  2 s.  c  o m
    if (getConfiguration().getMaximumMessageSize() != null) {
        request.getAttributes().put(QueueAttributeName.MaximumMessageSize.name(),
                String.valueOf(getConfiguration().getMaximumMessageSize()));
    }
    if (getConfiguration().getMessageRetentionPeriod() != null) {
        request.getAttributes().put(QueueAttributeName.MessageRetentionPeriod.name(),
                String.valueOf(getConfiguration().getMessageRetentionPeriod()));
    }
    if (getConfiguration().getPolicy() != null) {
        request.getAttributes().put(QueueAttributeName.Policy.name(),
                String.valueOf(getConfiguration().getPolicy()));
    }
    if (getConfiguration().getReceiveMessageWaitTimeSeconds() != null) {
        request.getAttributes().put(QueueAttributeName.ReceiveMessageWaitTimeSeconds.name(),
                String.valueOf(getConfiguration().getReceiveMessageWaitTimeSeconds()));
    }
    LOG.trace("Creating queue [{}] with request [{}]...", configuration.getQueueName(), request);

    CreateQueueResult queueResult = client.createQueue(request);
    queueUrl = queueResult.getQueueUrl();

    LOG.trace("Queue created and available at: {}", queueUrl);
}