Example usage for com.amazonaws.services.sqs AmazonSQSClient AmazonSQSClient

List of usage examples for com.amazonaws.services.sqs AmazonSQSClient AmazonSQSClient

Introduction

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

Prototype

AmazonSQSClient(AwsSyncClientParams clientParams) 

Source Link

Document

Constructs a new client to invoke service methods on Amazon SQS using the specified parameters.

Usage

From source file:com.brianmcmichael.sagu.AmazonDownloadRequest.java

License:Open Source License

@Override
public void actionPerformed(ActionEvent e) {

    if (e.getSource() == jbtDownload) {
        archiveId = jtfDownloadField.getText().trim();
        if ((archiveId.equals(""))) {
            JOptionPane.showMessageDialog(null, "Enter the Archive ID of the file to be requested.", "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else {/*from  ww w.  java  2  s  . c o m*/
            SwingWorker downloadWorker = new SwingWorker() {

                private String archiveId = jtfDownloadField.getText().trim();

                @Override
                protected Object doInBackground() throws Exception {

                    // Create dumb progressbar
                    JFrame downloadFrame = new JFrame("Downloading");
                    {
                        downloadFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                        final JProgressBar dumJProgressBar = new JProgressBar(JProgressBar.HORIZONTAL);
                        dumJProgressBar.setIndeterminate(true);
                        downloadFrame.add(dumJProgressBar, BorderLayout.NORTH);
                        downloadFrame.setSize(300, 60);
                    }
                    centerDefineFrame(downloadFrame, 300, 50);

                    String archiveId = jtfDownloadField.getText().trim();
                    try {
                        String vaultName = dlVault;

                        FileDialog fd = new FileDialog(new Frame(), "Save Archive As...", FileDialog.SAVE);
                        fd.setFile("Save Archive As...");
                        fd.setDirectory(System.getProperty("user.dir"));
                        fd.setLocation(50, 50);
                        fd.setVisible(true);

                        String filePath = "" + fd.getDirectory() + System.getProperty("file.separator")
                                + fd.getFile();

                        File outFile = new File(filePath);

                        if (outFile != null) {
                            downloadFrame.setTitle("Downloading " + outFile.toString());
                            downloadFrame.setVisible(true);

                            final Endpoint endpoint = Endpoint.getByIndex(locationChoice);

                            AmazonSQSClient dlSQS = new AmazonSQSClient(dlCredentials);
                            AmazonSNSClient dlSNS = new AmazonSNSClient(dlCredentials);

                            dlSQS.setEndpoint(endpoint.getSQSEndpoint());
                            dlSNS.setEndpoint(endpoint.getSNSEndpoint());

                            // ArchiveTransferManager atm = new
                            // ArchiveTransferManager(dlClient,
                            // dlCredentials);
                            ArchiveTransferManager atm = new ArchiveTransferManager(dlClient, dlSQS, dlSNS);

                            atm.download("-", vaultName, archiveId, outFile);

                            JOptionPane.showMessageDialog(null, "Sucessfully downloaded " + outFile.toString(),
                                    "Success", JOptionPane.INFORMATION_MESSAGE);
                            downloadFrame.setVisible(false);
                        }
                    } catch (AmazonServiceException k) {
                        JOptionPane.showMessageDialog(null,
                                "The server returned an error. Wait 24 hours after submitting an archive to attempt a download. Also check that correct location of archive has been set on the previous page.",
                                "Error", JOptionPane.ERROR_MESSAGE);
                        System.out.println("" + k);
                        downloadFrame.setVisible(false);
                    } catch (AmazonClientException i) {
                        JOptionPane.showMessageDialog(null,
                                "Client Error. Check that all fields are correct. Archive not downloaded.",
                                "Error", JOptionPane.ERROR_MESSAGE);
                        downloadFrame.setVisible(false);
                    } catch (Exception j) {
                        JOptionPane.showMessageDialog(null, "Archive not found. Unspecified Error.", "Error",
                                JOptionPane.ERROR_MESSAGE);
                        downloadFrame.setVisible(false);
                    }
                    return null;
                }
            };
            downloadWorker.execute();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

            this.setVisible(false);
            dispose();
        }

    } else if (e.getSource() == jbtBack) {
        this.setVisible(false);
        dispose();
    } else {
        JOptionPane.showMessageDialog(this, "Please choose a valid action.");
    }

}

From source file:com.brianmcmichael.sagu.ui.AmazonDownloadRequest.java

License:Open Source License

@Override
public void actionPerformed(ActionEvent e) {

    if (e.getSource() == jbtDownload) {
        archiveId = jtfDownloadField.getText().trim();
        if ((archiveId.equals(""))) {
            JOptionPane.showMessageDialog(null, "Enter the Archive ID of the file to be requested.", "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else {//w  w  w.  j  a  va2 s. c  o  m
            SwingWorker<Object, Void> downloadWorker = new SwingWorker<Object, Void>() {

                private String archiveId = jtfDownloadField.getText().trim();

                @Override
                protected Void doInBackground() throws Exception {

                    // Create dumb progressbar
                    JFrame downloadFrame = new JFrame("Downloading");
                    {
                        downloadFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                        final JProgressBar dumJProgressBar = new JProgressBar(JProgressBar.HORIZONTAL);
                        dumJProgressBar.setIndeterminate(true);
                        downloadFrame.add(dumJProgressBar, BorderLayout.NORTH);
                        downloadFrame.setSize(300, 60);
                    }
                    centerDefineFrame(downloadFrame, 300, 50);

                    try {
                        String vaultName = dlVault;

                        FileDialog fd = new FileDialog(new Frame(), "Save Archive As...", FileDialog.SAVE);
                        fd.setFile("Save Archive As...");
                        fd.setDirectory(System.getProperty("user.dir"));
                        fd.setLocation(50, 50);
                        fd.setVisible(true);

                        String filePath = "" + fd.getDirectory() + System.getProperty("file.separator")
                                + fd.getFile();

                        File outFile = new File(filePath);

                        if (outFile != null) {
                            downloadFrame.setTitle("Downloading " + outFile.toString());
                            downloadFrame.setVisible(true);

                            final Endpoint endpoint = Endpoint.getByIndex(locationChoice);

                            AmazonSQSClient dlSQS = new AmazonSQSClient(dlCredentials);
                            AmazonSNSClient dlSNS = new AmazonSNSClient(dlCredentials);

                            dlSQS.setEndpoint(endpoint.getSQSEndpoint());
                            dlSNS.setEndpoint(endpoint.getSNSEndpoint());

                            // ArchiveTransferManager atm = new
                            // ArchiveTransferManager(dlClient,
                            // dlCredentials);
                            ArchiveTransferManager atm = new ArchiveTransferManager(dlClient, dlSQS, dlSNS);

                            atm.download("-", vaultName, archiveId, outFile);

                            JOptionPane.showMessageDialog(null, "Sucessfully downloaded " + outFile.toString(),
                                    "Success", JOptionPane.INFORMATION_MESSAGE);
                            downloadFrame.setVisible(false);
                        }
                    } catch (AmazonServiceException k) {
                        JOptionPane.showMessageDialog(null,
                                "The server returned an error. Wait 24 hours after submitting an archive to attempt a download. Also check that correct location of archive has been set on the previous page.",
                                "Error", JOptionPane.ERROR_MESSAGE);
                        System.out.println("" + k);
                        downloadFrame.setVisible(false);
                    } catch (AmazonClientException i) {
                        JOptionPane.showMessageDialog(null,
                                "Client Error. Check that all fields are correct. Archive not downloaded.",
                                "Error", JOptionPane.ERROR_MESSAGE);
                        downloadFrame.setVisible(false);
                    } catch (Exception j) {
                        JOptionPane.showMessageDialog(null, "Archive not found. Unspecified Error.", "Error",
                                JOptionPane.ERROR_MESSAGE);
                        downloadFrame.setVisible(false);
                    }
                    return null;
                }
            };
            downloadWorker.execute();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

            this.setVisible(false);
            dispose();
        }

    } else if (e.getSource() == jbtBack) {
        this.setVisible(false);
        dispose();
    } else {
        JOptionPane.showMessageDialog(this, "Please choose a valid action.");
    }

}

From source file:com.brianmcmichael.SimpleGlacierUploader.AmazonDownloadRequest.java

License:Open Source License

@Override
public void actionPerformed(ActionEvent e) {

    if (e.getSource() == jbtDownload) {
        archiveId = jtfDownloadField.getText().trim();
        if ((archiveId.equals(""))) {
            JOptionPane.showMessageDialog(null, "Enter the Archive ID of the file to be requested.", "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else {/*w  w w.j  a  v a  2  s .c  o  m*/
            SwingWorker downloadWorker = new SwingWorker() {

                private String archiveId = jtfDownloadField.getText().trim();

                @Override
                protected Object doInBackground() throws Exception {

                    // Create dumb progressbar
                    JFrame downloadFrame = new JFrame("Downloading");
                    {
                        downloadFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                        final JProgressBar dumJProgressBar = new JProgressBar(JProgressBar.HORIZONTAL);
                        dumJProgressBar.setIndeterminate(true);
                        downloadFrame.add(dumJProgressBar, BorderLayout.NORTH);
                        downloadFrame.setSize(300, 60);
                    }
                    centerDefineFrame(downloadFrame, 300, 50);

                    String archiveId = jtfDownloadField.getText().trim();
                    try {
                        String vaultName = dlVault;

                        FileDialog fd = new FileDialog(new Frame(), "Save Archive As...", FileDialog.SAVE);
                        fd.setFile("Save Archive As...");
                        fd.setDirectory(System.getProperty("user.dir"));
                        fd.setLocation(50, 50);
                        fd.setVisible(true);

                        String filePath = "" + fd.getDirectory() + System.getProperty("file.separator")
                                + fd.getFile();

                        File outFile = new File(filePath);

                        if (outFile != null) {
                            downloadFrame.setTitle("Downloading " + outFile.toString());
                            downloadFrame.setVisible(true);

                            Endpoints notificationEP = new Endpoints(locationChoice);

                            AmazonSQSClient dlSQS = new AmazonSQSClient(dlCredentials);
                            AmazonSNSClient dlSNS = new AmazonSNSClient(dlCredentials);

                            dlSQS.setEndpoint(notificationEP.sqsEndpoint());
                            dlSNS.setEndpoint(notificationEP.snsEndpoint());

                            // ArchiveTransferManager atm = new
                            // ArchiveTransferManager(dlClient,
                            // dlCredentials);
                            ArchiveTransferManager atm = new ArchiveTransferManager(dlClient, dlSQS, dlSNS);

                            atm.download("-", vaultName, archiveId, outFile);

                            JOptionPane.showMessageDialog(null, "Sucessfully downloaded " + outFile.toString(),
                                    "Success", JOptionPane.INFORMATION_MESSAGE);
                            downloadFrame.setVisible(false);
                        }
                    } catch (AmazonServiceException k) {
                        JOptionPane.showMessageDialog(null,
                                "The server returned an error. Wait 24 hours after submitting an archive to attempt a download. Also check that correct location of archive has been set on the previous page.",
                                "Error", JOptionPane.ERROR_MESSAGE);
                        System.out.println("" + k);
                        downloadFrame.setVisible(false);
                    } catch (AmazonClientException i) {
                        JOptionPane.showMessageDialog(null,
                                "Client Error. Check that all fields are correct. Archive not downloaded.",
                                "Error", JOptionPane.ERROR_MESSAGE);
                        downloadFrame.setVisible(false);
                    } catch (Exception j) {
                        JOptionPane.showMessageDialog(null, "Archive not found. Unspecified Error.", "Error",
                                JOptionPane.ERROR_MESSAGE);
                        downloadFrame.setVisible(false);
                    }
                    return null;
                }
            };
            downloadWorker.execute();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

            this.setVisible(false);
            dispose();
        }

    } else if (e.getSource() == jbtBack) {
        this.setVisible(false);
        dispose();
    } else {
        JOptionPane.showMessageDialog(this, "Please choose a valid action.");
    }

}

From source file:com.clicktravel.infrastructure.runtime.config.aws.AwsConfiguration.java

License:Apache License

@Bean
@Autowired//from   www  .j av a 2s  .c  om
public AmazonSQS amazonSqsClient(final AWSCredentials awsCredentials,
        @Value("${aws.sqs.client.endpoint}") final String endpoint) {
    final AmazonSQS amazonSqsClient = new AmazonSQSClient(awsCredentials);
    logger.info("Setting AWS SQS endpoint to: " + endpoint);
    amazonSqsClient.setEndpoint(endpoint);
    return amazonSqsClient;
}

From source file:com.cloud.Assignment.QueueSender.java

License:Open Source License

public boolean sendToQueue(String queue, String message) throws Exception {
    Properties props = new Properties();
    AWSCredentials credentials = null;//ww  w .j  a v a 2 s .  c  om
    String myQueueUrl = null;
    System.out.println("Queue :" + queue + " Message :" + message);
    try {
        credentials = new ClasspathPropertiesFileCredentialsProvider("AwsCredentials.properties")
                .getCredentials();
        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        props.load(loader.getResourceAsStream("/QueueURL.properties"));
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (/Users/prabhus/.aws/credentials), and is in valid format.", e);
    }
    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usWest2);

    try {
        myQueueUrl = props.getProperty(queue);
        System.out.println("URL :" + myQueueUrl);
        System.out.println("Sending " + message);
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, message));
        isMessagePosted = true;
    } catch (AmazonServiceException ase) {

        throw new AmazonServiceException("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");

    } catch (AmazonClientException ace) {
        System.out.println("Error Message: " + ace.getMessage());
        throw new AmazonClientException("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.");

    }
    return isMessagePosted;
}

From source file:com.comcast.cmb.common.controller.AdminServletBase.java

License:Apache License

/**
  * Method to set the aws credentials for sqs and sns handlers
  * @param userId/*  w w w  .  j  av  a  2 s  . c o m*/
  * @throws ServletException
  */
protected void connect(HttpServletRequest request) throws ServletException {

    String userId = request.getParameter("userId");

    IUserPersistence userHandler = PersistenceFactory.getUserPersistence();

    try {
        user = userHandler.getUserById(userId);
    } catch (PersistenceException ex) {
        throw new ServletException(ex);
    }

    if (user == null) {
        throw new ServletException("User " + userId + " does not exist");
    }

    if (!user.getUserName().equals(getAuthenticatedUser(request).getUserName())
            && !getAuthenticatedUser(request).getIsAdmin()) {
        throw new ServletException("Only admin may impersonate other users");
    }

    awsCredentials = new BasicAWSCredentials(user.getAccessKey(), user.getAccessSecret());

    sqs = new AmazonSQSClient(awsCredentials);
    sqs.setEndpoint(CMBProperties.getInstance().getCQSServiceUrl());

    sns = new AmazonSNSClient(awsCredentials);
    sns.setEndpoint(CMBProperties.getInstance().getCNSServiceUrl());
}

From source file:com.comcast.cmb.test.tools.CMBTutorial.java

License:Apache License

public static void main(String[] args) {

    try {/*from   www  .j  a  va 2 s .  c  o  m*/

        Util.initLog4jTest();

        //TODO: set user id and credentials for two distinct users

        // user "cqs_test_1"

        //BasicAWSCredentials user1Credentials = new BasicAWSCredentials("<access_key>", "<secret_key>");

        BasicAWSCredentials user1Credentials = new BasicAWSCredentials("Z2DVBFRNZ2C2SSXDWS5F",
                "bH2UQiJkpctBaE3eaDob19fj5J9Q1FVafrZantBp");

        // user "cqs_test_2"

        //String user2Id = "<user_id>";
        String user2Id = "389653920093";

        //BasicAWSCredentials user2Credentials = new BasicAWSCredentials("<access_key>", "<secret_key>");

        BasicAWSCredentials user2Credentials = new BasicAWSCredentials("QL8Q1VOBCSJC5FZ2DMIU",
                "n6a82gyJZ04Z+Xqp7OgfqPtbbKqVc3UbuOTNrF+7");

        // service urls

        //TODO: add service URLs

        //String cqsServerUrl = "http://<host>:<port>";
        //String cnsServerUrl = "http://<host>:<port>";

        String cqsServerUrl = "http://localhost:6059";
        String cnsServerUrl = "http://localhost:6061";

        // initialize service

        AmazonSQSClient sqs = new AmazonSQSClient(user1Credentials);
        sqs.setEndpoint(cqsServerUrl);

        AmazonSNSClient sns = new AmazonSNSClient(user2Credentials);
        sns.setEndpoint(cnsServerUrl);

        // create queue

        Random randomGenerator = new Random();

        String queueName = QUEUE_PREFIX + randomGenerator.nextLong();

        HashMap<String, String> attributeParams = new HashMap<String, String>();
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
        createQueueRequest.setAttributes(attributeParams);
        String queueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

        AddPermissionRequest addPermissionRequest = new AddPermissionRequest();
        addPermissionRequest.setQueueUrl(queueUrl);
        addPermissionRequest.setActions(Arrays.asList("SendMessage"));
        addPermissionRequest.setLabel(UUID.randomUUID().toString());
        addPermissionRequest.setAWSAccountIds(Arrays.asList(user2Id));
        sqs.addPermission(addPermissionRequest);

        // create topic

        String topicName = "TSTT" + randomGenerator.nextLong();

        CreateTopicRequest createTopicRequest = new CreateTopicRequest(topicName);
        CreateTopicResult createTopicResult = sns.createTopic(createTopicRequest);
        String topicArn = createTopicResult.getTopicArn();

        // subscribe and confirm cqs endpoint

        SubscribeRequest subscribeRequest = new SubscribeRequest();
        String queueArn = getArnForQueueUrl(queueUrl);
        subscribeRequest.setEndpoint(queueArn);
        subscribeRequest.setProtocol("cqs");
        subscribeRequest.setTopicArn(topicArn);
        SubscribeResult subscribeResult = sns.subscribe(subscribeRequest);
        String subscriptionArn = subscribeResult.getSubscriptionArn();

        if (subscriptionArn.equals("pending confirmation")) {

            Thread.sleep(500);

            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
            receiveMessageRequest.setQueueUrl(queueUrl);
            receiveMessageRequest.setMaxNumberOfMessages(1);
            ReceiveMessageResult receiveMessageResult = sqs.receiveMessage(receiveMessageRequest);

            List<Message> messages = receiveMessageResult.getMessages();

            if (messages != null && messages.size() == 1) {

                JSONObject o = new JSONObject(messages.get(0).getBody());

                if (!o.has("SubscribeURL")) {
                    throw new Exception("message is not a confirmation messsage");
                }

                String subscriptionUrl = o.getString("SubscribeURL");
                httpGet(subscriptionUrl);

                DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
                deleteMessageRequest.setReceiptHandle(messages.get(0).getReceiptHandle());
                deleteMessageRequest.setQueueUrl(queueUrl);
                sqs.deleteMessage(deleteMessageRequest);

            } else {
                throw new Exception("no confirmation message found");
            }
        }

        // publish and receive message

        PublishRequest publishRequest = new PublishRequest();
        String messageText = "quamvis sint sub aqua, sub aqua maledicere temptant";
        publishRequest.setMessage(messageText);
        publishRequest.setSubject("unit test message");
        publishRequest.setTopicArn(topicArn);
        sns.publish(publishRequest);

        Thread.sleep(500);

        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
        receiveMessageRequest.setQueueUrl(queueUrl);
        receiveMessageRequest.setMaxNumberOfMessages(1);
        ReceiveMessageResult receiveMessageResult = sqs.receiveMessage(receiveMessageRequest);

        List<Message> messages = receiveMessageResult.getMessages();

        if (messages != null && messages.size() == 1) {

            String messageBody = messages.get(0).getBody();

            if (!messageBody.contains(messageText)) {
                throw new Exception("message text not found");
            }

            DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
            deleteMessageRequest.setReceiptHandle(messages.get(0).getReceiptHandle());
            deleteMessageRequest.setQueueUrl(queueUrl);
            sqs.deleteMessage(deleteMessageRequest);

        } else {
            throw new Exception("no messages found");
        }

        // subscribe and confirm http endpoint

        String id = randomGenerator.nextLong() + "";
        String endPointUrl = CMBTestingConstants.HTTP_ENDPOINT_BASE_URL + "recv/" + id;
        String lastMessageUrl = CMBTestingConstants.HTTP_ENDPOINT_BASE_URL + "info/" + id + "?showLast=true";

        subscribeRequest = new SubscribeRequest();
        subscribeRequest.setEndpoint(endPointUrl);
        subscribeRequest.setProtocol("http");
        subscribeRequest.setTopicArn(topicArn);
        subscribeResult = sns.subscribe(subscribeRequest);
        subscriptionArn = subscribeResult.getSubscriptionArn();

        if (subscriptionArn.equals("pending confirmation")) {

            Thread.sleep(500);

            String response = httpGet(lastMessageUrl);

            JSONObject o = new JSONObject(response);

            if (!o.has("SubscribeURL")) {
                throw new Exception("message is not a confirmation messsage");
            }

            String subscriptionUrl = o.getString("SubscribeURL");

            response = httpGet(subscriptionUrl);
        }

        // publish and receive message

        publishRequest = new PublishRequest();
        publishRequest.setMessage(messageText);
        publishRequest.setSubject("unit test message");
        publishRequest.setTopicArn(topicArn);
        sns.publish(publishRequest);

        Thread.sleep(500);

        String response = httpGet(lastMessageUrl);

        if (response != null && response.length() > 0) {

            if (!response.contains(messageText)) {
                throw new Exception("message text not found");
            }

        } else {
            throw new Exception("no messages found");
        }

        // delete queue and topic

        DeleteTopicRequest deleteTopicRequest = new DeleteTopicRequest(topicArn);
        sns.deleteTopic(deleteTopicRequest);

        sqs.deleteQueue(new DeleteQueueRequest(queueUrl));

        System.out.println("OK");

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.comcast.cns.controller.CNSPublishAction.java

License:Apache License

/**
 * The method simply gets the information from the user and request to call publish the message passed in
 * the "Message" field in the request parameters, and publish them to all endpoints subscribed to the topic
 * designated by the "TopicArn" field in the request, then take the response and generate an XML response 
 * and put it in the parameter response//from  w ww  .  j  av a  2 s .  c  om
 * @param user the user for whom we are listing the subscription
 * @param asyncContext
 */
@Override
public boolean doAction(User user, AsyncContext asyncContext) throws Exception {

    CQSHttpServletRequest request = (CQSHttpServletRequest) asyncContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();

    if (cnsInternalUser == null) {

        IUserPersistence userHandler = PersistenceFactory.getUserPersistence();
        cnsInternalUser = userHandler.getUserByName(CMBProperties.getInstance().getCNSUserName());

        if (cnsInternalUser == null) {
            cnsInternalUser = userHandler.createDefaultUser();
        }
    }

    if (awsCredentials == null) {
        awsCredentials = new BasicAWSCredentials(cnsInternalUser.getAccessKey(),
                cnsInternalUser.getAccessSecret());
    }

    if (sqs == null) {
        sqs = new AmazonSQSClient(awsCredentials);
        sqs.setEndpoint(CMBProperties.getInstance().getCQSServiceUrl());
    }

    String userId = user.getUserId();
    String message = request.getParameter("Message");
    String topicArn = request.getParameter("TopicArn");

    String messageStructure = null;
    String subject = null;

    CNSMessage cnsMessage = new CNSMessage();
    cnsMessage.generateMessageId();
    cnsMessage.setTimestamp(new Date());
    cnsMessage.setMessage(message);

    //TODO: optional shortcut

    if (request.getParameter("MessageStructure") != null) {

        messageStructure = request.getParameter("MessageStructure");

        if (!messageStructure.equals("json")) {
            logger.error(
                    "event=cns_publish error_code=InvalidParameters message=" + message + " message_structure="
                            + messageStructure + " topic_arn=" + topicArn + " user_id=" + userId);
            throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,
                    "Invalid parameter: Invalid Message Structure parameter: " + messageStructure);
        }

        cnsMessage.setMessageStructure(CNSMessage.CNSMessageStructure.valueOf(messageStructure));
    }

    if (request.getParameter("Subject") != null) {
        subject = request.getParameter("Subject");
        cnsMessage.setSubject(subject);
    }

    if ((userId == null) || (message == null)) {
        logger.error("event=cns_publish error_code=InvalidParameters message=" + message + " topic_arn="
                + topicArn + " user_id=" + userId);
        throw new CMBException(CNSErrorCodes.CNS_ValidationError,
                "1 validation error detected: Value null at 'message' failed to satisfy constraint: Member must not be null");
    }

    if ((topicArn == null) || !Util.isValidTopicArn(topicArn)) {
        logger.error("event=cns_publish error_code=InvalidParameters message=" + message + " topic_arn="
                + topicArn + " user_id=" + userId);
        throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "TopicArn");
    }

    CNSTopic topic = CNSCache.getTopic(topicArn);

    if (topic == null) {
        logger.error("event=cns_publish error_code=NotFound message=" + message + " topic_arn=" + topicArn
                + " user_id=" + userId);
        throw new CMBException(CNSErrorCodes.CNS_NotFound, "Resource not found.");
    }

    cnsMessage.setUserId(topic.getUserId());
    cnsMessage.setTopicArn(topicArn);
    cnsMessage.setMessageType(CNSMessageType.Notification);

    cnsMessage.checkIsValid();

    CNSTopicAttributes topicAttributes = CNSCache.getTopicAttributes(topicArn);
    List<String> receiptHandles = new ArrayList<String>();

    boolean success = true;

    if (topicAttributes != null && topicAttributes.getSubscriptionsConfirmed() == 0) {

        // optimization: don't do anything if there are no confirmed subscribers

        logger.warn("event=no_confirmed_subscribers action=publish topic_arn=" + topicArn);

    } else if (CMBProperties.getInstance().isCNSBypassPublishJobQueueForSmallTopics() && topicAttributes != null
            && topicAttributes.getSubscriptionsConfirmed() <= CMBProperties.getInstance()
                    .getCNSMaxSubscriptionsPerEndpointPublishJob()) {

        // optimization: if there's only one chunk due to few subscribers, write directly into endpoint publish queue bypassing the publish job queue

        logger.debug("event=using_job_queue_overpass");

        List<CNSEndpointPublishJob.CNSEndpointSubscriptionInfo> subscriptions = CNSEndpointPublisherJobProducer
                .getSubscriptionsForTopic(topicArn);

        if (subscriptions != null && subscriptions.size() > 0) {

            List<CNSEndpointPublishJob> epPublishJobs = CNSEndpointPublisherJobProducer
                    .createEndpointPublishJobs(cnsMessage, subscriptions);

            if (epPublishJobs.size() != 1) {
                logger.warn("event=unexpected_number_of_endpoint_publish_jobs count=" + epPublishJobs.size());
            }

            for (CNSEndpointPublishJob epPublishJob : epPublishJobs) {
                String handle = sendMessageOnRandomShardAndCreateQueueIfAbsent(CNS_ENDPOINT_QUEUE_NAME_PREFIX,
                        CMBProperties.getInstance().getCNSNumEndpointPublishJobQueues(),
                        epPublishJob.serialize(), cnsInternalUser.getUserId());
                if (handle != null && !handle.equals("")) {
                    receiptHandles.add(handle);
                } else {
                    success = false;
                }
            }
        }

    } else {

        // otherwise pick publish job queue

        logger.debug("event=going_through_job_queue_town_center");

        String handle = sendMessageOnRandomShardAndCreateQueueIfAbsent(CNS_PUBLISH_QUEUE_NAME_PREFIX,
                CMBProperties.getInstance().getCNSNumPublishJobQueues(), cnsMessage.serialize(),
                cnsInternalUser.getUserId());
        if (handle != null && !handle.equals("")) {
            receiptHandles.add(handle);
        } else {
            success = false;
        }
    }

    if (!success) {
        throw new CMBException(CMBErrorCodes.InternalError, "Failed to place message on internal cns queue");
    }

    request.setReceiptHandles(receiptHandles);

    String out = CNSSubscriptionPopulator.getPublishResponse(receiptHandles);
    writeResponse(out, response);

    return true;
}

From source file:com.comcast.cns.io.CQSEndpointPublisher.java

License:Apache License

@Override
public void send() throws Exception {

    if ((message == null) || (endpoint == null)) {
        throw new Exception("Message and Endpoint must both be set");
    }//from w  w w  . j  a  v a 2  s. co m

    String absoluteQueueUrl;

    if (com.comcast.cqs.util.Util.isValidQueueUrl(endpoint)) {
        absoluteQueueUrl = endpoint;
    } else {
        absoluteQueueUrl = com.comcast.cqs.util.Util.getAbsoluteQueueUrlForArn(endpoint);
    }

    try {

        String msg = null;

        if (message.getMessageStructure() == CNSMessageStructure.json) {
            msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.cqs);
        } else {
            msg = message.getMessage();
        }

        if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) {
            msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.cqs);
        }

        if (msg == null) {
            logger.warn("event=message_is_null endpoint=" + endpoint);
            return;
        }

        if (CMBProperties.getInstance().useInlineApiCalls()
                && CMBProperties.getInstance().getCQSServiceEnabled()) {
            CQSAPI.sendMessage(user.getUserId(), Util.getRelativeForAbsoluteQueueUrl(absoluteQueueUrl), msg,
                    null);
        } else {
            awsCredentials = new BasicAWSCredentials(user.getAccessKey(), user.getAccessSecret());
            sqs = new AmazonSQSClient(awsCredentials);
            sqs.setEndpoint(CMBProperties.getInstance().getCQSServiceUrl());
            sqs.sendMessage(new SendMessageRequest(absoluteQueueUrl, msg));
        }

        if (CMBProperties.getInstance().getMaxMessagePayloadLogLength() > 0) {
            if (msg.length() > CMBProperties.getInstance().getMaxMessagePayloadLogLength()) {

                logger.debug("event=delivering_cqs_message endpoint=" + endpoint + "\" message=\""
                        + msg.substring(0, CMBProperties.getInstance().getMaxMessagePayloadLogLength() - 1));

            } else {
                logger.debug("event=delivering_cqs_message endpoint=" + endpoint + "\" message=\"" + msg);
            }
        } else {
            logger.debug("event=delivering_cqs_message endpoint=" + endpoint);
        }

    } catch (Exception ex) {
        logger.warn("event=send_cqs_message endpoint=" + endpoint + "\" message=\"" + message, ex);
        throw new CMBException(CNSErrorCodes.InternalError, "internal service error");
    }

    logger.debug("event=send_cqs_message endpoint=" + endpoint + " message=\"" + message + "\"");
}

From source file:com.comcast.cns.io.SQSEndpointPublisher.java

License:Apache License

@Override
public void send() throws Exception {

    if ((message == null) || (endpoint == null)) {
        throw new Exception("Message and Endpoint must both be set");
    }/*  w ww  .  ja v  a 2 s.c o  m*/

    awsCredentials = new BasicAWSCredentials(CMBProperties.getInstance().getAwsAccessKey(),
            CMBProperties.getInstance().getAwsAccessSecret());
    sqs = new AmazonSQSClient(awsCredentials);

    String url;

    if (com.comcast.cqs.util.Util.isValidQueueUrl(endpoint)) {
        url = endpoint;
    } else {
        url = com.comcast.cqs.util.Util.getAbsoluteAWSQueueUrlForArn(endpoint);
    }

    try {

        String msg = null;

        if (message.getMessageStructure() == CNSMessageStructure.json) {
            msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.cqs);
        } else {
            msg = message.getMessage();
        }

        if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) {
            msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.cqs);
        }

        logger.debug("event=send_sqs_message endpoint=" + endpoint + "\" message=\"" + msg);

        sqs.sendMessage(new SendMessageRequest(url, msg));

    } catch (Exception ex) {
        logger.warn("event=send_sqs_message endpoint=" + endpoint + "\" message=\"" + message, ex);
        throw new CMBException(CNSErrorCodes.InternalError, "internal service error");
    }

    logger.debug("event=send_sqs_message endpoint=" + endpoint + " message=\"" + message + "\"");
}