Example usage for com.amazonaws.services.sqs AmazonSQS setRegion

List of usage examples for com.amazonaws.services.sqs AmazonSQS setRegion

Introduction

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

Prototype

@Deprecated
void setRegion(Region region);

Source Link

Document

An alternative to AmazonSQS#setEndpoint(String) , sets the regional endpoint for this client's service calls.

Usage

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;//from w  w w. j av a  2  s .c  o  m
    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.dushyant.flume.sink.aws.sqs.BasicSQSMsgSender.java

License:Apache License

public BasicSQSMsgSender(String sqsUrl, String region, String awsAccessKey, String awsSecretKey) {
    this.sqsUrl = sqsUrl;
    this.region = region;
    this.awsAccessKey = awsAccessKey;
    this.awsSecretKey = awsSecretKey;

    AmazonSQS sqs = null;
    if (StringUtils.isBlank(awsAccessKey) || StringUtils.isBlank(awsSecretKey)) {
        LOG.warn(/*from   w  w  w  . ja va 2s  . c  om*/
                "Either awsAccessKey or awsSecretKey not specified. Will use DefaultAWSCredentialsProviderChain "
                        + "to look for AWS credentials.");
        sqs = new AmazonSQSClient();
    } else {
        sqs = new AmazonSQSClient(new BasicAWSCredentials(this.awsAccessKey, this.awsSecretKey));
    }

    Region sqsRegion = Region.getRegion(Regions.fromName(this.region));
    sqs.setRegion(sqsRegion);

    this.amazonSQS = sqs;
}

From source file:com.dushyant.flume.sink.aws.sqs.BatchSQSMsgSender.java

License:Apache License

public BatchSQSMsgSender(String sqsUrl, String region, String awsAccessKey, String awsSecretKey, int batchSize,
        long maxMessageSize) {
    this.sqsUrl = sqsUrl;
    this.region = region;
    this.awsAccessKey = awsAccessKey;
    this.awsSecretKey = awsSecretKey;

    AmazonSQS sqs = null;
    if (StringUtils.isBlank(awsAccessKey) || StringUtils.isBlank(awsSecretKey)) {
        LOG.warn(//w  ww .j  a v a  2s  . c om
                "Either awsAccessKey or awsSecretKey not specified. Will use DefaultAWSCredentialsProviderChain "
                        + "to look for AWS credentials.");
        sqs = new AmazonSQSClient();
    } else {
        sqs = new AmazonSQSClient(new BasicAWSCredentials(this.awsAccessKey, this.awsSecretKey));
    }

    Region sqsRegion = Region.getRegion(Regions.fromName(this.region));
    sqs.setRegion(sqsRegion);

    this.batchSize = batchSize;
    this.maxMessageSize = maxMessageSize;

    this.amazonSQS = sqs;
}

From source file:com.dxc.temp.SimpleQueueServiceSample.java

License:Open Source License

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

    BasicConfigurator.configure();// w  w w .j a  v  a2s .  co  m

    /*
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().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);
    }
    System.out.println(String.format("Found AWSAccessKeyId: %s", credentials.getAWSAccessKeyId()));
    System.out.println(String.format("Found AWSAccessSecretKey: %s", credentials.getAWSSecretKey()));

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

    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, "Message body 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 messageReceiptHandle = messages.get(0).getReceiptHandle();
        //            sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));

        // Delete a queue
        // You must wait 60 seconds after deleting a queue before you can create another with the same name
        //            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.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.SqsQueueDetail.java

License:Open Source License

@Override
public String retrieveDetails(ResourceDetailRequest detailRequest) {

    String response = null;// w ww . j  a  v  a2 s.  c  o  m

    try {

        AmazonSQS client = new AmazonSQSClient(credentials);
        client.setRegion(Region.getRegion(Regions.fromName(detailRequest.getRegion())));

        buildUI(null);

    } catch (IllegalArgumentException | AmazonClientException e) {
        response = e.getMessage();
        LOGGER.log(Level.WARNING, "Problem retrieving SQS details from AWS", e);
    }

    return response;
}

From source file:com.ibm.connectors.AmazonSQS.AmazonSQSInputConnector.java

License:Open Source License

@Override
public void poll(long waitInterval) {
    Properties properties = new Properties();

    String access_key_id = getProperty("AccessKeyId");
    String secret_access_key = getProperty("SecretAccessKey");
    BasicAWSCredentials credentials = new BasicAWSCredentials(access_key_id, secret_access_key);

    AmazonSQS sqs = new AmazonSQSClient(credentials);

    // Region selection
    Region region = Region.getRegion(Regions.fromName(getProperty("region")));
    sqs.setRegion(region);

    GetQueueUrlResult queueUrl = sqs.getQueueUrl(getProperty("Queue"));

    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl.getQueueUrl());
    List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();

    String outputMessage = "";
    // if there are messages then do the processing
    if (messages.size() > 0) {

        //append the message properties to the localenv tree
        for (Message message : messages) {
            properties.setProperty("MessageId", message.getMessageId());
            properties.setProperty("ReceiptHandle", message.getReceiptHandle());
            properties.setProperty("MD5OfBody", message.getMD5OfBody());
            // get the message body to a string
            outputMessage = message.getBody();
        }// w w w .j a  va 2 s . c om
        properties.setProperty("queueUrl", queueUrl.getQueueUrl());
        // delete the message from the queue
        String messageReceiptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(queueUrl.getQueueUrl(), messageReceiptHandle));
        ConnectorCallback callback = getCallback();
        callback.processInboundData(outputMessage.getBytes(), properties);
    }
}

From source file:com.ibm.connectors.AmazonSQS.AmazonSQSOutputInteraction.java

License:Open Source License

@Override
public Properties send(Properties properties, Object message) throws ConnectorException {

    String access_key_id = properties.getProperty("AccessKeyId");
    String secret_access_key = properties.getProperty("SecretAccessKey");
    BasicAWSCredentials credentials = new BasicAWSCredentials(access_key_id, secret_access_key);

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    //System.out.println(properties.getProperty("region"));
    // Region selection
    Region region = Region.getRegion(Regions.fromName(properties.getProperty("region")));
    sqs.setRegion(region);

    GetQueueUrlResult queueUrl = sqs.getQueueUrl(properties.getProperty("Queue"));
    String messageStr = new String((byte[]) message);

    sqs.sendMessage(new SendMessageRequest(queueUrl.getQueueUrl(), messageStr));

    return properties;
}

From source file:com.mateusz.mateuszsqs.SQSprocessor.java

public static void main(String[] args) throws AmazonClientException {
    System.out.println("Start process SQS");
    try {/*ww  w .j  a va 2s  .  c om*/
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        System.out.println("Error");
        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);
    }

    final Thread mainThread = new Thread(() -> {
        while (!Thread.currentThread().isInterrupted()) {
            AmazonSQS sqs = new AmazonSQSClient(credentials);
            Region usWest2 = Region.getRegion(Regions.US_WEST_2);
            sqs.setRegion(usWest2);

            AmazonS3 s3 = new AmazonS3Client(credentials);
            s3.setRegion(usWest2);

            List<String> filesList = SQSConfig.getMessages(sqs, sqsURL);

            for (String file : filesList) {
                String[] files = file.split(",");
                if (!file.equals("missing parameter: fileNames"))
                    for (int i = 0; i < files.length; i++) {
                        try {
                            SQSConfig.processFile(files[i], s3, bucketName);
                        } catch (IOException e) {
                            System.out.println("Error");
                            e.printStackTrace();
                        }
                    }

            }
            System.out.println("\nWaiting for messages.........\n");
        }
    });
    mainThread.start();
}

From source file:com.mycompany.rproject.runnableClass.java

public static void use() throws IOException {
    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);
    String myQueueUrl = "https://sqs.us-west-2.amazonaws.com/711690152696/MyQueue";

    System.out.println("Receiving messages from MyQueue.\n");

    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
    List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
    while (messages.isEmpty()) {

        messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
    }/* w ww  . ja v a 2s  .c o  m*/

    String messageRecieptHandle = messages.get(0).getReceiptHandle();

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

    sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

    //aqui opero y cuando acabe llamo para operar el siguiente.

    String n = "";
    String dbName = "mydb";
    String userName = "pmontojo";
    String password = "pmontojo";
    String hostname = "mydb.cued7orr1q2t.us-west-2.rds.amazonaws.com";
    String port = "3306";
    String jdbcUrl = "jdbc:mysql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password="
            + password;
    Connection conn = null;
    Statement setupStatement = null;
    Statement readStatement = null;
    ResultSet resultSet = null;
    String results = "";
    int numresults = 0;
    String statement = null;

    try {

        conn = DriverManager.getConnection(jdbcUrl);

        setupStatement = conn.createStatement();

        String insertUrl = "select video_name from metadata where id = " + a + ";";
        String checkUrl = "select url from metadata where id = " + a + ";";

        ResultSet rs = setupStatement.executeQuery(insertUrl);

        rs.next();

        System.out.println("este es el resultdo " + rs.getString(1));

        String names = rs.getString(1);
        ResultSet ch = setupStatement.executeQuery(checkUrl);
        ch.next();
        System.out.println("este es la url" + ch.getString(1));
        String urli = ch.getString(1);

        while (urli == null) {
            ResultSet sh = setupStatement.executeQuery(checkUrl);
            sh.next();
            System.out.println("este es la url" + sh.getString(1));
            urli = sh.getString(1);

        }
        setupStatement.close();
        AmazonS3 s3Client = new AmazonS3Client(awsCreds);

        S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, names));

        IOUtils.copy(object.getObjectContent(),
                new FileOutputStream(new File("/Users/paulamontojo/Desktop/download.avi")));

        putOutput();
        write();
        putInDb(sbu.toString(), a);

    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
    } finally {
        System.out.println("Closing the connection.");
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
    }

    use();

}

From source file:com.rodosaenz.samples.aws.sqs.AwsSqsSimpleExample.java

License:Open Source License

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

    /*//from www. ja v a 2  s  .  c  o m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().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.US_EAST_1);
    sqs.setRegion(usWest2);

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

    String queue_name = "com-rodosaenz-examples-aws-sqs";

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called " + queue_name + ".\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(queue_name);
        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 " + queue_name + ".\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);
        receiveMessageRequest.setMaxNumberOfMessages(1);
        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 messageReceiptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));

        //Get attributes
        GetQueueAttributesRequest request = new GetQueueAttributesRequest(myQueueUrl).withAttributeNames("All");
        final Map<String, String> attributes = sqs.getQueueAttributes(request).getAttributes();

        System.out.println("  Policy: " + attributes.get("Policy"));
        System.out.println("  MessageRetentionPeriod: " + attributes.get("MessageRetentionPeriod"));
        System.out.println("  MaximumMessageSize: " + attributes.get("MaximumMessageSize"));
        System.out.println("  CreatedTimestamp: " + attributes.get("CreatedTimestamp"));
        System.out.println("  VisibilityTimeout: " + attributes.get("VisibilityTimeout"));
        System.out.println("  QueueArn: " + attributes.get("QueueArn"));
        System.out.println("  ApproximateNumberOfMessages: " + attributes.get("ApproximateNumberOfMessages"));
        System.out.println("  ApproximateNumberOfMessagesNotVisible: "
                + attributes.get("ApproximateNumberOfMessagesNotVisible"));
        System.out.println("  DelaySeconds: " + attributes.get("DelaySeconds"));

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