List of usage examples for com.amazonaws AmazonServiceException getStatusCode
public int getStatusCode()
From source file:aws.sample.SimpleQueueServiceSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*// w w w.ja v a2 s .c o m * Important: Be sure to fill in your AWS access credentials in the AwsCredentials.properties file before you try to run this sample. http://aws.amazon.com/security-credentials */ AmazonSQS sqs = new AmazonSQSClient(new PropertiesCredentials( SimpleQueueServiceSample.class.getResourceAsStream("/AwsCredentials.properties"))); 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, "This is my message 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 messageRecieptHandle = messages.get(0).getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle)); // 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:awslabs.labutility.LabUtility.java
License:Open Source License
public static void dumpError(Exception ex) { if (ex instanceof AmazonServiceException) { AmazonServiceException ase = (AmazonServiceException) ex; System.out.println();/*from ww w . ja v a 2s.c o m*/ System.out.println("Caught an AmazonServiceException, which means your request made it AWS,"); System.out.println("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()); System.out.println("Stack trace:"); ase.printStackTrace(); } else if (ex instanceof AmazonClientException) { AmazonClientException ace = (AmazonClientException) ex; System.out.println(); System.out.println("Caught an AmazonClientException, which means the client encountered"); System.out.println("a problem without before communicating with the service."); System.out.println("Error Message: " + ace.getMessage()); System.out.println("Stack trace:"); ace.printStackTrace(); } else { System.out.println(); System.out.println("Caught exception [" + ex.getClass() + "]."); System.out.println("Error Message: " + ex.getMessage()); System.out.println("Cause: " + ex.getCause()); System.out.println("Stack trace:"); ex.printStackTrace(); } }
From source file:beanstalk.BeanstalkDeployNoGUI.java
License:Apache License
public void upload_file_to_s3(String bucketName, String keyName, String uploadFileName, String AWSKeyId, String AWSSecretKey) throws BeanstalkAdapterException { BasicAWSCredentials basic_credentials = new BasicAWSCredentials(AWSKeyId, AWSSecretKey); AmazonS3 s3client = new AmazonS3Client(basic_credentials); try {//w w w . j ava 2 s . c o m System.out.println("Uploading a new object to S3 from a file\n"); File file = new File(uploadFileName); s3client.putObject(new PutObjectRequest(bucketName, keyName, file)); } 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()); throw new BeanstalkAdapterException(ase.getMessage()); } 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()); throw new BeanstalkAdapterException(ace.getMessage()); } }
From source file:beanstalk.BeanstalkFirstDeploymentNoGUI.java
License:Apache License
public void upload_file_to_s3(String bucketName, String keyName, String uploadFileName, String AWSKeyId, String AWSSecretKey) throws BeanstalkAdapterException { BasicAWSCredentials basic_credentials = new BasicAWSCredentials(AWSKeyId, AWSSecretKey); AmazonS3 s3client = new AmazonS3Client(basic_credentials); try {//from www .jav a 2 s .co m System.out.println("Uploading a new object to S3 from a file\n"); File file = new File(uploadFileName); s3client.putObject(new PutObjectRequest(bucketName, keyName, file)); } 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()); throw new BeanstalkAdapterException(ase.getMessage()); } 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()); throw new BeanstalkAdapterException(ace.getMessage()); } }
From source file:bench.auth.SimpleDBSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*/*from w w w . j a v a 2s . com*/ * Important: Be sure to fill in your AWS access credentials in the * AwsCredentials.properties file before you try to run this sample. * http://aws.amazon.com/security-credentials */ String home = System.getProperty("user.home"); String props = home + "/.amazon/AwsCredentials.properties"; System.out.println("props = " + props); URL url = new File(props).toURI().toURL(); System.out.println("url = " + url); final AWSCredentials credentials = new PropertiesCredentials(url.openStream()); final AmazonSimpleDB sdb = new AmazonSimpleDBClient(credentials); System.out.println("==========================================="); System.out.println("Getting Started with Amazon SimpleDB"); System.out.println("===========================================\n"); try { // Create a domain String domain = "domain-tester"; System.out.println("Creating domain called " + domain + ".\n"); sdb.createDomain(new CreateDomainRequest(domain)); // List domains System.out.println("Listing all domains in your account:\n"); for (String domainName : sdb.listDomains().getDomainNames()) { System.out.println(" " + domainName); } System.out.println(); // Put data into a domain System.out.println("Putting data into " + domain + " domain.\n"); sdb.batchPutAttributes( // new BatchPutAttributesRequest(domain, createSampleData())); // Select data from a domain // Notice the use of backticks around the domain name in our select // expression. String selectExpression = // "select * from `" + domain + "` where Category = 'Clothes'"; System.out.println("Selecting: " + selectExpression + "\n"); SelectRequest selectRequest = new SelectRequest(selectExpression); for (Item item : sdb.select(selectRequest).getItems()) { System.out.println(" Item"); System.out.println(" Name: " + item.getName()); for (Attribute attribute : item.getAttributes()) { System.out.println(" Attribute"); System.out.println(" Name: " + attribute.getName()); System.out.println(" Value: " + attribute.getValue()); } } System.out.println(); // Delete values from an attribute System.out.println("Deleting Blue attributes in Item_O3.\n"); Attribute deleteValueAttribute = new Attribute("Color", "Blue"); sdb.deleteAttributes( new DeleteAttributesRequest(domain, "Item_03").withAttributes(deleteValueAttribute)); // Delete an attribute and all of its values System.out.println("Deleting attribute Year in Item_O3.\n"); sdb.deleteAttributes(new DeleteAttributesRequest(domain, "Item_03") .withAttributes(new Attribute().withName("Year"))); // Replace an attribute System.out.println("Replacing Size of Item_03 with Medium.\n"); List<ReplaceableAttribute> replaceableAttributes = new ArrayList<ReplaceableAttribute>(); replaceableAttributes.add(new ReplaceableAttribute("Size", "Medium", true)); sdb.putAttributes(new PutAttributesRequest(domain, "Item_03", replaceableAttributes)); // Delete an item and all of its attributes System.out.println("Deleting Item_03.\n"); sdb.deleteAttributes(new DeleteAttributesRequest(domain, "Item_03")); // Delete a domain // System.out.println("Deleting " + myDomain + " domain.\n"); // sdb.deleteDomain(new DeleteDomainRequest(myDomain)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SimpleDB, 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 SimpleDB, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:br.com.faccilitacorretor.middleware.dynamo.AmazonDynamoDBSample.java
License:Open Source License
public static void main(String[] args) throws Exception { init();/* w w w .j av a2s . c o m*/ try { String tableName = "my-favorite-movies-table"; // Create table if it does not exist yet if (Tables.doesTableExist(dynamoDB, tableName)) { System.out.println("Table " + tableName + " is already ACTIVE"); } else { // Create a table with a primary hash key named 'name', which holds a string CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name") .withAttributeType(ScalarAttributeType.S)) .withProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)); TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest) .getTableDescription(); System.out.println("Created Table: " + createdTableDescription); // Wait for it to become active System.out.println("Waiting for " + tableName + " to become ACTIVE..."); Tables.awaitTableToBecomeActive(dynamoDB, tableName); } // Describe our new table DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName); TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable(); System.out.println("Table Description: " + tableDescription); // Add an item Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James", "Sara"); PutItemRequest putItemRequest = new PutItemRequest(tableName, item); PutItemResult putItemResult = dynamoDB.putItem(putItemRequest); System.out.println("Result: " + putItemResult); // Add another item item = newItem("Airplane", 1980, "*****", "James", "Billy Bob"); putItemRequest = new PutItemRequest(tableName, item); putItemResult = dynamoDB.putItem(putItemRequest); System.out.println("Result: " + putItemResult); // Scan items for movies with a year attribute greater than 1985 HashMap<String, Condition> scanFilter = new HashMap<String, Condition>(); Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withN("1985")); scanFilter.put("year", condition); ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter); ScanResult scanResult = dynamoDB.scan(scanRequest); System.out.println("Result: " + scanResult); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS, 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 AWS, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:br.com.tamandua.aws.S3Sample.java
License:Open Source License
public static void main(String[] args) throws IOException { /*/* www . ja v a2 s . c o m*/ * Important: Be sure to fill in your AWS access credentials in the * AwsCredentials.properties file before you try to run this * sample. * http://aws.amazon.com/security-credentials */ AmazonS3 s3 = new AmazonS3Client( new PropertiesCredentials(S3Sample.class.getResourceAsStream("AwsCredentials.properties"))); String bucketName = "test-bucket-everton-" + UUID.randomUUID(); String key = "somekey"; 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("some")); 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:br.com.unb.aws.client.S3ClientV1.java
License:Open Source License
public static void main(String[] args) throws IOException { /*// w w w. j ava2s. c o m * Create your credentials file at ~/.aws/credentials (C:\Users\USER_NAME\.aws\credentials for Windows users) * and save the following lines after replacing the underlined values with your own. * * [default] * aws_access_key_id = YOUR_ACCESS_KEY_ID * aws_secret_access_key = YOUR_SECRET_ACCESS_KEY */ AmazonS3 s3 = new AmazonS3Client(); 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:br.unb.cic.bionimbuz.elasticity.legacy.Ec2Commands.java
License:Open Source License
public static void createinstance() throws IOException { Ec2Commands.setup();/*from w w w . ja v a2 s . c om*/ try { System.out.println("Criando nova maquina BioninbuZ"); String imageId; System.out.println("Enter the image AMI id (eg: ami-687b4f2d)"); imageId = user_input.next(); int minInstanceCount = 1; // int maxInstanceCount = 1; RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount); rir.setInstanceType("t1.micro"); Scanner keyscan = new Scanner(System.in); System.out.println("Do you want to use an existing keypair or do you want to create a new one?"); System.out.println("#1 Use existing keypair"); System.out.println("#2 Create a new keypair"); int keypairoption; String key; //existing keypair name keypairoption = keyscan.nextInt(); if (keypairoption == 1) { System.out.println("Enter the existing keypair name to use with the new instance"); key = keyscan.next(); rir.withKeyName(key); } else if (keypairoption == 2) { //count++; System.out.println("Enter the keypair name to create"); String newkeyname; newkeyname = keyscan.next(); CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest(); newKeyRequest.setKeyName(newkeyname); CreateKeyPairResult keyresult = EC2.createKeyPair(newKeyRequest); keyPair = keyresult.getKeyPair(); System.out.println("The key we created is = " + keyPair.getKeyName() + "\nIts fingerprint is=" + keyPair.getKeyFingerprint() + "\nIts material is= \n" + keyPair.getKeyMaterial()); System.out.println( "Enter the directory to store .pem file (eg: Windows C:\\Users\\user\\Desktop\\, Linux /user/home)"); String dir; dir = keyscan.next(); String fileName = dir + newkeyname + ".pem"; File distFile = new File(fileName); BufferedReader bufferedReader = new BufferedReader(new StringReader(keyPair.getKeyMaterial())); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile)); char buf[] = new char[1024]; int len; while ((len = bufferedReader.read(buf)) != -1) { bufferedWriter.write(buf, 0, len); } bufferedWriter.flush(); bufferedReader.close(); bufferedWriter.close(); } rir.withSecurityGroups("default"); RunInstancesResult result = EC2.runInstances(rir); System.out.println("waiting"); try { Thread.sleep(50000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("OK"); List<Instance> resultInstance = result.getReservation().getInstances(); String createdInstanceId = null; for (Instance ins : resultInstance) { createdInstanceId = ins.getInstanceId(); System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID } try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(); System.out.println("Restarting the application"); System.out.println(); // Ec2Commands.enteroption(); } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); System.out.println("Give a valid input"); System.out.println(""); // Ec2Commands.enteroption(); } }
From source file:br.unb.cic.bionimbuz.services.elasticity.Ec2Commands.java
License:Open Source License
public static void createinstance() throws IOException { Ec2Commands.setup();//w w w. j a va 2 s.co m try { System.out.println("Criando nova maquina BioninbuZ"); String imageId; System.out.println("Enter the image AMI id (eg: ami-687b4f2d)"); imageId = user_input.next(); int minInstanceCount = 1; // int maxInstanceCount = 1; RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount); rir.setInstanceType("t1.micro"); try (Scanner keyscan = new Scanner(System.in)) { System.out.println("Do you want to use an existing keypair or do you want to create a new one?"); System.out.println("#1 Use existing keypair"); System.out.println("#2 Create a new keypair"); int keypairoption; String key; //existing keypair name keypairoption = keyscan.nextInt(); if (keypairoption == 1) { System.out.println("Enter the existing keypair name to use with the new instance"); key = keyscan.next(); rir.withKeyName(key); } else if (keypairoption == 2) { //count++; System.out.println("Enter the keypair name to create"); String newkeyname; newkeyname = keyscan.next(); CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest(); newKeyRequest.setKeyName(newkeyname); CreateKeyPairResult keyresult = EC2.createKeyPair(newKeyRequest); keyPair = keyresult.getKeyPair(); System.out.println("The key we created is = " + keyPair.getKeyName() + "\nIts fingerprint is=" + keyPair.getKeyFingerprint() + "\nIts material is= \n" + keyPair.getKeyMaterial()); System.out.println( "Enter the directory to store .pem file (eg: Windows C:\\Users\\user\\Desktop\\, Linux /user/home)"); String dir; dir = keyscan.next(); String fileName = dir + newkeyname + ".pem"; File distFile = new File(fileName); BufferedReader bufferedReader = new BufferedReader(new StringReader(keyPair.getKeyMaterial())); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile)); char buf[] = new char[1024]; int len; while ((len = bufferedReader.read(buf)) != -1) { bufferedWriter.write(buf, 0, len); } bufferedWriter.flush(); bufferedReader.close(); bufferedWriter.close(); } } rir.withSecurityGroups("default"); RunInstancesResult result = EC2.runInstances(rir); System.out.println("waiting"); try { Thread.sleep(50000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("OK"); List<Instance> resultInstance = result.getReservation().getInstances(); String createdInstanceId = null; for (Instance ins : resultInstance) { createdInstanceId = ins.getInstanceId(); System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID } try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(); System.out.println("Restarting the application"); System.out.println(); // Ec2Commands.enteroption(); } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); System.out.println("Give a valid input"); System.out.println(""); // Ec2Commands.enteroption(); } }