Example usage for com.amazonaws.regions Region getRegion

List of usage examples for com.amazonaws.regions Region getRegion

Introduction

In this page you can find the example usage for com.amazonaws.regions Region getRegion.

Prototype

public static Region getRegion(Regions region) 

Source Link

Document

Returns the region with the id given, or null if it cannot be found in the current regions.xml file.

Usage

From source file:receiveSQS.java

License:Open Source License

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

    /*//from   w  ww.  j av  a2 s.  co m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * ().
     */

    BasicAWSCredentials credentials = new BasicAWSCredentials("AKIAI2ZCFS3NVEENXW5A",
            "tI/GgpSWDF/QrNVhtCRu1G+PX/10A2nJQH+yTOiv");
    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_WEST_2);
    sqs.setRegion(usWest2);

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

    try {

        // 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();
            // Receive messages
            System.out.println("Receiving messages from MyQueue.\n");
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl);
            System.out.println("Message size:");

            //*****************************************************

            //For some reason, we only get one message at a time and it does not loop over.

            //*****************************************************

            //ReceiveMessageResponse receiveMessageResponse = amazonSQSClient.ReceiveMessage(receiveMessageRequest);
            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());
                String[] tweetdata = message.getBody().split("\\|\\|");
                System.out.println(Arrays.toString(tweetdata));
                System.out.println("Deleting a message.\n");
                String messageRecieptHandle = messages.get(0).getReceiptHandle();
                sqs.deleteMessage(new DeleteMessageRequest(queueUrl, messageRecieptHandle));

            }
        }

        System.out.println();
        /*
                    // Delete a message
                
                    // 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:aot.storage.s3.CustomStorage.java

License:Open Source License

protected static AmazonS3 createS3(String[] ids) {
    AmazonS3 s3;//  w  ww  .j  av a2 s .  com
    if ((ids.length >= 1) && !ids[1].trim().isEmpty()) {
        String[] creds = ids[1].split(":");
        s3 = new AmazonS3Client(new BasicAWSCredentials(creds[0], creds[1]));
    } else {
        s3 = new AmazonS3Client();
    }
    if ((ids.length >= 2) && !ids[2].trim().isEmpty()) {
        s3.setRegion(Region.getRegion(Regions.fromName(ids[2])));
    }
    if ((ids.length >= 3) && !ids[3].trim().isEmpty()) {
        s3.setEndpoint(ids[3]);
    }
    return s3;
}

From source file:app.SQSMessage.java

License:Open Source License

public void sendmsg(Tweet t, String keyword) throws Exception {

    /*//from   w  ww  . jav  a  2s .c  o  m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * ().
     */
    credentials = new ProfileCredentialsProvider("default").getCredentials();
    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usWest2);

    System.out.println("===========================================");
    System.out.println("sending tweet to Queue");
    System.out.println("===========================================\n");

    try {

        // Send a message
        System.out.println("Sending a message to TweetQueue.\n");

        JSONObject obj = new JSONObject();

        obj.put("userId", t.getUserId() + "");
        obj.put("lng", t.getLongitude() + "");
        obj.put("lat", t.getLatitude() + "");
        obj.put("text", t.getText());
        // obj.put("time", t.getCreatedTime().toString());
        obj.put("kwd", keyword);

        //String TwtJson = "{\"userId\":\"" + t.getUserId() + "\",\"lng\":\"" + t.getLongitude() + "\",\"lat\":\"" + t.getLatitude() + "\",\"text\":\"" + JSONObject.escape(t.getText()) +  "\",\"time\":\"" + t.getCreatedTime() + "\",\"kwd\":\"" + keyword + "\"}";

        String TwtJson = obj.toString();

        System.out.println(TwtJson);
        sqs.sendMessage(new SendMessageRequest(q_url, TwtJson));

    } 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:apphub.storage.s3.CustomStorage.java

License:Open Source License

protected static AmazonS3 createS3(URL url) {
    AmazonS3 s3;/*  w w w .  j  a  v  a 2 s  .  c om*/
    String userInfo = url.getUserInfo();
    if (userInfo != null) {
        String[] creds = userInfo.split(":");
        if (creds.length == 2) {
            s3 = new AmazonS3Client(new BasicAWSCredentials(creds[0], creds[1]));
        } else {
            throw new CreateStorageException(url.toString(),
                    "Credentials for S3 storage must be in form of KEY:SECRET");
        }
    } else {
        s3 = new AmazonS3Client();
    }
    Map<String, String> queryParameters = UrlUtil.getQueryParameters(url);
    String region = queryParameters.get("region");
    if (region != null) {
        s3.setRegion(Region.getRegion(Regions.fromName(region)));
    }
    String endpoint = queryParameters.get("endpoint");
    if (endpoint != null) {
        s3.setEndpoint(endpoint);
    }
    return s3;
}

From source file:arcade.database.S3Connections.java

License:Open Source License

/**
 * Constructor that connects to S3Instance
 *//*from   www .  ja va 2 s .co  m*/
public S3Connections() {
    myS3Instance = new AmazonS3Client(
            new ClasspathPropertiesFileCredentialsProvider("AwsCredentials.properties"));
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    myS3Instance.setRegion(usWest2);
}

From source file:awslabs.lab22.StudentCode.java

License:Open Source License

/**
 * Create a DynamoDB item from the values specified in the account parameter. The names of the attributes in the
 * item should match the corresponding property names in the Account object. Don't add attributes for fields in the
 * Account object that are empty./*  w  w w.  j  av a 2  s  . c o m*/
 * 
 * Since the Company and Email attributes are part of the table key, those will always be provided in the Account
 * object when this method is called. This method will be called multiple times by the code controlling the lab.
 * 
 * Important: Even thought the Account.Age property is passed to you as a string, add it to the item as a numerical
 * value.
 * 
 * @param ddbClient The DynamoDB client object.
 * @param tableName The name of the table to add the item to.
 * @param account The Account object containing the data to add.
 */
@Override
public void createAccountItem(AmazonDynamoDBClient ddbClient, String tableName, Account account) {
    // TODO: Replace this call to the super class with your own implementation of the method.
    ddbClient.setRegion(Region.getRegion(Regions.US_EAST_1));
    Map<String, AttributeValue> items = new HashMap<String, AttributeValue>();
    items.put("Company", new AttributeValue().withS(account.getCompany()));
    items.put("Email", new AttributeValue().withS(account.getEmail()));

    if (account.getFirst() != null) {
        items.put("First", new AttributeValue().withS(account.getFirst()));
    }

    if (account.getLast() != null) {
        items.put("Last", new AttributeValue().withS(account.getLast()));
    }

    if (account.getAge() != null) {
        items.put("Age", new AttributeValue().withN(account.getAge()));
    }

    PutItemRequest request = new PutItemRequest().withTableName(tableName).withItem(items);
    ddbClient.putItem(request);
}

From source file:awslabs.lab51.SolutionCode.java

License:Open Source License

@Override
public AmazonS3Client createS3Client(AWSCredentials credentials) {
    Region region = Region.getRegion(Regions.fromName(System.getProperty("REGION")));
    AmazonS3Client client = new AmazonS3Client();
    client.setRegion(region);/* w  w w .ja va 2s . c o  m*/

    return client;
}

From source file:awslabs.lab51.SolutionCode.java

License:Open Source License

@Override
public AmazonDynamoDBClient createDynamoDbClient(AWSCredentials credentials) {
    Region region = Region.getRegion(Regions.fromName(System.getProperty("REGION")));
    AmazonDynamoDBClient client = new AmazonDynamoDBClient();
    client.setRegion(region);//ww w .ja  v a 2  s  . c  o m

    return client;
}

From source file:br.com.faccilitacorretor.middleware.dynamo.AmazonDynamoDBSample.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.ProfilesConfigFile
 * @see com.amazonaws.ClientConfiguration
 *///from ww w.  j  ava 2  s.  c  om
private static void init() throws Exception {
    /*
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (/home/turbiani/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new BasicAWSCredentials(PropertiesConfig.getInstance().get("ACCESS_KEY"),
                PropertiesConfig.getInstance().get("SECRET_ACCESS_KEY"));
    } 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/turbiani/.aws/credentials), and is in valid format.", e);
    }
    dynamoDB = new AmazonDynamoDBClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    dynamoDB.setRegion(usEast1);
}

From source file:br.com.ingenieux.jenkins.plugins.awsebdeployment.Deployer.java

License:Apache License

private void initAWS() {
    log("Creating S3 and AWSEB Client (AWS Access Key Id: %s, region: %s)", context.getAwsAccessKeyId(),
            context.getAwsRegion());//from  w  ww  .  j  a  v a  2s  . c  om

    AWSCredentialsProvider credentials = new AWSCredentialsProviderChain(new StaticCredentialsProvider(
            new BasicAWSCredentials(context.getAwsAccessKeyId(), context.getAwsSecretSharedKey())));
    Region region = Region.getRegion(Regions.fromName(context.getAwsRegion()));
    ClientConfiguration clientConfig = new ClientConfiguration();

    clientConfig.setUserAgent("ingenieux CloudButler/" + getVersion());

    s3 = region.createClient(AmazonS3Client.class, credentials, clientConfig);
    awseb = region.createClient(AWSElasticBeanstalkClient.class, credentials, clientConfig);
}