List of usage examples for com.amazonaws AmazonServiceException getRequestId
public String getRequestId()
From source file:CloudFormation.java
License:Open Source License
public static void main(String[] args) throws Exception { /*/* w w w .j av a 2 s . co m*/ * This credentials provider implementation loads your AWS credentials * from a properties file at the root of your classpath. * 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 */ AmazonCloudFormation stackbuilder = new AmazonCloudFormationClient( new ClasspathPropertiesFileCredentialsProvider()); Region usWest2 = Region.getRegion(Regions.US_EAST_1); stackbuilder.setRegion(usWest2); System.out.println("==========================================="); System.out.println("Getting Started with AWS CloudFormation"); System.out.println("===========================================\n"); String stackName = "CloudFormationSampleStack"; String logicalResourceName = "SampleNotificationTopic"; try { // Create a stack CreateStackRequest createRequest = new CreateStackRequest(); createRequest.setStackName(stackName); createRequest.setTemplateBody( convertStreamToString(CloudFormation.class.getResourceAsStream("CloudFormation.template"))); System.out.println("Creating a stack called " + createRequest.getStackName() + "."); stackbuilder.createStack(createRequest); // Wait for stack to be created // Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation System.out.println("Stack creation completed, the stack " + stackName + " completed with " + waitForCompletion(stackbuilder, stackName)); // Show all the stacks for this account along with the resources for each stack for (Stack stack : stackbuilder.describeStacks(new DescribeStacksRequest()).getStacks()) { System.out.println( "Stack : " + stack.getStackName() + " [" + stack.getStackStatus().toString() + "]"); DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest(); stackResourceRequest.setStackName(stack.getStackName()); for (StackResource resource : stackbuilder.describeStackResources(stackResourceRequest) .getStackResources()) { System.out.format(" %1$-40s %2$-25s %3$s\n", resource.getResourceType(), resource.getLogicalResourceId(), resource.getPhysicalResourceId()); } } // Lookup a resource by its logical name DescribeStackResourcesRequest logicalNameResourceRequest = new DescribeStackResourcesRequest(); logicalNameResourceRequest.setStackName(stackName); logicalNameResourceRequest.setLogicalResourceId(logicalResourceName); System.out.format("Looking up resource name %1$s from stack %2$s\n", logicalNameResourceRequest.getLogicalResourceId(), logicalNameResourceRequest.getStackName()); for (StackResource resource : stackbuilder.describeStackResources(logicalNameResourceRequest) .getStackResources()) { System.out.format(" %1$-40s %2$-25s %3$s\n", resource.getResourceType(), resource.getLogicalResourceId(), resource.getPhysicalResourceId()); } // Delete the stack DeleteStackRequest deleteRequest = new DeleteStackRequest(); deleteRequest.setStackName(stackName); System.out.println("Deleting the stack called " + deleteRequest.getStackName() + "."); stackbuilder.deleteStack(deleteRequest); // Wait for stack to be deleted // Note that you could used SNS notifications on the original CreateStack call to track the progress of the stack deletion System.out.println("Stack creation completed, the stack " + stackName + " completed with " + waitForCompletion(stackbuilder, stackName)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS CloudFormation, 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 CloudFormation, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:AmazonS3Handler.java
License:Open Source License
public void putObject(File file, String key) throws IOException { try {//from w w w . j a va2s . com // System.out.println("Creating bucket " + bucketName + "\n"); // s3.createBucket(bucketName); // 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"); s3.putObject( new PutObjectRequest(bucketName, key, file).withCannedAcl(CannedAccessControlList.PublicRead)); } 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:AmazonS3Handler.java
License:Open Source License
public void listObject() { try {/*from ww w. j a v a2 s .c o m*/ // System.out.println("Creating bucket " + bucketName + "\n"); // s3.createBucket(bucketName); // 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"); // s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()).withCannedAcl(CannedAccessControlList.PublicRead)); // 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()); 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(); // System.out.println("Deleting an object\n"); // s3.deleteObject(bucketName, key); // 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:CloudFormationSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*/*ww w. jav 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 */ AmazonCloudFormation stackbuilder = new AmazonCloudFormationClient(new PropertiesCredentials( CloudFormationSample.class.getResourceAsStream("AwsCredentials.properties"))); System.out.println("==========================================="); System.out.println("Getting Started with AWS CloudFormation"); System.out.println("===========================================\n"); String stackName = "CloudFormationSampleStack"; String logicalResourceName = "SampleNotificationTopic"; try { // Create a stack CreateStackRequest createRequest = new CreateStackRequest(); createRequest.setStackName(stackName); createRequest.setTemplateBody(convertStreamToString( CloudFormationSample.class.getResourceAsStream("CloudFormationSample.template"))); System.out.println("Creating a stack called " + createRequest.getStackName() + "."); stackbuilder.createStack(createRequest); // Wait for stack to be created // Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation System.out.println("Stack creation completed, the stack " + stackName + " completed with " + waitForCompletion(stackbuilder, stackName)); // Show all the stacks for this account along with the resources for each stack for (Stack stack : stackbuilder.describeStacks(new DescribeStacksRequest()).getStacks()) { System.out.println( "Stack : " + stack.getStackName() + " [" + stack.getStackStatus().toString() + "]"); DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest(); stackResourceRequest.setStackName(stack.getStackName()); for (StackResource resource : stackbuilder.describeStackResources(stackResourceRequest) .getStackResources()) { System.out.format(" %1$-40s %2$-25s %3$s\n", resource.getResourceType(), resource.getLogicalResourceId(), resource.getPhysicalResourceId()); } } // Lookup a resource by its logical name DescribeStackResourcesRequest logicalNameResourceRequest = new DescribeStackResourcesRequest(); logicalNameResourceRequest.setStackName(stackName); logicalNameResourceRequest.setLogicalResourceId(logicalResourceName); System.out.format("Looking up resource name %1$s from stack %2$s\n", logicalNameResourceRequest.getLogicalResourceId(), logicalNameResourceRequest.getStackName()); for (StackResource resource : stackbuilder.describeStackResources(logicalNameResourceRequest) .getStackResources()) { System.out.format(" %1$-40s %2$-25s %3$s\n", resource.getResourceType(), resource.getLogicalResourceId(), resource.getPhysicalResourceId()); } // Delete the stack DeleteStackRequest deleteRequest = new DeleteStackRequest(); deleteRequest.setStackName(stackName); System.out.println("Deleting the stack called " + deleteRequest.getStackName() + "."); stackbuilder.deleteStack(deleteRequest); // Wait for stack to be deleted // Note that you could used SNS notifications on the original CreateStack call to track the progress of the stack deletion System.out.println("Stack creation completed, the stack " + stackName + " completed with " + waitForCompletion(stackbuilder, stackName)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS CloudFormation, 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 CloudFormation, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:Uploader.java
License:Open Source License
private static void uploadFile(AmazonS3 s3, String bucketName, String key, File file) { if (!file.exists()) { System.out.println("File does not exist: " + file.getAbsolutePath()); return;/*w ww.ja v a 2s. c o m*/ } /* * 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. */ try { System.out.println(file.getAbsolutePath() + " ---> " + key + "\n"); s3.putObject(new PutObjectRequest(bucketName, key, file)); // Change permissions. Grant all users the read permission. AccessControlList acl = s3.getObjectAcl(bucketName, key); Permission permission = Permission.Read; Grantee grantee = GroupGrantee.AllUsers; acl.grantPermission(grantee, permission); s3.setObjectAcl(bucketName, key, acl); } 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:RandomQuery2OnDynamoDB.java
License:Open Source License
public static void main(String[] args) throws Exception { init();/* w w w .j a v a 2s .co m*/ try { // Describe our new table DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName); TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable(); System.out.println("Table Description: " + tableDescription); long lStartTime = new Date().getTime(); System.out.println("start time: " + lStartTime); Random rn = new Random(); Long lItem = tableDescription.getItemCount(); int iNoOfItems = lItem.intValue(); int iPointOnePercent = (int) ((int) iNoOfItems * 0.001); int iOnePercent = (int) ((int) iNoOfItems * 0.01); System.out.println("TotalItems:" + iNoOfItems + "::0.1% of data is :: " + iPointOnePercent + "::1% of data is :" + iOnePercent); // Generating 25000 random queries for 0.1 to 1 % of the data for (int i = 0; i <= 24999; i++) { String randomInt = Integer.toString(rn.nextInt(iOnePercent - iPointOnePercent) + iPointOnePercent); HashMap<String, Condition> scanFilter = new HashMap<String, Condition>(); Condition condition = new Condition().withComparisonOperator(ComparisonOperator.EQ.toString()) .withAttributeValueList(new AttributeValue().withN(randomInt)); scanFilter.put("id", condition); ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter); ScanResult scanResult = dynamoDB.scan(scanRequest); System.out.println("Random No :" + randomInt + ":: Query no: " + (i + 1)); } // calculate time difference for update file time long lEndTime = new Date().getTime(); long difference = lEndTime - lStartTime; System.out.println("Elapsed milliseconds: " + difference); System.out.println("Elapsed seconds: " + difference * 0.001); System.out.println("Elapsed Minutes: " + (int) ((difference / (1000 * 60)) % 60)); } 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:SQS.java
License:Open Source License
public String createQueue(String name) { String myQueueUrl = null;/*from ww w . jav a2 s . c om*/ try { System.out.println("Creating a new SQS queue called " + name); CreateQueueRequest createQueueRequest = new CreateQueueRequest(name); myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); } 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()); } return myQueueUrl; }
From source file:SQS.java
License:Open Source License
public void sendMessage(String myQueueUrl, String message) { try {/*from www . ja v a2 s . c om*/ //System.out.println("Sending a message"); sqs.sendMessage(new SendMessageRequest(myQueueUrl, message)); } 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:Assignment1.java
License:Open Source License
public static void main(String[] args) throws Exception { AWSCredentials credentials = new PropertiesCredentials( Assignment1.class.getResourceAsStream("AwsCredentials.properties")); /********************************************* * #1 Create Amazon Client object// w w w . ja va 2 s . co m **********************************************/ ec2 = new AmazonEC2Client(credentials); // We assume that we've already created an instance. Use the id of the instance. //String instanceId = "i-4e6c2a3d"; //put your own instance id to test this code. try { CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest(); createSecurityGroupRequest.withGroupName("mini").withDescription("My Java Security Group"); CreateSecurityGroupResult createSecurityGroupResult = ec2 .createSecurityGroup(createSecurityGroupRequest); IpPermission ipPermission = new IpPermission(); ipPermission.withIpRanges("0.0.0.0/0", "150.150.150.150/32").withIpProtocol("tcp").withFromPort(22) .withToPort(22); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest(); authorizeSecurityGroupIngressRequest.withGroupName("mini").withIpPermissions(ipPermission); ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest(); createKeyPairRequest.withKeyName("E3instance_key"); CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest); KeyPair keyPair = new KeyPair(); keyPair = createKeyPairResult.getKeyPair(); String privateKey = keyPair.getKeyMaterial(); System.out.print(privateKey); /********************************************* * * #1.1 Describe Key Pair * *********************************************/ System.out.println("\n#1.1 Describe Key Pair"); DescribeKeyPairsResult dkr = ec2.describeKeyPairs(); System.out.println(dkr.toString()); /********************************************* * * #1.2 Create an Instance * *********************************************/ RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId("ami-ab844dc2").withInstanceType("t1.micro").withMinCount(2) .withMaxCount(2).withKeyName("E3instance_key").withSecurityGroups("mini"); RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest); System.out.println("\n#1.2 Create an Instance"); List<Instance> resultInstance = runInstancesResult.getReservation().getInstances(); String createdInstanceId = null; for (Instance ins : resultInstance) { createdInstanceId = ins.getInstanceId(); System.out.println("New instance has been created: " + ins.getInstanceId()); } String myinstanceZone = resultInstance.get(0).getPlacement().getAvailabilityZone(); String myinstanceZone1 = resultInstance.get(1).getPlacement().getAvailabilityZone(); String myinstanceID = resultInstance.get(0).getInstanceId(); String myinstanceID1 = resultInstance.get(1).getInstanceId(); Thread.sleep(1000 * 1 * 60); /********************************************* * #2.1 Create a volume *********************************************/ //create a volume CreateVolumeRequest cvr = new CreateVolumeRequest(); CreateVolumeRequest cvr1 = new CreateVolumeRequest(); cvr.setAvailabilityZone(myinstanceZone); cvr1.setAvailabilityZone(myinstanceZone1); cvr.setSize(10); //size = 10 gigabytes cvr1.setSize(10); CreateVolumeResult volumeResult = ec2.createVolume(cvr); CreateVolumeResult volumeResult1 = ec2.createVolume(cvr1); String createdVolumeId = volumeResult.getVolume().getVolumeId(); String createdVolumeId1 = volumeResult1.getVolume().getVolumeId(); String[] volumeID = new String[2]; volumeID[0] = createdVolumeId; volumeID[1] = createdVolumeId1; System.out.println("\n#2.1 Create a volume for each instance"); Thread.sleep(1000 * 1 * 60); /********************************************* * #2.2 Attach the volume to the instance *********************************************/ AttachVolumeRequest avr = new AttachVolumeRequest(); AttachVolumeRequest avr1 = new AttachVolumeRequest(); avr.setInstanceId(myinstanceID); avr1.setInstanceId(myinstanceID1); avr.setVolumeId(createdVolumeId); avr1.setVolumeId(createdVolumeId1); avr.setDevice("/dev/sda2"); avr1.setDevice("/dev/sda2"); //avr.setVolumeId(createdVolumeId); //avr.setInstanceId(createdInstanceId); //avr.setDevice("/dev/sdf"); ec2.attachVolume(avr); ec2.attachVolume(avr1); System.out.println("\n#2.2 Attach the volume"); System.out.println("EBS volume has been attached and the volume ID is: " + createdVolumeId); System.out.println("EBS volume has been attached and the volume ID is: " + createdVolumeId1); Thread.sleep(1000 * 2 * 60); /*********************************** * #2.3 Monitoring (CloudWatch) *********************************/ //create CloudWatch client AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(credentials); //create request message GetMetricStatisticsRequest statRequest = new GetMetricStatisticsRequest(); //set up request message statRequest.setNamespace("AWS/EC2"); //namespace statRequest.setPeriod(60); //period of data ArrayList<String> stats = new ArrayList<String>(); //Use one of these strings: Average, Maximum, Minimum, SampleCount, Sum stats.add("Average"); stats.add("Sum"); statRequest.setStatistics(stats); //Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations statRequest.setMetricName("CPUUtilization"); // set time GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // 1 second ago Date endTime = calendar.getTime(); calendar.add(GregorianCalendar.MINUTE, -10); // 10 minutes ago Date startTime = calendar.getTime(); statRequest.setStartTime(startTime); statRequest.setEndTime(endTime); //specify an instance ArrayList<Dimension> dimensions = new ArrayList<Dimension>(); String monitorInstanceId = null; int i = 0; String[] idleInstance = new String[2]; for (Instance ins : resultInstance) { monitorInstanceId = ins.getInstanceId(); dimensions.add(new Dimension().withName("InstanceId").withValue(monitorInstanceId)); statRequest.setDimensions(dimensions); Thread.sleep(1000 * 3 * 60); //get statistics GetMetricStatisticsResult statResult = cloudWatch.getMetricStatistics(statRequest); //display System.out.println(statResult.toString()); List<Datapoint> dataList = statResult.getDatapoints(); Double averageCPU = null; Date timeStamp = null; for (Datapoint data : dataList) { averageCPU = data.getAverage(); timeStamp = data.getTimestamp(); System.out.println("Average CPU utlilization for last 1 minutes: " + averageCPU); //System.out.println("Total CPU utlilization for last 1 minutes: "+data.getSum()); //Calendar vmTime=GregorianCalendar.getInstance(); //vmTime.setTime(timeStamp); //vmTime.get(Calendar.HOUR_OF_DAY); if (averageCPU < 50 && i < 2) { idleInstance[i] = monitorInstanceId; i++; } } } System.out.println("\n" + i + " instance(s) idling."); /********************************************* * #2.4 Detach the volume from the instance *********************************************/ DetachVolumeRequest dvr = new DetachVolumeRequest(); DetachVolumeRequest dvr1 = new DetachVolumeRequest(); dvr.setVolumeId(createdVolumeId); dvr1.setVolumeId(createdVolumeId1); dvr.setInstanceId(myinstanceID); dvr1.setInstanceId(myinstanceID1); dvr.setDevice("/dev/sda2"); dvr1.setDevice("/dev/sda2"); ec2.detachVolume(dvr); ec2.detachVolume(dvr1); System.out.println("\n#2.4 Detach the volume"); Thread.sleep(1000 * 1 * 60); /********************************************* * #2.5 Create new AMI for idle instance *********************************************/ String[] idleAMIID = new String[2]; int j = 0; for (j = 0; j < idleInstance.length; j++) { CreateImageRequest Im = new CreateImageRequest(idleInstance[j], "image" + j); //CreateImageRequest Im1=new CreateImageRequest(myinstanceID1, "image1"); Im.setInstanceId(idleInstance[j]); //Im1.setInstanceId(myinstanceID1); CreateImageResult myAMI = ec2.createImage(Im); idleAMIID[j] = myAMI.getImageId(); //CreateImageResult myAMI1= ec2.createImage(Im1); System.out.println("\n#2.5 Create new AMI"); } Thread.sleep(1000 * 1 * 60); /********************************************* * * # Terminate an Instance * *********************************************/ //System.out.println("#8 Terminate the Instance"); // TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds); //ec2.terminateInstances(tir); /********************************************* * #2.6 Create new VMs *********************************************/ RunInstancesRequest runNewInstancesRequest = new RunInstancesRequest(); int m; String[] newCreatedInstanceId = new String[2]; for (m = 0; m < j; m++)//j is the number of AMI created { runNewInstancesRequest.withImageId(idleAMIID[m]).withInstanceType("t1.micro").withMinCount(1) .withMaxCount(1).withKeyName("E3instance_key").withSecurityGroups("mini"); RunInstancesResult runNewInstancesResult = ec2.runInstances(runNewInstancesRequest); List<Instance> newResultInstance = runNewInstancesResult.getReservation().getInstances(); String newInstanceId = null; for (Instance ins : newResultInstance) { newInstanceId = ins.getInstanceId(); } newCreatedInstanceId[m] = newInstanceId; System.out.println("Using AMI, a new instance has been created: " + newCreatedInstanceId[m]); } Thread.sleep(1000 * 1 * 60); //System.out.println("\n#2.6 Create "+ m + " instance using AMI"); /********************************************* * #2.7 Attach the volume to the new instance *********************************************/ int n; for (n = 0; n < idleInstance.length; n++) { AttachVolumeRequest new_avr = new AttachVolumeRequest(); //AttachVolumeRequest new_avr1 = new AttachVolumeRequest(); new_avr.setInstanceId(newCreatedInstanceId[n]); //avr1.setInstanceId(myinstanceID1); new_avr.setVolumeId(volumeID[n]); //avr1.setVolumeId(createdVolumeId1); new_avr.setDevice("/dev/sda2"); //avr1.setDevice("/dev/sda2"); //avr.setVolumeId(createdVolumeId); //avr.setInstanceId(createdInstanceId); //avr.setDevice("/dev/sdf"); ec2.attachVolume(new_avr); //ec2.attachVolume(avr1); System.out.println("\n#2.7 Re-attach the volume"); System.out.println("EBS volume has been attached and the volume ID is: " + volumeID[n]); //System.out.println("EBS volume has been attached and the volume ID is: "+createdVolumeId1); Thread.sleep(1000 * 1 * 60); } /************************************************ * #3 S3 bucket and object ***************************************************/ s3 = new AmazonS3Client(credentials); //create bucket String bucketName = "lucinda.duan"; 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 *********************************************/ // 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:MonitorTableCreator.java
License:Open Source License
public static void main(String[] args) throws Exception { init();/* w ww.java 2 s.com*/ long readCapacity = 2L; long writeCapacity = 2L; try { String tableName = "monitor"; // DeleteTableRequest deleteTableRequest = new DeleteTableRequest(tableName); // dynamoDB.deleteTable(deleteTableRequest); // // waitForTableToBecomeAvailable(tableName); // Create a table with a primary hash key named 'name', which holds a string CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) .withKeySchema(new KeySchemaElement().withAttributeName("id").withKeyType(KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition().withAttributeName("id") .withAttributeType(ScalarAttributeType.N)) .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(readCapacity) .withWriteCapacityUnits(writeCapacity)); TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest) .getTableDescription(); System.out.println("Created Table: " + createdTableDescription); // Wait for it to become active waitForTableToBecomeAvailable(tableName); // Describe our new table DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName); TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable(); System.out.println("Table Description: " + tableDescription); } 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()); } }