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.twitter.services.SQS.java

License:Open Source License

private static void createSQS() {
    AWSCredentials credentials = null;//from   w  w w. j  a va2  s . c  o  m
    try {
        credentials = new BasicAWSCredentials("", "");
    } 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);
    }

    sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);
}

From source file:com.zhang.aws.sqs.SimpleQueueServiceSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    AWSCredentials credentials = null;//from   w w w.j  a v a  2 s .c  om
    try {
        credentials = CredentialsUtil.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.AP_SOUTHEAST_1);
    sqs.setRegion(usWest2);

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon SQS");
    System.out.println("===========================================\n");

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called MyQueue.\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
        String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

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

        // Send a message
        System.out.println("Sending a message to MyQueue.\n");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        for (Message message : messages) {
            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());
            for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }
        System.out.println();

        // Delete a message
        System.out.println("Deleting a message.\n");
        String messageRecieptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

        // Delete a queue
        System.out.println("Deleting the test queue.\n");
        sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.zotoh.cloudapi.aws.AWSCloud.java

License:Open Source License

private void createAWSClients(Properties ps) {
    AWSCredentials cc = new BasicAWSCredentials(ps.getProperty(P_ID), ps.getProperty(P_PWD));
    AmazonWebServiceClient c;//from w w  w . j a  v a  2  s  . co  m

    _WEB.put("ec2", new AmazonEC2Client(cc));

    _WEB.put("s3", new AmazonS3Client(cc));

    // SIMPLE-DB
    c = new AmazonSimpleDBClient(cc);
    _WEB.put("sdb", c);
    c.setEndpoint("sdb.amazonaws.com");

    // LOAD BALANCER
    c = new AmazonElasticLoadBalancingClient(cc);
    _WEB.put("elb", c);
    c.setEndpoint("elasticloadbalancing.amazonaws.com");

    _WEB.put("cloudwatch", new AmazonCloudWatchClient(cc));
    _WEB.put("autoscale", new AmazonAutoScalingClient(cc));

    // NOTIFICATION
    c = new AmazonSNSClient(cc);
    _WEB.put("sns", c);
    c.setEndpoint("sns.us-east-1.amazonaws.com");

    _WEB.put("sqs", new AmazonSQSClient(cc));
    _WEB.put("rds", new AmazonRDSClient(cc));
    _WEB.put("s3s", new AmazonS3EncryptionClient(cc, new EncryptionMaterials((KeyPair) null)));

}

From source file:de.kopis.glacier.commands.AbstractCommand.java

License:Open Source License

public AbstractCommand(final URL endpoint, final File credentials) throws IOException {
    this.log = LogFactory.getLog(this.getClass());

    if (credentials != null) {
        this.credentials = new PropertiesCredentials(credentials);
        this.client = new AmazonGlacierClient(this.credentials);
        this.sqs = new AmazonSQSClient(this.credentials);
        this.sns = new AmazonSNSClient(this.credentials);
    }/*from ww w .  j  ava2s. c om*/

    if (endpoint != null) {
        this.setEndpoint(endpoint);
    }
}

From source file:getting_started.SimpleQueueServiceSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*from ww w .j ava  2s  . com*/
     * 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 PropertiesCredentials(
            SimpleQueueServiceSample.class.getResourceAsStream("AwsCredentials.properties")));

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon SQS");
    System.out.println("===========================================\n");

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called MyQueue.\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
        String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

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

        // Send a message
        System.out.println("Sending a message to MyQueue.\n");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        for (Message message : messages) {
            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());
            for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }
        System.out.println();

        // Delete a message
        System.out.println("Deleting a message.\n");
        String messageRecieptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

        // Delete a queue
        System.out.println("Deleting the test queue.\n");
        sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:hu.cloud.edu.SimpleQueueServiceSample.java

License:Open Source License

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

    /*//  w w  w.ja  v a2 s  . com
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (C:\\Users\\Isaac\\.aws\\credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (C:\\Users\\Isaac\\.aws\\credentials), and is in valid format.", e);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon SQS");
    System.out.println("===========================================\n");

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called MyQueue.\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
        String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

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

        // Send a message
        System.out.println("Sending a message to MyQueue.\n");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        for (Message message : messages) {
            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());
            for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }
        System.out.println();

        // Delete a message
        System.out.println("Deleting a message.\n");
        String messageRecieptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

        // Delete a queue
        System.out.println("Deleting the test queue.\n");
        sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:io.konig.etl.aws.CamelEtlRouteController.java

License:Apache License

@Bean
AmazonSQSClient sqsClient() {
    AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
    return new AmazonSQSClient(credentials);
}

From source file:it.polimi.modaclouds.cpimlibrary.msgqueuemng.AmazonMessageQueueFactory.java

License:Apache License

public AmazonMessageQueueFactory(CloudMetadata metadata) {
    AWSCredentials credentials = null;/*from  w  w  w . j a  v a  2 s . c  om*/
    try {
        credentials = new PropertiesCredentials(
                getClass().getClassLoader().getResourceAsStream("AwsCredentials.properties"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    this.sqs = new AmazonSQSClient(credentials);
    this.info = metadata.getQueueMedatada();
}

From source file:it.polimi.modaclouds.cpimlibrary.taskqueuemng.AmazonInternalWorker.java

License:Apache License

public void run() {
    //queue = (AmazonTaskQueue) MF.getFactory().getTaskQueueFactory().getQueue(queueName);

    AWSCredentials credentials = null;/*from   w  w w.j  a  v  a 2s.  co  m*/
    try {
        credentials = new PropertiesCredentials(
                getClass().getClassLoader().getResourceAsStream("AwsCredentials.properties"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    this.sqs = new AmazonSQSClient(credentials);
    queue = new AmazonTaskQueue(queueName, sqs);

    AmazonTaskQueueMessage msg = null;

    while (true) {
        System.out.println("Iteration..");
        msg = queue.getMessage();
        if (msg != null) {
            System.out.println("Message found");
            final AmazonTaskQueueMessage aqmsg = msg;
            new Thread() {

                ///////////////////////////////////////THREAD ////////////////////////////
                public void run() {
                    System.out.println("Run");
                    handleTask(aqmsg);
                    System.out.println("Finish");
                    //this.interrupt();
                }

                private void handleTask(AmazonTaskQueueMessage msg) {
                    info = parserMessage(msg.getMessageText());
                    String parameters = "";
                    boolean firstIt = true;
                    for (String key : info.getParameters().keySet()) {
                        if (firstIt) {
                            parameters = parameters + "?";
                            firstIt = false;
                        } else {
                            parameters = parameters + "&";
                        }
                        parameters = parameters + key + "=" + info.getParameters().get(key);
                    }

                    System.out.println("Starting servlet.");
                    //creo l'url
                    URI host = URI.create("http://localhost:8080/");
                    String url = "http://" + host.getHost() + ":" + host.getPort() + host.getPath()
                            + info.getServletUri().getPath() + parameters;
                    System.out.println(url);

                    URL iurl = null;
                    HttpURLConnection uc = null;
                    //DataOutputStream  out = null;
                    BufferedReader rd = null;

                    try {
                        iurl = new URL(url);
                        uc = (HttpURLConnection) iurl.openConnection();
                        uc.setDoOutput(true);

                        uc.setRequestMethod(info.getMethod().toUpperCase());
                        //uc.addRequestProperty("Content-Length", file_length.toString());

                        //out = new DataOutputStream(uc.getOutputStream());
                        //out.write(file_content, 0, file_length);
                        //out.flush();
                        //out.close();

                        //uc.setReadTimeout(file_length/50);
                        //System.out.println("Set timeout: " + uc.getReadTimeout() + "ms.");
                        InputStream is = uc.getInputStream();

                        rd = new BufferedReader(new InputStreamReader(is));

                        String line;
                        while ((line = rd.readLine()) != null) {
                            System.out.println("Response: " + line);
                        }
                        rd.close();
                        System.out.println("Response code: " + uc.getResponseCode());
                        if (uc.getResponseCode() == 500) {
                            ;
                            ;
                        }

                    } catch (RuntimeException e) {
                        // TODO Auto-generated catch block
                        System.out.println("RuntimeException error!!");
                        System.out.println("------");
                        e.printStackTrace();
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        System.out.println("MalformedURLException error!!");
                        System.out.println("------");
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        System.out.println("IOException error!!");
                        System.out.println("------");
                        e.printStackTrace();
                    }
                    System.out.println("End of servlet.");

                    /*
                       try {
                            
                       StringBuffer sb = new StringBuffer();
                       sb.append(info.getMethod() + " " + info.getHostUri()
                             + info.getServletUri() + parameters + " HTTP/1.1\r\n");
                       sb.append(HttpHeader.HOST + ": " + info.getHostUri().getHost()
                             + ":" + info.getHostUri().getPort() + "\r\n");
                       sb.append(HttpHeader.CONNECTION + ": "
                             + HttpHeader.CONNECTION_CLOSE + "\r\n");
                       sb.append("\r\n");
                       String request = sb.toString();
                            
                       System.out
                             .println("********************REQUEST !!!!!************************");
                       System.out.println(request);
                       System.out
                             .println("********************END REQUEST !!!!!!!!************************");
                       SocketFactory socketFactory = SocketFactory.getDefault();
                       InetAddress ip = InetAddress.getByName(info.getHostUri().getHost());
                       Socket socket = socketFactory.createSocket(ip, info.getHostUri()
                             .getPort());
                       OutputStreamWriter osw = new OutputStreamWriter(
                             socket.getOutputStream());
                       int requestLength = request.length();
                       BufferedWriter bw = new BufferedWriter(osw, requestLength);
                       bw.write(request);
                       bw.flush();
                            
                       InputStreamReader isr = new InputStreamReader(
                             socket.getInputStream());
                       BufferedReader br = new BufferedReader(isr, 8192);
                       @SuppressWarnings("unused")
                       HttpResult result = buildResult(HttpMethod.POST, br);
                            
                       br.close();
                       isr.close();
                       socket.close();
                       */

                    int i = 0;
                    Boolean deleted = queue.deleteMessage(msg);
                    while (!deleted && i < NUM_ATTEMPT_DELETE) {

                        i++;
                        deleted = queue.deleteMessage(msg);

                    }
                    if (!deleted)
                        try {
                            throw new CloudTaskQueueException(
                                    "Deletion of Message " + msg.getMessageId() + " failed!!");
                        } catch (CloudTaskQueueException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    else
                        System.out.println("Message " + msg.getMessageId() + "Deleted at attempt number " + i);

                    /*
                    } catch (Exception e) {
                    new Diagnostics("Exception during queue management:"
                       + e.getMessage()).save();
                    }
                    */

                }

                private CloudTask parserMessage(String messageText) {
                    CloudTask t = new CloudTask();
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db;
                    try {
                        db = dbf.newDocumentBuilder();

                        InputSource is = new InputSource();
                        is.setCharacterStream(new StringReader(messageText));

                        Document doc = db.parse(is);
                        Element root = doc.getDocumentElement();

                        //String uri = getTextValue(root, "URL");
                        //t.setHostUri(uri);

                        String uriS = getTextValue(root, "SERVLET");
                        t.setServletUri(uriS);

                        String method = getTextValue(root, "METHOD");
                        t.setMethod(method);

                        NodeList par = root.getElementsByTagName("PARAMETER");
                        for (int i = 0; i < par.getLength(); i++) {
                            Element elPar = (Element) par.item(i);

                            String key = getTextValue(elPar, "KEY");

                            String value = getTextValue(elPar, "VALUE");

                            t.setParameters(key, value);
                        }

                    } catch (ParserConfigurationException e) {
                        e.printStackTrace();
                    } catch (SAXException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    return t;
                }

                private String getTextValue(Element ele, String tagName) {
                    String textVal = null;
                    NodeList nl = ele.getElementsByTagName(tagName);
                    if (nl != null && nl.getLength() > 0) {
                        Element el = (Element) nl.item(0);
                        textVal = el.getFirstChild().getNodeValue();
                    }

                    return textVal;
                }

                ///////////////////////////// THREAD ///////////////////////////////////
            }.start();
        }
        System.out.println("Sleeping..");
        try {
            Thread.sleep(queueInfo.getRate());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:it.polimi.modaclouds.cpimlibrary.taskqueuemng.AmazonTaskQueueFactory.java

License:Apache License

public AmazonTaskQueueFactory(CloudMetadata metadata) {
    AWSCredentials credentials = null;//from www  .j  a  v  a  2 s  . c o m
    try {
        credentials = new PropertiesCredentials(
                getClass().getClassLoader().getResourceAsStream("AwsCredentials.properties"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    this.sqs = new AmazonSQSClient(credentials);
    this.info = metadata.getQueueMedatada();
}