List of usage examples for com.amazonaws AmazonServiceException getRequestId
public String getRequestId()
From source file:sqsAlertReceive.java
License:Open Source License
public static void main(String[] args) throws Exception { /*/*from w w w. j av a 2 s . co m*/ * The ProfileCredentialsProvider will return your [awsReilly] * credential profile by reading from the credentials file located at * (/Users/johnreilly/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("awsReilly").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/johnreilly/.aws/credentials), and is in valid format.", e); } AmazonSQS sqs = new AmazonSQSClient(credentials); Region usEast1 = Region.getRegion(Regions.US_EAST_1); sqs.setRegion(usEast1); String testQueue = "reillyInbound001"; System.out.println(""); System.out.println("==========================================="); System.out.println("Getting Started with sqsAlertReceive"); 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."); for (String queueUrl : sqs.listQueues().getQueueUrls()) { System.out.println("QueueUrl: " + queueUrl); } System.out.println(); // Receive messages System.out.println("Receiving messages from " + testQueue + "."); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(testQueue); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); System.out.println("Message count for " + testQueue + ": " + messages.size() + "\n"); 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(); // call a function to transform message // then send message to database persist queue System.out.println("Sending messages to alertsPersist.\n"); sqs.sendMessage(new SendMessageRequest("alertPersist", message.getBody())); // delete message after sending to persist queue System.out.println("Deleting message.\n"); String messageRecieptHandle = message.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(testQueue, messageRecieptHandle)); } } 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:PutTestFile.java
License:Apache License
public static void main(String[] args) throws IOException { /*/* w ww . j a v a 2 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( PutTestFile.class.getResourceAsStream("AwsCredentials.properties"))); String bucketName = "dtccTest"; String key = "largerfile.txt"; System.out.println("==========================================="); System.out.println("Getting Started with Amazon S3"); System.out.println("===========================================\n"); try { /* * List the buckets in your account */ System.out.println("Listing buckets"); for (Bucket bucket : s3.listBuckets()) { System.out.println(" - " + bucket.getName()); } System.out.println(); System.out.println("Uploading a new object to S3 from a file\n"); PutObjectRequest request = new PutObjectRequest(bucketName, key, createSampleFile()); request.setCannedAcl(CannedAccessControlList.PublicRead); s3.putObject(request); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, whichmeans your request made it " + "to Amazon S3, but was rejected with an errorresponse 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, whichmeans the client encountered " + "a serious internal problem while trying tocommunicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:ProductCategoryPriceIndex.java
License:Open Source License
public static void main(String[] args) throws Exception { init();/*from w w w .j av a 2s .c o m*/ try { String tableName = "product_cat_pi"; // Create table if it does not exist yet if (!Tables.doesTableExist(dynamoDB, tableName)) { System.out.println("Table " + tableName + " is does not exist"); } // 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("TV", 2, "TV Type one", "TV Type two"); PutItemRequest putItemRequest = new PutItemRequest(tableName, item); PutItemResult putItemResult = dynamoDB.putItem(putItemRequest); System.out.println("Result: " + putItemResult); } 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:SimpleQueueServiceMultiThread.java
License:Open Source License
@Override public Long call() throws Exception { Long transformTimeDiff = 0L;//from w ww . j ava2 s . c om long startDate = System.currentTimeMillis(); try { System.out.println("Sending a message to MyQueue.\n"); sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text.")); } 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()); } long endDate = System.currentTimeMillis(); transformTimeDiff = Long.valueOf(endDate - startDate); return transformTimeDiff; }
From source file:EBS_S3.java
License:Open Source License
public static void main(String[] args) throws Exception { AWSCredentials credentials = new PropertiesCredentials( EBS_S3.class.getResourceAsStream("AwsCredentials.properties")); /********************************************* * #1 Create Amazon Client object//w w w .j av a 2s . c o m **********************************************/ ec2 = new AmazonEC2Client(credentials); // We assume that we've already created an instance. Use the id of the instance. String instanceId = "i-278afe40"; //put your own instance id to test this code. try { /********************************************* * #2.1 Create a volume *********************************************/ // release System.out.println(ec2.describeVolumes()); List<Volume> v_list = ec2.describeVolumes().getVolumes(); System.out.println("Volume size: " + v_list.size()); DeleteVolumeRequest rq; for (Volume v : v_list) { if (v.getVolumeId().compareTo("vol-343dd879") != 0) { rq = new DeleteVolumeRequest(v.getVolumeId()); ec2.deleteVolume(rq); } } System.out.println(ec2.describeVolumes()); System.out.println("Volume size: " + v_list.size()); //create a volume System.out.println("2.1 Create a volume"); CreateVolumeRequest cvr = new CreateVolumeRequest(); cvr.setAvailabilityZone("us-east-1b"); cvr.setSize(10); //size = 10 gigabytes CreateVolumeResult volumeResult = ec2.createVolume(cvr); String createdVolumeId = volumeResult.getVolume().getVolumeId(); System.out.println("Created Volume ID: " + createdVolumeId); /********************************************* * #2.2 Attach the volume to the instance *********************************************/ System.out.println("2.2 Attach the volume to the instance"); Thread.sleep(30000); AttachVolumeRequest avr = new AttachVolumeRequest(); avr.setVolumeId(createdVolumeId); avr.setInstanceId(instanceId); avr.setDevice("/dev/sdf"); ec2.attachVolume(avr); /********************************************* * #2.3 Detach the volume from the instance *********************************************/ System.out.println("2.3 Detach the volume from the instance"); DetachVolumeRequest dvr = new DetachVolumeRequest(); dvr.setVolumeId(createdVolumeId); dvr.setInstanceId(instanceId); ec2.detachVolume(dvr); /************************************************ * #3 S3 bucket and object ***************************************************/ System.out.println("3 S3 bucket and object"); s3 = new AmazonS3Client(credentials); //create bucket String bucketName = "cloud-xiangyao-bucket"; s3.createBucket(bucketName); //set key String key = "object-name.txt"; //set value File file = File.createTempFile("temp", ".txt"); file.deleteOnExit(); Writer writer = new OutputStreamWriter(new FileOutputStream(file)); writer.write("This is a sample sentence.\r\nYes!"); writer.close(); //put object - bucket, key, value(file) s3.putObject(new PutObjectRequest(bucketName, key, file)); //get object S3Object object = s3.getObject(new GetObjectRequest(bucketName, key)); BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent())); String data = null; while ((data = reader.readLine()) != null) { System.out.println(data); } /********************************************* * #4 shutdown client object *********************************************/ System.out.println("4 shutdown client object"); ec2.shutdown(); s3.shutdown(); } 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()); } }
From source file:NYSEQuery.java
License:Open Source License
private static void query(String tableName) { Table table = null;/*from www .jav a2 s .com*/ try { // Create table if it does not exist yet if (!Tables.doesTableExist(dynamoDB, tableName)) { System.out.println("Table " + tableName + " is does not exist"); } else { table = dynamo.getTable(tableName); } // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html // select stockTicker, tradeDate, v from stock_eod // where stockTicker = 'LEA' and tradeDate between '02-Oct-2013' and '03-Oct-2013' QuerySpec spec = new QuerySpec().withProjectionExpression("stockTicker,tradeDate,v") .withKeyConditionExpression("stockTicker = :v_st and tradeDate between :v_sd and :v_ed") // .withFilterExpression("contains(tradeDate, :v_t)") .withValueMap(new ValueMap().withString(":v_st", "LEA").withString(":v_sd", "02-Oct-2013") .withString(":v_ed", "03-Oct-2013") // .withString(":v_td", "01-Oct-2013") // .withString(":v_t", "Oct") ).withConsistentRead(true); ItemCollection<QueryOutcome> items = table.query(spec); Iterator<Item> iterator = items.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().toJSONPretty()); } } 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:AmazonDynamoDBPopulator.java
License:Open Source License
public static void main(String[] args) throws Exception { init();//from w w w .jav a2 s . c om try { //The methods below are commented but any of them will be used to refresh the AmazonDynamo DB database when the data changes. //New Data sets will be added in the same fashion. //populateDataVersions(); //populateBloodBanks(); //populateAutoFare(); //populateTaxiFare(); //populateHelplines(); // SAMPLE SCAN FUNCTION - Scan items for bloodbanks in a particular area /*HashMap<String, Condition> scanFilter = new HashMap<String, Condition>(); Condition condition = new Condition() .withComparisonOperator(ComparisonOperator.EQ.toString()) .withAttributeValueList(new AttributeValue().withS("Parel")); scanFilter.put("AREA", condition); ScanRequest scanRequest = new ScanRequest(BLOODBANK_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:SimpleDBSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*//w w w . ja v a 2 s . co 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 */ AmazonSimpleDB sdb = new AmazonSimpleDBClient( new PropertiesCredentials(SimpleDBSample.class.getResourceAsStream("AwsCredentials.properties"))); System.out.println("==========================================="); System.out.println("Getting Started with Amazon SimpleDB"); System.out.println("===========================================\n"); try { // Create a domain String myDomain = "MyStore"; System.out.println("Creating domain called " + myDomain + ".\n"); sdb.createDomain(new CreateDomainRequest(myDomain)); // 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 " + myDomain + " domain.\n"); sdb.batchPutAttributes(new BatchPutAttributesRequest(myDomain, createSampleData())); // Select data from a domain // Notice the use of backticks around the domain name in our select expression. String selectExpression = "select * from `" + myDomain + "` 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(myDomain, "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(myDomain, "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(myDomain, "Item_03", replaceableAttributes)); // Delete an item and all of its attributes System.out.println("Deleting Item_03.\n"); sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "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:AwsSample.java
License:Open Source License
public static void main(String[] args) throws Exception { BasicAWSCredentials credentials = new BasicAWSCredentials("", ""); /********************************************* * /*w w w .j a v a2 s . c om*/ * #1 Create Amazon Client object * *********************************************/ System.out.println("#1 Create Amazon Client object"); ec2 = new AmazonEC2Client(credentials); try { /********************************************* * * #2 Describe Availability Zones. * *********************************************/ System.out.println("#2 Describe Availability Zones."); DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones(); System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() + " Availability Zones."); /********************************************* * * #3 Describe Available Images * *********************************************/ System.out.println("#3 Describe Available Images"); DescribeImagesResult dir = ec2.describeImages(); List<Image> images = dir.getImages(); System.out.println("You have " + images.size() + " Amazon images"); /********************************************* * * #4 Describe Key Pair * *********************************************/ System.out.println("#9 Describe Key Pair"); DescribeKeyPairsResult dkr = ec2.describeKeyPairs(); System.out.println(dkr.toString()); /********************************************* * * #5 Describe Current Instances * *********************************************/ System.out.println("#4 Describe Current Instances"); DescribeInstancesResult describeInstancesRequest = ec2.describeInstances(); List<Reservation> reservations = describeInstancesRequest.getReservations(); Set<Instance> instances = new HashSet<Instance>(); // add all instances to a Set. for (Reservation reservation : reservations) { instances.addAll(reservation.getInstances()); } System.out.println("You have " + instances.size() + " Amazon EC2 instance(s)."); for (Instance ins : instances) { // instance id String instanceId = ins.getInstanceId(); // instance state InstanceState is = ins.getState(); System.out.println(instanceId + " " + is.getName()); } /////////////////////////////////////// String Temp_Group = "Testgroup1"; //name of the group CreateSecurityGroupRequest r1 = new CreateSecurityGroupRequest(Temp_Group, "temporal group"); ec2.createSecurityGroup(r1); AuthorizeSecurityGroupIngressRequest r2 = new AuthorizeSecurityGroupIngressRequest(); r2.setGroupName(Temp_Group); /*************the property of http*****************/ IpPermission permission = new IpPermission(); permission.setIpProtocol("tcp"); permission.setFromPort(80); permission.setToPort(80); List<String> ipRanges = new ArrayList<String>(); ipRanges.add("0.0.0.0/0"); permission.setIpRanges(ipRanges); /*************the property of SSH**********************/ IpPermission permission1 = new IpPermission(); permission1.setIpProtocol("tcp"); permission1.setFromPort(22); permission1.setToPort(22); List<String> ipRanges1 = new ArrayList<String>(); ipRanges1.add("0.0.0.0/22"); permission1.setIpRanges(ipRanges1); /*************the property of https**********************/ IpPermission permission2 = new IpPermission(); permission2.setIpProtocol("tcp"); permission2.setFromPort(443); permission2.setToPort(443); List<String> ipRanges2 = new ArrayList<String>(); ipRanges2.add("0.0.0.0/0"); permission2.setIpRanges(ipRanges2); /*************the property of tcp**********************/ IpPermission permission3 = new IpPermission(); permission3.setIpProtocol("tcp"); permission3.setFromPort(0); permission3.setToPort(65535); List<String> ipRanges3 = new ArrayList<String>(); ipRanges3.add("0.0.0.0/0"); permission3.setIpRanges(ipRanges3); /**********************add rules to the group*********************/ List<IpPermission> permissions = new ArrayList<IpPermission>(); permissions.add(permission); permissions.add(permission1); permissions.add(permission2); permissions.add(permission3); r2.setIpPermissions(permissions); ec2.authorizeSecurityGroupIngress(r2); List<String> groupName = new ArrayList<String>(); groupName.add(Temp_Group);//wait to out our instance into this group /********************************************* * * #6.2 Create a New Key Pair * *********************************************/ CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest(); newKeyRequest.setKeyName("Test_Key2"); CreateKeyPairResult keyresult = ec2.createKeyPair(newKeyRequest); /************************print the properties of this key*****************/ KeyPair kp = new KeyPair(); kp = keyresult.getKeyPair(); System.out.println("The key we created is = " + kp.getKeyName() + "\nIts fingerprint is=" + kp.getKeyFingerprint() + "\nIts material is= \n" + kp.getKeyMaterial()); String fileName = "C:/Users/Akhil/workspace/Test_Key2.pem"; File distFile = new File(fileName); BufferedReader bufferedReader = new BufferedReader(new StringReader(kp.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(); //String myinstance; /********************************************* * * #6 Create an Instance * *********************************************/ System.out.println("#5 Create an Instance"); String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI int minInstanceCount = 1; // create 1 instance int maxInstanceCount = 1; RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount); rir.setKeyName("Test_Key2"); rir.withSecurityGroups("Testgroup1"); RunInstancesResult result = ec2.runInstances(rir); //get instanceId from the result List<Instance> resultInstance = result.getReservation().getInstances(); String createdInstanceId = null; String myAvailabilityZone = null; for (Instance ins : resultInstance) { createdInstanceId = ins.getInstanceId(); System.out.println("New instance has been created: " + ins.getInstanceId()); //myinstance = ins.getInstanceId(); } Thread.currentThread().sleep(60000); /********************************************* * * * Create a New Volume and attach it * ***********************************************/ List<Instance> resultInstance2 = result.getReservation().getInstances(); createdInstanceId = null; for (Instance ins : resultInstance2) { createdInstanceId = ins.getInstanceId(); System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID /********************************************* * * #6.4 Create an Instance * *********************************************/ CreateVolumeRequest newVol = new CreateVolumeRequest(1, "us-east-1a"); CreateVolumeResult volresult = ec2.createVolume(newVol); Volume vol1 = volresult.getVolume(); String volId = vol1.getVolumeId(); Thread.currentThread().sleep(30000); AttachVolumeRequest attachRequest = new AttachVolumeRequest().withInstanceId(createdInstanceId) .withVolumeId(volId); attachRequest.withDevice("/dev/sda5"); ec2.attachVolume(attachRequest); System.out.println("EBS volume has been attached and the volume ID is: " + volId); } /********************************************* * * #7 Create a 'tag' for the new instance. * *********************************************/ System.out.println("#6 Create a 'tag' for the new instance."); List<String> resources = new LinkedList<String>(); List<Tag> tags = new LinkedList<Tag>(); Tag nameTag = new Tag("Akhil", "MyFirstInstance"); resources.add(createdInstanceId); tags.add(nameTag); CreateTagsRequest ctr = new CreateTagsRequest(resources, tags); ec2.createTags(ctr); /********************************************* * * #8 Stop/Start an Instance * *********************************************/ System.out.println("#7 Stop the Instance"); List<String> instanceIds = new LinkedList<String>(); instanceIds.add(createdInstanceId); //stop StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds); ec2.stopInstances(stopIR); //start StartInstancesRequest startIR = new StartInstancesRequest(instanceIds); ec2.startInstances(startIR); System.out.println("#8 Getting DNS, IP."); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(instanceIds); DescribeInstancesResult result1 = ec2.describeInstances(request); List<Reservation> reservations1 = result1.getReservations(); List<Instance> instances1; for (Reservation res : reservations1) { instances1 = res.getInstances(); for (Instance ins1 : instances1) { System.out .println("The public DNS is: " + ins1.getPublicDnsName() + "\n" + ins1.getRamdiskId()); System.out.println("The private IP is: " + ins1.getPrivateIpAddress()); System.out.println("The public IP is: " + ins1.getPublicIpAddress()); } /********************************************* * #10 Terminate an Instance * *********************************************/ System.out.println("#8 Terminate the Instance"); TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds); //ec2.terminateInstances(tir); /********************************************* * * #11 shutdown client object * *********************************************/ ec2.shutdown(); } } 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()); } }
From source file:AwsConsoleApp.java
License:Open Source License
public static void main(String[] args) throws Exception { System.out.println("==========================================="); System.out.println("Welcome to the AWS Java SDK!"); System.out.println("==========================================="); init();/*from w w w . java 2s .co m*/ /* * Amazon EC2 * * The AWS EC2 client allows you to create, delete, and administer * instances programmatically. * * In this sample, we use an EC2 client to get a list of all the * availability zones, and all instances sorted by reservation id. */ try { DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones(); System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() + " Availability Zones."); DescribeInstancesResult describeInstancesRequest = ec2.describeInstances(); List<Reservation> reservations = describeInstancesRequest.getReservations(); Set<Instance> instances = new HashSet<Instance>(); for (Reservation reservation : reservations) { instances.addAll(reservation.getInstances()); } System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running."); } 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()); } /* * Amazon SimpleDB * * The AWS SimpleDB client allows you to query and manage your data * stored in SimpleDB domains (similar to tables in a relational DB). * * In this sample, we use a SimpleDB client to iterate over all the * domains owned by the current user, and add up the number of items * (similar to rows of data in a relational DB) in each domain. */ try { ListDomainsRequest sdbRequest = new ListDomainsRequest().withMaxNumberOfDomains(100); ListDomainsResult sdbResult = sdb.listDomains(sdbRequest); int totalItems = 0; for (String domainName : sdbResult.getDomainNames()) { DomainMetadataRequest metadataRequest = new DomainMetadataRequest().withDomainName(domainName); DomainMetadataResult domainMetadata = sdb.domainMetadata(metadataRequest); totalItems += domainMetadata.getItemCount(); } System.out.println("You have " + sdbResult.getDomainNames().size() + " Amazon SimpleDB domain(s)" + "containing a total of " + totalItems + " items."); } 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()); } /* * Amazon S3 * * The AWS S3 client allows you to manage buckets and programmatically * put and get objects to those buckets. * * In this sample, we use an S3 client to iterate over all the buckets * owned by the current user, and all the object metadata in each * bucket, to obtain a total object and space usage count. This is done * without ever actually downloading a single object -- the requests * work with object metadata only. */ try { List<Bucket> buckets = s3.listBuckets(); long totalSize = 0; int totalItems = 0; for (Bucket bucket : buckets) { /* * In order to save bandwidth, an S3 object listing does not * contain every object in the bucket; after a certain point the * S3ObjectListing is truncated, and further pages must be * obtained with the AmazonS3Client.listNextBatchOfObjects() * method. */ ObjectListing objects = s3.listObjects(bucket.getName()); do { for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) { totalSize += objectSummary.getSize(); totalItems++; } objects = s3.listNextBatchOfObjects(objects); } while (objects.isTruncated()); } System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s), " + "containing " + totalItems + " objects with a total size of " + totalSize + " bytes."); } catch (AmazonServiceException ase) { /* * AmazonServiceExceptions represent an error response from an AWS * services, i.e. your request made it to AWS, but the AWS service * either found it invalid or encountered an error trying to execute * it. */ 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) { /* * AmazonClientExceptions represent an error that occurred inside * the client on the local host, either while trying to send the * request to AWS or interpret the response. For example, if no * network connection is available, the client won't be able to * connect to AWS to execute a request and will throw an * AmazonClientException. */ System.out.println("Error Message: " + ace.getMessage()); } }