services.SQSQueue.java Source code

Java tutorial

Introduction

Here is the source code for services.SQSQueue.java

Source

package services;
/*
 * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.DeleteQueueRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.amazonaws.services.sqs.model.GetQueueUrlRequest;

public class SQSQueue {

    private AmazonSQS sqs;
    private String QueueName;
    private String queueUrl;
    private int numberOfMsg;

    /**
     * This contractor connects to an existing queue
     * @param AmazonSQS sqs
     * @param QueueName the queue name
     */
    public SQSQueue(AmazonSQS sqs, String queueName) {
        this.sqs = sqs;
        this.QueueName = queueName;
        this.queueUrl = sqs.getQueueUrl(new GetQueueUrlRequest(QueueName)).getQueueUrl();
        //      this.numberOfMsg = 0;
        //      this.queueUrl="https://queue.amazonaws.com/774031739424/" +QueueName;//g1.getQueueUrl();
    }

    /**
     * This contractor create a new queue 
     * @param AmazonSQS sqs
     * @param QueueName the queue name
     */
    public SQSQueue(String queueName, AmazonSQS sqs) {
        this.sqs = sqs;
        this.QueueName = queueName;
        this.createQueue(queueName);
        //      this.numberOfMsg = 0;
        //      this.queueUrl="https://queue.amazonaws.com/774031739424/" +QueueName;//g1.getQueueUrl();
    }

    /**
     * Copy Constructor
     */
    public SQSQueue(AmazonSQS sqs, String QueueName, String queueUrl, int numberOfMsg) {
        this.sqs = sqs;
        this.numberOfMsg = numberOfMsg;
        this.QueueName = QueueName;
        this.queueUrl = queueUrl;
    }

    // getters
    public AmazonSQS getSQS() {
        return this.sqs;
    }

    public String getQueueUrl() {
        return this.queueUrl;
    }

    public boolean isEmpty() {
        return this.numberOfMsg == 0;
    }

    public void setSQS(AmazonSQS newSQS) {
        this.sqs = newSQS;
    }

    //constructor creating a new queue/using existing queue in order to init queueUrl field
    //status=0 - new queue
    //status!=0 - existing queue
    /*   public void superCreateQueue(String QueueName,int status) {
          while(createQueue(QueueName,status) < 0)
     try {
        Thread.sleep(1000);
     } catch (InterruptedException e) {
        e.printStackTrace();
     }
       }*/

    /**
     * This function create a queue
     * @param QueueName the Queue  Name
     * @param status 0 to create a queue 
           1 to connect to exist queue
     */
    public void createQueue(String QueueName) {
        try {
            System.out.println("Creating a new SQS queue called " + QueueName);
            sqs.setEndpoint("sqs.us-east-1.amazonaws.com");
            CreateQueueRequest createQueueRequest = new CreateQueueRequest(QueueName);
            queueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();
        }

        catch (AmazonServiceException ase) {
            queueUrl = "";
            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) {
            queueUrl = "";
            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());
        }
    }

    public String isExists(String QueueName) {
        try {
            System.out.println("connecting to existing SQS queue called " + QueueName + "\n");
            GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QueueName);
            this.queueUrl = this.sqs.getQueueUrl(getQueueUrlRequest).getQueueUrl();
        }

        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());
            this.queueUrl = null;
        }

        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());
            this.queueUrl = null;
        }

        return this.queueUrl;
    }

    /**
     * This function sends message to queue until he receive it
     * @param msg the message to send
     */
    public void superSendMessage(String msg) throws InterruptedException {
        while (sendMsg(msg) == -1)
            Thread.sleep(1000);
    }

    /**
     * This function sends message to queue.
     * @param msg the message to send
     */
    public int sendMsg(String msg) {
        try {
            System.out.println("Sending a message to " + QueueName + ".\n");
            sqs.sendMessage(new SendMessageRequest(queueUrl, msg));
            this.numberOfMsg++;
        }

        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("Org message" + this.QueueName + " m is " + msg);
            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());
            numberOfMsg--;
            return -1;
        }

        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());
            numberOfMsg--;
            return -1;
        }

        return 0;
    }

    /**
     * This function receive Message from queue.
     * @return  Message
     */
    public Message reciveMsg() {
        Message message = null;

        try {
            System.out.println("Receiving messages from " + QueueName + " \n");
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl);
            message = sqs.receiveMessage(receiveMessageRequest).getMessages().get(0);

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

        catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException in Recieve, 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());
        }

        catch (java.lang.IndexOutOfBoundsException e) {
        }

        return message;
    }

    /**
     * This function delete  Message from queue
     * @param msg the Message to delete
     */
    public void deleteMsg(Message msg) {
        try {
            System.out.println("Deleting a message.\n");
            String messageRecieptHandle = msg.getReceiptHandle();
            sqs.deleteMessage(new DeleteMessageRequest(queueUrl, messageRecieptHandle));
            numberOfMsg--;
        }

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

    /**
     * This function delete the queue
     */
    public void deleteQueue() {
        try {
            System.out.println("Deleting the test queue.\n");
            sqs.deleteQueue(new DeleteQueueRequest(queueUrl));
            this.queueUrl = "";
            this.numberOfMsg = 0;
        }

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

    /*   public static void main(String[] args) throws Exception {
          System.out.println("===========================================");
          System.out.println("Getting Started with Amazon SQS");
          System.out.println("===========================================\n");
              
          SBSQueue queue1= new SBSQueue();
          queue1.createQueue(sqs, "queue3",0);
          queue1.sendMsg(sqs,"I am the king 1");
          queue1.sendMsg(sqs,"I am the king 2");
          Message m=queue1.reciveMsg(sqs);
          
          Message m1=queue1.reciveMsg(sqs);
          queue1.deleteMsg(sqs, m);
       }   */

}