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:com.infinitechaos.vpcviewer.service.impl.VpcServiceImpl.java

License:Open Source License

private synchronized AmazonEC2 getClientForRegion(final String regionName) {
    return clients.computeIfAbsent(Regions.fromName(regionName), region -> {
        LOG.info("Creating client for region {}", region);
        return Region.getRegion(region).createClient(AmazonEC2Client.class,
                new DefaultAWSCredentialsProviderChain(), new ClientConfiguration());
    });//from  w ww  .  j a va 2 s .  c  om
}

From source file:com.intuit.tank.vmManager.environment.amazon.CloudwatchInstance.java

License:Open Source License

/**
 * /*from  ww  w.  j  a  v  a 2s.c  o m*/
 * @param request
 * @param vmRegion
 */
public CloudwatchInstance(VMRegion vmRegion) {
    // In case vmRegion is passed as null, use default region from settings file
    if (vmRegion == null) {
        vmRegion = config.getVmManagerConfig().getDefaultRegion();
    }
    try {
        CloudCredentials creds = config.getVmManagerConfig().getCloudCredentials(CloudProvider.amazon);
        AWSCredentials credentials = new BasicAWSCredentials(creds.getKeyId(), creds.getKey());
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setMaxConnections(2);
        if (StringUtils.isNotBlank(creds.getProxyHost())) {
            try {
                clientConfig.setProxyHost(creds.getProxyHost());

                if (StringUtils.isNotBlank(creds.getProxyPort())) {
                    clientConfig.setProxyPort(Integer.valueOf(creds.getProxyPort()));
                }
            } catch (NumberFormatException e) {
                logger.error("invalid proxy setup.");
            }

        }
        if (StringUtils.isNotBlank(creds.getKeyId()) && StringUtils.isNotBlank(creds.getKey())) {
            asynchCloudWatchClient = new AmazonCloudWatchAsyncClient(credentials, clientConfig,
                    Executors.newFixedThreadPool(2));
            asyncSnsClient = new AmazonSNSAsyncClient(credentials, clientConfig,
                    Executors.newFixedThreadPool(2));
        } else {
            asynchCloudWatchClient = new AmazonCloudWatchAsyncClient(clientConfig);
            asyncSnsClient = new AmazonSNSAsyncClient(clientConfig);
        }
        asynchCloudWatchClient.setRegion(Region.getRegion(Regions.fromName(vmRegion.getRegion())));
        asyncSnsClient.setRegion(Region.getRegion(Regions.fromName(vmRegion.getRegion())));
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw new RuntimeException(ex);
    }
}

From source file:com.ipcglobal.awscdh.config.ManageEc2.java

License:Apache License

/**
 * Instantiates a new manage ec2.//from  w  w  w  .ja  v a 2s .  c  om
 *
 * @param properties the properties
 * @throws Exception the exception
 */
public ManageEc2(Properties properties) throws Exception {
    this.properties = properties;
    String credentialsProfileName = this.properties.getProperty("credentialsProfileName").trim();
    String credentialsRegion = this.properties.getProperty("credentialsRegion").trim();
    this.vpcId = this.properties.getProperty("vpcId").trim();
    this.instanceIds = new ArrayList<String>(Arrays.asList(properties.getProperty("instanceIds").split("[ ]")));
    this.timeoutMinutesStartEc2Instances = Integer
            .parseInt(this.properties.getProperty("timeoutMinutesStartEc2Instances"));
    this.timeoutMinutesStopEc2Instances = Integer
            .parseInt(this.properties.getProperty("timeoutMinutesStopEc2Instances"));

    if (credentialsProfileName == null)
        this.credentialsProvider = Utils.initCredentials();
    else
        this.credentialsProvider = Utils.initProfileCredentialsProvider(credentialsProfileName);

    this.ec2Client = new AmazonEC2Client(credentialsProvider);
    if (credentialsRegion != null) {
        Regions regions = Regions.fromName(credentialsRegion);
        this.ec2Client.setRegion(Region.getRegion(regions));
    }
}

From source file:com.jfixby.scarabei.red.aws.test.S3Sample.java

License:Open Source License

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

    /*//from w  w  w . j a  v  a2s  . c  o m
     * The ProfileCredentialsProvider will return your [default] credential profile by reading from the credentials file located
     * at (C:\\Users\\JCode\\.aws\\credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (final 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\\%USERNAME%\\.aws\\credentials), and is in valid format.", e);
    }

    final AmazonS3 s3 = new AmazonS3Client(credentials);
    final Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    final String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    final String key = "MyObjectKey";

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

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique, so once a bucket name has been taken by any user,
         * you can't create another bucket with that same name.
         *
         * You can optionally specify a location for your bucket if you want to keep your data closer to your applications or
         * users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (final Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        /*
         * Upload an object to your bucket - You can easily upload a file to S3, or upload directly an InputStream if you know
         * the length of the data in the stream. You can also specify your own metadata when uploading to S3, which allows you
         * set a variety of options like content-type and content-encoding, plus additional metadata specific to your
         * applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Download an object - When you download an object, you get all of the object's metadata and a stream from which to read
         * the contents. It's important to read the contents of the stream as quickly as possibly since the data is streamed
         * directly from Amazon S3 and your network connection will remain open until you read all the data or close the input
         * stream.
         *
         * GetObjectRequest also supports several other options, including conditional downloading of objects based on
         * modification times, ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        final S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for listing the objects in your bucket. Keep in mind
         * that buckets with many objects might truncate their results when listing their objects, so be sure to check if the
         * returned object listing is truncated, and use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
         * additional results.
         */
        System.out.println("Listing objects");
        final ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (final S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket, there is no way to undelete an object, so use
         * caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be deleted, so remember to delete any objects from
         * your buckets before you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } catch (final AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, 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 (final AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.jktsoftware.amazondownloader.queuemanager.DownloaderQueueManager.java

License:Open Source License

public void CreateQueues() {
    AWSCredentials awscredentials = new BasicAWSCredentials(this._credentials.getAccessKey(),
            this._credentials.getSecretAccessKey());

    _sqs = new AmazonSQSClient(awscredentials);
    Region euWest1 = Region.getRegion(Regions.EU_WEST_1);
    _sqs.setRegion(euWest1);//from   ww  w. j ava 2 s  .co m

    System.out.println("Creating amazon download queues.\n");

    CreateQueueRequest createReceivedQueueRequest = new CreateQueueRequest(_receivedqueuename);

    this._receivedqueueurl = _sqs.createQueue(createReceivedQueueRequest).getQueueUrl();

    CreateQueueRequest createFailedQueueRequest = new CreateQueueRequest(_failedqueuename);

    this._failedqueueurl = _sqs.createQueue(createFailedQueueRequest).getQueueUrl();
}

From source file:com.jooketechnologies.network.ServerUtilities.java

License:Apache License

public void generateProfileImageUrl(Uri uri, Context context) {
    s3Client.setRegion(Region.getRegion(Regions.US_EAST_1));
    new S3PutObjectTask(context).execute(uri);

}

From source file:com.kirana.services.ProductServicesImpl.java

public AmazonS3 getS3Client() {
    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider("kirana-s3"));
    s3client.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));
    return s3client;
}

From source file:com.kirana.utils.GeneratePresignedUrlAndUploadObject.java

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

    System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
    System.setProperty(SDKGlobalConfiguration.ACCESS_KEY_ENV_VAR, "AKIAJ666LALJZHA6THGQ");
    System.setProperty(SDKGlobalConfiguration.SECRET_KEY_ENV_VAR, "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");
    //      AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider("kirana"));

    ProfilesConfigFile profile = new ProfilesConfigFile("AwsCredentials.properties");
    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
    s3client.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));

    try {/*from w  ww  .ja v a2 s .c  o  m*/
        System.out.println("Generating pre-signed URL.");
        java.util.Date expiration = new java.util.Date();
        long milliSeconds = expiration.getTime();
        milliSeconds += 1000 * 60 * 60; // Add 1 hour.
        expiration.setTime(milliSeconds);

        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName,
                objectKey);
        generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
        generatePresignedUrlRequest.setExpiration(expiration);

        //                        s3client.putObject(bucketName, objectKey, null);

        URL url = s3client.generatePresignedUrl(generatePresignedUrlRequest);
        UploadObject(url);

        System.out.println("Pre-Signed URL = " + url.toString());
    } catch (AmazonServiceException exception) {
        System.out.println("Caught an AmazonServiceException, " + "which means your request made it "
                + "to Amazon S3, but was rejected with an error response " + "for some reason.");
        System.out.println("Error Message: " + exception.getMessage());
        System.out.println("HTTP  Code: " + exception.getStatusCode());
        System.out.println("AWS Error Code:" + exception.getErrorCode());
        System.out.println("Error Type:    " + exception.getErrorType());
        System.out.println("Request ID:    " + exception.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, " + "which means the client encountered "
                + "an internal error while trying to communicate" + " with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.kiribuki.queueservice.QueueService.java

License:Open Source License

public QueueService() throws Exception {
    Region euWest1 = Region.getRegion(Regions.EU_WEST_1);
    try {//from   w  w  w  .j  ava 2s .co m
        sqs.setRegion(euWest1);
        swok = true;
    } catch (Exception e) {
        swok = false;
    }
}

From source file:com.kixeye.chassis.support.metrics.aws.DefaultCloudWatchFactory.java

License:Apache License

private Region getCloudWatchRegion(String region) {
    if ("default".equals(region)) {
        return Region.getRegion(Regions.DEFAULT_REGION);
    }/* ww  w.  ja  v  a 2  s  . c o m*/
    return Region.getRegion(Regions.fromName(region));
}