List of usage examples for com.amazonaws.regions Region getRegion
public static Region getRegion(Regions region)
From source file:com.arc.cloud.aws.s3.S3Sample.java
License:Open Source License
public static void main(String[] args) throws IOException { /*//from w w w . jav a2s . 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); } AmazonS3 s3 = new AmazonS3Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); s3.setRegion(usWest2); String bucketName = "my-first-s3-bucket-" + UUID.randomUUID(); 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 (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"); 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"); ObjectListing objectListing = s3 .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My")); for (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 (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 (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.atlassian.localstack.sample.S3Sample.java
License:Open Source License
public static void runTest(AWSCredentials credentials) throws IOException { AmazonS3 s3 = new AmazonS3Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); s3.setRegion(usWest2);// w w w.j a va2 s . co m s3.setEndpoint(LocalstackTestRunner.getEndpointS3()); String bucketName = "my-first-s3-bucket-" + UUID.randomUUID(); String key = "MyObjectKey"; System.out.println("==========================================="); System.out.println("Getting Started with Amazon S3"); System.out.println("===========================================\n"); /* * 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 (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"); 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"); ObjectListing objectListing = s3 .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My")); for (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); }
From source file:com.aws.sampleImage.url.LambdaFunctionImageURLCrawlerHandler.java
private static void init() { AWSCredentials awsCredentials = new AWSCredentials() { @Override//from w ww . j av a 2 s . co m public String getAWSSecretKey() { return "M2HnD68DXBmeNYcuxO0PDVuRPjJONDLiRXTFwygN";//M2HnD68DXBmeNYcuxO0PDVuRPjJONDLiRXTFwygN } @Override public String getAWSAccessKeyId() { return "AKIAJ5LSYQCPXHSNYVYQ";//AKIAJ5LSYQCPXHSNYVYQ } }; //dynamoDB = new AmazonDynamoDBClient(new EnvironmentVariableCredentialsProvider()); dynamoDB = new AmazonDynamoDBClient(awsCredentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); dynamoDB.setRegion(usWest2); System.out.println("^^^^^ DynamoDB created successfully --> " + dynamoDB); }
From source file:com.AWSManagementAntTask.dao.RDSDao.java
public RDSDao(AWSMATDto dto) { AWSCredentialsProvider provider = new ProfileCredentialsProvider(dto.getProfilename()); rds = Region.getRegion(dto.getRegionid()).createClient(AmazonRDSClient.class, provider, new ClientConfiguration()); this.dto = dto; }
From source file:com.bodybuilding.turbine.discovery.AsgTagInstanceDiscovery.java
License:Apache License
protected AsgTagInstanceDiscovery(AmazonAutoScalingClient asgClient, AmazonEC2Client ec2Client) { Preconditions.checkNotNull(asgClient); Preconditions.checkNotNull(ec2Client); Preconditions.checkState(!Strings.isNullOrEmpty(CLUSTER_TAG_KEY.get()), TAG_PROPERTY_NAME + " must be supplied!"); this.asgClient = asgClient; this.ec2Client = ec2Client; String regionName = DynamicPropertyFactory.getInstance().getStringProperty("turbine.region", "").get(); if (Strings.isNullOrEmpty(regionName)) { Region currentRegion = Regions.getCurrentRegion(); if (currentRegion != null) { regionName = currentRegion.getName(); } else {//from ww w . j a v a 2 s . c o m regionName = "us-east-1"; } } Region region = Region.getRegion(Regions.fromName(regionName)); ec2Client.setRegion(region); asgClient.setRegion(region); log.debug("Set the region to [{}]", region); }
From source file:com.bodybuilding.turbine.discovery.Ec2TagInstanceDiscovery.java
License:Apache License
protected Ec2TagInstanceDiscovery(AmazonEC2Client ec2Client) { Preconditions.checkNotNull(ec2Client); this.ec2Client = ec2Client; Preconditions.checkState(!Strings.isNullOrEmpty(CLUSTER_TAG_KEY.get()), PROPERTY_NAME + " must be supplied!"); String regionName = DynamicPropertyFactory.getInstance().getStringProperty("turbine.region", "").get(); if (Strings.isNullOrEmpty(regionName)) { Region currentRegion = Regions.getCurrentRegion(); if (currentRegion != null) { regionName = currentRegion.getName(); } else {/* w w w .j av a2s .c o m*/ regionName = "us-east-1"; } } ec2Client.setRegion(Region.getRegion(Regions.fromName(regionName))); log.debug("Set the ec2 region to [{}]", regionName); }
From source file:com.boundary.aws.dynamodb.QueryDynamoDB.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 w w w . ja va 2s . co m*/ private static void init() throws Exception { /* * The ProfileCredentialsProvider will return your [default] credential * profile by reading from the credentials file located at * (/Users/davidg/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file." + e); } dynamoDB = new AmazonDynamoDBClient(credentials); Region usWest1 = Region.getRegion(Regions.US_WEST_1); dynamoDB.setRegion(usWest1); }
From source file:com.boundary.aws.kinesis.Sample.java
License:Open Source License
private static void init() throws Exception { /*/* ww w . j av a2 s .c om*/ * The ProfileCredentialsProvider will return your [default] credential * profile by reading from the credentials file located at * (HOME/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. ", e); } kinesisClient = new AmazonKinesisClient(credentials); Region region = Region.getRegion(Regions.US_WEST_2); kinesisClient.setRegion(region); }
From source file:com.boundary.aws.sqs.Sample.java
License:Open Source License
public static void main(String[] args) throws Exception { String queueName = "boundary-sqs-demo-queue"; /*/*from ww w. j a va 2s .c o m*/ * The ProfileCredentialsProvider will return your [default] credential * profile by reading from the credentials file located at * (HOME/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. ", e); } AmazonSQS sqs = new AmazonSQSClient(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); sqs.setRegion(usWest2); try { // Create a queue System.out.printf("Creating queue: %s.\n", queueName); CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); int messageCount = 100; // Send a messages for (int count = 1; count <= messageCount; count++) { System.out.printf("Sending message %3d to %s.\n", count, queueName); sqs.sendMessage(new SendMessageRequest(myQueueUrl, new Date() + ": This is my message text.")); } for (int count = 1; count <= messageCount; count++) { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message msg : messages) { System.out.printf("Received message: %s queue: %s body: %s\n", msg.getMessageId(), queueName, msg.getBody()); System.out.printf("Deleting message: %s queue: %s\n", msg.getMessageId(), queueName); String messageRecieptHandle = msg.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle)); } } System.out.printf("Deleting queue: %s\n", queueName); 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()); } sqs.shutdown(); }
From source file:com.boxupp.dao.AwsProjectDAOManager.java
License:Apache License
private String getPrivateHostName(String instanceID, String accessKeyId, String secretKey, String instanceRegion) {/* w ww . ja va2 s. c o m*/ String privateHostName = null; BasicAWSCredentials cred = new BasicAWSCredentials(accessKeyId, secretKey); AmazonEC2Client ec2Client = new AmazonEC2Client(cred); try { ec2Client.setRegion(Region.getRegion(Regions.fromName(instanceRegion))); ArrayList<String> instanceIds = new ArrayList<String>(); instanceIds.add(instanceID); DescribeInstancesRequest req = new DescribeInstancesRequest(); req.setInstanceIds(instanceIds); DescribeInstancesResult result = ec2Client.describeInstances(req); Instance instance = result.getReservations().get(0).getInstances().get(0); privateHostName = instance.getPrivateDnsName(); } catch (AmazonServiceException amazonServiceException) { logger.info("Error while fecthing instance info from aws " + amazonServiceException.getMessage()); } catch (Exception exception) { logger.info("Error while fecthing instance info from aws " + exception.getMessage()); } return privateHostName; }