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:Server.aws.yulei.SQSOperation.java

License:Open Source License

public static void receiveSQS() {
    AWSCredentials credentials = null;// w ww  . j a v a2 s.c  o m
    try {
        credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (/Users/daniel/.aws/credentials), and is in valid format.", e);
    }

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

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

    try {

        // Create a queue
        System.out.println("Creating a new SQS queue called MyQueue.\n");
        //CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
        String myQueueUrl = "https://sqs.us-east-1.amazonaws.com/659322195879/MyQueue";

        // List queues

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

            // load text
            String text = content;

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

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

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

}

From source file:servlet.FileUploadServlet.java

public void sqs(String msg) throws Exception {
    AWSCredentials awsCreds = new PropertiesCredentials(
            new File("/Users/paulamontojo/Desktop/AwsCredentials.properties"));

    AmazonSQS sqs = new AmazonSQSClient(awsCreds);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);/*  www .ja  va2 s. c  o  m*/

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

    try {

        String myQueueUrl = "https://sqs.us-west-2.amazonaws.com/711690152696/MyQueue";

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

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

    } 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:Servlet.WorkPool.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials
 * consisting of the AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints, are performed
 * automatically. Client parameters, such as proxies, can be specified in an
 * optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 *///from w ww  .j  a  va2  s. c  o m
private static void init() throws Exception {

    /*
     * The ProfileCredentialsProvider will return your [default] credential
     * profile by reading from the credentials file located at
     * (/home/zeweijiang/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("jiangzewei").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 (/home/zeweijiang/.aws/credentials), and is in valid format.", e);
    }
    sqs = new AmazonSQSClient(credentials);
    sns = new AmazonSNSClient(credentials);
}

From source file:shapeways.api.robocreator.BaseRoboCreator.java

License:Apache License

/**
 * Initialize the servlet. Sets up the base directory properties for finding
 * stuff later on.//w  w w .  j  av  a  2 s .c  om
 */
public void init() throws ServletException {
    // DirectorServlet overrides all but this method.  If your making changes here
    // you might need to change that class as well

    ServletConfig config = getServletConfig();
    ServletContext ctx = config.getServletContext();

    serviceQueue = getInitParameter("ServiceQueue");
    if (serviceQueue == null) {
        System.out.println("ServiceQueue is null, add entry to web.xml");
    }

    shapewaysHost = getInitParameter("ShapewaysHost");

    System.out.println("ShapewaysHost: " + shapewaysHost);

    if (shapewaysHost == null) {
        shapewaysHost = ShapewaysAPI.getShapewaysHost();
    }

    String instanceType = getInstanceMetadata("instance-type", "localhost");

    // 0 = number of processors.  > 0 specific number.  Default is 1
    String num_threads_st = getInitParameter("NumThreads");
    Gson gson = new Gson();
    Map<String, Number> threadsMap = new HashMap<String, Number>();
    try {
        threadsMap = gson.fromJson(num_threads_st, Map.class);
    } catch (Exception e) {
        System.out.println(
                "Cannot parse threads: " + serviceQueue + ".  Should be map of instanceType to numThreads");
        System.out.println("numThreads: " + num_threads_st);
        e.printStackTrace();
    }

    threads = threadsMap.get(instanceType).intValue();

    if (threads == 0) {
        threads = Runtime.getRuntime().availableProcessors();
        ;
    }

    threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(threads);

    consumerKey = getInitParameter("ShapewaysConsumerKey");
    consumerSecret = getInitParameter("ShapewaysConsumerSecret");
    accessToken = getInitParameter("ShapewaysAccessToken");
    accessSecret = getInitParameter("ShapewaysAccessSecret");

    String proxyType = getInitParameter("ProxyType");
    String proxyHost = getInitParameter("ProxyHost");
    String proxyPort = getInitParameter("ProxyPort");

    if (proxyHost != null) {
        // TODO: think about selectors as this is per JVM
        System.out.println("Configuring proxy: " + proxyHost + ":" + proxyPort);

        Properties systemSettings = System.getProperties();

        systemSettings.put("proxySet", "true");
        if (proxyType.equalsIgnoreCase("SOCKS")) {
            systemSettings.put("socksProxyHost", proxyHost);
            systemSettings.put("socksProxyPort", proxyPort);
        } else {
            systemSettings.put("http.proxyHost", proxyHost);
            systemSettings.put("http.proxyPort", proxyPort);
        }
    }

    String awsAccessKey = getInitParameter("AWSAccessKey");
    String awsAccessSecret = getInitParameter("AWSAccessSecret");
    String awsRegion = getInitParameter("AWSRegion");
    String st = getInitParameter("AWSSQSVisibilityTimeout");
    if (st != null) {
        visibilityTimeout = Integer.parseInt(st);
    }

    st = getInitParameter("AWSSQSMessagePollFrequency");

    if (st != null) {
        pollFrequency = Integer.parseInt(st);
    } else {
        pollFrequency = DEFAULT_POLL_FREQUENCY;
    }

    // TODO: Not certain we want to do these here as it delays deploy and might stop all deploys if AWS is down.
    // Switch to a threaded runnable or maybe just add the job to the threadPool we have.
    sqs = new AmazonSQSClient(new BasicAWSCredentials(awsAccessKey, awsAccessSecret));

    Region region = RegionUtils.getRegion(awsRegion);
    sqs.setRegion(region);

    threadPool.submit(new SQSCreateQueueTask(sqs, QUEUE_PREPEND + serviceQueue, visibilityTimeout, this));
}

From source file:shapeways.api.robocreator.RoboCreatorWeb.java

License:Apache License

/**
 * Initialize the servlet. Sets up the base directory properties for finding
 * stuff later on./*from   w w w  .  ja v  a2 s  .c om*/
 */
public void init() throws ServletException {

    if (DEBUG) {
        System.out.println("Starting RoboCreatorWeb");
    }

    ServletConfig config = getServletConfig();
    ServletContext ctx = config.getServletContext();

    kernels = getInitParameter("Kernels");
    if (kernels == null) {
        System.out.println("ServiceQueue is null, add entry to web.xml");
    }

    System.out.println("Handling Kernels: " + kernels);
    instanceType = getInstanceMetadata("instance-type", "localhost");

    // 0 = number of processors.  > 0 specific number.  Default is 1
    String num_threads_st = getInitParameter("NumThreads");
    Gson gson = new Gson();
    Map<String, Number> threadsMap = new HashMap<String, Number>();
    try {
        threadsMap = gson.fromJson(num_threads_st, Map.class);
    } catch (Exception e) {
        System.out.println(
                "Cannot parse threads in RoboCreatorWeb.  Should be map of instanceType to numThreads");
        System.out.println("numThreads: " + num_threads_st);
        e.printStackTrace();
    }

    int threads = threadsMap.get(instanceType).intValue();

    if (threads == 0) {
        int cores = Runtime.getRuntime().availableProcessors();
        threads = cores;
    }

    threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(threads);

    System.out.println("ThreadPool: " + threadPool);
    awsAccessKey = getInitParameter("AWSAccessKey");
    awsAccessSecret = getInitParameter("AWSAccessSecret");
    awsRegion = getInitParameter("AWSRegion");
    String st = getInitParameter("AWSSQSVisibilityTimeout");
    if (st != null) {
        visibilityTimeout = Integer.parseInt(st);
    }

    // TODO: Not certain we want to do these here as it delays deploy and might stop all deploys if AWS is down.
    // Switch to a threaded runnable or maybe just add the job to the threadPool we have.
    sqs = new AmazonSQSClient(new BasicAWSCredentials(awsAccessKey, awsAccessSecret));

    Region region = RegionUtils.getRegion(awsRegion);
    sqs.setRegion(region);

    queUrlMap = new HashMap<String, String>();

    System.out.println("Creating Queues");
    String[] queues = kernels.split(" ");
    for (int i = 0; i < queues.length; i++) {
        threadPool.submit(new SQSCreateQueueTask(sqs, QUEUE_PREPEND + queues[i], visibilityTimeout, this));
    }
}

From source file:shnakkydoodle.queueing.provider.aws.AwsProvider.java

License:Open Source License

/**
 * Create the queue/*from ww  w  . j av a  2 s.com*/
 * 
 * @param queueName
 */
@Override
public void createQueue(String queueName) throws Exception {
    new AmazonSQSClient(credentials).createQueue(queueName);
}

From source file:shnakkydoodle.queueing.provider.aws.AwsProvider.java

License:Open Source License

/**
 * Delete the queue//from  w  ww .  j a  v a2 s.  c om
 * 
 * @param queueName
 */
@Override
public void deleteQueue(String queueName) throws Exception {
    AmazonSQS sqs = new AmazonSQSClient(credentials);
    sqs.setRegion(Region.EU_Ireland.toAWSRegion());
    CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
    sqs.deleteQueue(sqs.createQueue(createQueueRequest).getQueueUrl());
}

From source file:shnakkydoodle.queueing.provider.aws.AwsProvider.java

License:Open Source License

/**
 * Enqueue a message//from   ww  w  .  j av  a2  s  .  c o m
 * 
 * @param queuename
 * @param message
 */
@Override
public void enqueue(String queueName, String message) throws Exception {
    AmazonSQS sqs = new AmazonSQSClient(credentials);
    sqs.setRegion(Region.EU_Ireland.toAWSRegion());
    sqs.createQueue(queueName);
    CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
    String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();
    sqs.sendMessage(new SendMessageRequest(myQueueUrl, message));
}

From source file:shnakkydoodle.queueing.provider.aws.AwsProvider.java

License:Open Source License

/**
 * Enqueue a bunch of message//from w  w w  .  j  av a  2 s  .  c om
 * 
 * @param queuename
 * @param message
 */
@Override
public void enqueue(String queueName, ArrayList<String> messages) throws Exception {
    AmazonSQS sqs = new AmazonSQSClient(credentials);
    sqs.setRegion(Region.EU_Ireland.toAWSRegion());
    sqs.createQueue(queueName);
    CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
    String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

    SendMessageBatchRequest batchRequest = new SendMessageBatchRequest(myQueueUrl);
    batchRequest.setQueueUrl(myQueueUrl);

    List<SendMessageBatchRequestEntry> entries = new ArrayList<SendMessageBatchRequestEntry>();
    for (String message : messages) {
        entries.add(new SendMessageBatchRequestEntry(UUID.randomUUID().toString(), message));
    }
    batchRequest.setEntries(entries);
    sqs.sendMessageBatch(batchRequest);
}

From source file:shnakkydoodle.queueing.provider.aws.AwsProvider.java

License:Open Source License

/**
 * Dequeue a message// ww  w  .ja  va  2  s  .  c om
 * 
 * @param queuename
 * @param message
 */
@Override
public String dequeue(String queueName) throws Exception {

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    sqs.setRegion(Region.EU_Ireland.toAWSRegion());
    sqs.createQueue(queueName);
    CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
    String queueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl);
    Message message = sqs.receiveMessage(receiveMessageRequest).getMessages().get(0);
    if (message != null) {
        sqs.deleteMessage(new DeleteMessageRequest(queueUrl, message.getReceiptHandle()));
        return message.getBody();
    }
    return null;
}