List of usage examples for com.amazonaws.auth PropertiesCredentials PropertiesCredentials
public PropertiesCredentials(InputStream inputStream) throws IOException
From source file:AwsSample.java
License:Open Source License
public static void main(String[] args) throws Exception { AWSCredentials credentials = new PropertiesCredentials( AwsSample.class.getResourceAsStream("AwsCredentials.properties")); /********************************************* * /*from w w w.j av a 2 s . com*/ * #1 Create Amazon Client object * *********************************************/ System.out.println("#1 Create Amazon Client object"); ec2 = new AmazonEC2Client(credentials); /********************************************* * Added By Chenyun Zhang * # Create an Amazon EC2 Security Group * *********************************************/ System.out.println("#1 Create an Amazon EC2 Security Group"); CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest(); createSecurityGroupRequest.withGroupName("JavaSecurityGroup").withDescription("My Java Security Group"); CreateSecurityGroupResult createSecurityGroupResult = ec2.createSecurityGroup(createSecurityGroupRequest); /********************************************* * Added By Chenyun Zhang * # Authorize Security Group Ingress * *********************************************/ System.out.println("#2 Authorize Security Group Ingress"); ArrayList<IpPermission> ipPermission = new ArrayList<IpPermission>(); //SSH IpPermission ipssh = new IpPermission(); ipssh.setIpProtocol("tcp"); ipssh.setFromPort(new Integer(22)); ipssh.setToPort(new Integer(22)); //ipssh.withIpRanges(ipRanges); ipssh.withIpRanges("72.69.22.123/32"); ipPermission.add(ipssh); //HTTP IpPermission iphttp = new IpPermission(); iphttp.setIpProtocol("tcp"); iphttp.setFromPort(new Integer(80)); iphttp.setToPort(new Integer(80)); iphttp.withIpRanges("0.0.0.0/0"); ipPermission.add(iphttp); //TCP IpPermission iptcp = new IpPermission(); iptcp.setIpProtocol("tcp"); iptcp.setFromPort(new Integer(49152)); iptcp.setToPort(new Integer(49152)); iptcp.withIpRanges("0.0.0.0/0"); ipPermission.add(iptcp); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest(); authorizeSecurityGroupIngressRequest.withGroupName("JavaSecurityGroup").withIpPermissions(ipPermission); ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); /********************************************* * Added By Chenyun Zhang * # Create a Key Pair * *********************************************/ System.out.println("#3 Create a Key Pair"); CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest(); createKeyPairRequest.withKeyName("HW2"); CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest); KeyPair keyPair = new KeyPair(); keyPair = createKeyPairResult.getKeyPair(); String privateKey = keyPair.getKeyMaterial(); //Calling createKeyPair is the only way to obtain the private key programmatically. /********************************************* * Added By Chenyun Zhang * # Download KeyPair * *********************************************/ PrintWriter Storekey = new PrintWriter( "/Users/Annabelle/Documents/NYU-POLY/3/Cloud Computing/HW2" + "/" + "Hw2" + ".pem", "UTF-8"); Storekey.print(privateKey); Storekey.close(); System.out.println("Already store the key!"); 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()); } /********************************************* * * #6 Create an Instance * *********************************************/ System.out.println("#5 Create an Instance"); String imageId = "ami-76f0061f"; //Basic 64-bit Amazon Linux AMI int minInstanceCount = 1; // create 1 instance int maxInstanceCount = 1; //RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount); RunInstancesRequest rir = new RunInstancesRequest(); rir.withImageId(imageId).withInstanceType("t1.micro").withMinCount(minInstanceCount) .withMaxCount(maxInstanceCount).withKeyName("HW2").withSecurityGroups("JavaSecurityGroup"); RunInstancesResult result = ec2.runInstances(rir); /********************************************* * Added by Chenyun Zhang * # Get the public Ip address * *********************************************/ //get instanceId from the result 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()); //DescribeInstancesRequest and get ip String createdInstanceIp = null; while (createdInstanceIp == null) { System.out.println("Please waiting for 10 seconds!"); Thread.sleep(10000); DescribeInstancesRequest newdescribeInstances = new DescribeInstancesRequest(); DescribeInstancesResult newdescribeInstancesRequest = ec2 .describeInstances(newdescribeInstances); List<Reservation> newreservations = newdescribeInstancesRequest.getReservations(); Set<Instance> allinstances = new HashSet<Instance>(); for (Reservation reservation : newreservations) { allinstances.addAll(reservation.getInstances()); } for (Instance myinst : allinstances) { String instanceId = myinst.getInstanceId(); if (instanceId.equals(createdInstanceId)) { createdInstanceIp = myinst.getPublicIpAddress(); } } } System.out.println("Already get the Ip!"); System.out.println("New instance's ip address is:" + createdInstanceIp); IP = createdInstanceIp; } /********************************************* * * #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("Name", "MyFirstInstance"); resources.add(createdInstanceId); tags.add(nameTag); CreateTagsRequest ctr = new CreateTagsRequest(resources, tags); ec2.createTags(ctr); /********************************************* * Added By Chenyun Zhang * # SSH connect into EC2 * *********************************************/ Thread.sleep(100000); ssh con = new ssh(); con.sshcon(IP); /********************************************* * * #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); /********************************************* * * #9 Terminate an Instance * *********************************************/ System.out.println("#8 Terminate the Instance"); TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds); //ec2.terminateInstances(tir); /********************************************* * * #10 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:EbsAttach.java
License:Open Source License
private static void init() throws Exception { /*/*from ww w . j av a 2 s . c o m*/ * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (/Users/Modoka/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( EbsAttach.class.getResourceAsStream("AwsCredentials.properties")); // credentials = new ProfileCredentialsProvider("default").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/Modoka/.aws/credentials), and is in valid format.", e); } ec2 = new AmazonEC2Client(credentials); }
From source file:Encoder.java
License:Open Source License
/** * Amazon cloud credential submitter method (The real shit in the world of programming when you don't have anything to write for a function!). * /* w ww .j a va 2 s.c om*/ * @throws Exception */ private static void getAmazonCloud() throws Exception { credentials = new PropertiesCredentials( Encoder.class.getResourceAsStream("settings/" + "AwsCredentials.properties")); ec2 = new AmazonEC2Client(credentials); s3 = new AmazonS3Client(credentials); }
From source file:CloudFormationSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*// w w w. j av 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
public static void main(String[] args) throws IOException { if (args.length != 2) { System.out.println("Usage: bucket_name properties_file"); System.out.println("Please specify the bucket name and the properties file to process."); System.out.println(//w ww .j av a 2 s . com "The properties file contains the key for S3 as the key and absolute file path as the value."); System.exit(0); } /* * 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(Uploader.class.getResourceAsStream("AwsCredentials.properties"))); String bucketName = args[0]; System.out.println("==========================================="); System.out.println("Getting Started with Amazon S3"); System.out.println("===========================================\n"); Properties files = new Properties(); InputStream in = new FileInputStream(new File(args[1])); files.load(in); in.close(); Set keys = files.keySet(); for (Object key : keys) { uploadFile(s3, bucketName, (String) key, new File(files.getProperty((String) key))); } }
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//from ww w . j a va2s. 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-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:advanced.CreateSecurityGroupApp.java
License:Open Source License
/** * @param args//from ww w . ja v a 2 s. c o m */ public static void main(String[] args) { // Retrieves the credentials from an AWSCredentials.properties file. AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( InlineTaggingCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties")); } catch (IOException e1) { System.out.println("Credentials were not properly entered into AwsCredentials.properties."); System.out.println(e1.getMessage()); System.exit(-1); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest("GettingStartedGroup", "Getting Started Security Group"); ec2.createSecurityGroup(securityGroupRequest); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } String ipAddr = "0.0.0.0/0"; // Get the IP of the current host, so that we can limit the Security Group // by default to the ip range associated with your subnet. try { InetAddress addr = InetAddress.getLocalHost(); // Get IP Address ipAddr = addr.getHostAddress() + "/10"; } catch (UnknownHostException e) { } //System.exit(-1); // Create a range that you would like to populate. ArrayList<String> ipRanges = new ArrayList<String>(); ipRanges.add(ipAddr); // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic). ArrayList<IpPermission> ipPermissions = new ArrayList<IpPermission>(); IpPermission ipPermission = new IpPermission(); ipPermission.setIpProtocol("tcp"); ipPermission.setFromPort(new Integer(22)); ipPermission.setToPort(new Integer(22)); ipPermission.setIpRanges(ipRanges); ipPermissions.add(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( "GettingStartedGroup", ipPermissions); ec2.authorizeSecurityGroupIngress(ingressRequest); } catch (AmazonServiceException ase) { // Ignore because this likely means the zone has already been authorized. System.out.println(ase.getMessage()); } }
From source file:advanced.InlineGettingStartedCodeSampleApp.java
License:Open Source License
/** * @param args/* w ww . j ava2 s. co m*/ */ public static void main(String[] args) { //============================================================================================// //=============================== Submitting a Request =======================================// //============================================================================================// // Retrieves the credentials from an AWSCredentials.properties file. AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( InlineTaggingCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties")); } catch (IOException e1) { System.out.println("Credentials were not properly entered into AwsCredentials.properties."); System.out.println(e1.getMessage()); System.exit(-1); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); //*************************** Required Parameters Settings ************************// // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro) // and the latest Amazon Linux AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-8c1fece5"); launchSpecification.setInstanceType("t1.micro"); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); //*************************** Bid Type Settings ************************// // Set the type of the bid to persistent. requestRequest.setType("persistent"); //*************************** Valid From/To Settings ************************// // Set the valid start time to be two minutes from now. Calendar from = Calendar.getInstance(); from.add(Calendar.MINUTE, 2); requestRequest.setValidFrom(from.getTime()); // Set the valid end time to be two minutes and two hours from now. Calendar until = (Calendar) from.clone(); until.add(Calendar.HOUR, 2); requestRequest.setValidUntil(until.getTime()); //*************************** Launch Group Settings ************************// // Set the launch group. requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP"); //*************************** Availability Zone Group Settings ************************// // Set the availability zone group. requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP"); //*************************** Add the block device mapping ************************// // Goal: Setup block device mappings to ensure that we will not delete // the root partition on termination. // Create the block device mapping to describe the root partition. BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); // Set the delete on termination flag to false. EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setDeleteOnTermination(Boolean.FALSE); blockDeviceMapping.setEbs(ebs); // Add the block device mapping to the block list. ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); // Set the block device mapping configuration in the launch specifications. launchSpecification.setBlockDeviceMappings(blockList); //*************************** Add the availability zone ************************// // Setup the availability zone to use. Note we could retrieve the availability // zones using the ec2.describeAvailabilityZones() API. For this demo we will just use // us-east-1b. SpotPlacement placement = new SpotPlacement("us-east-1b"); launchSpecification.setPlacement(placement); //*************************** Add the placement group ************************// // Setup the placement group to use with whatever name you desire. // For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP". // Note: We have commented this out, because we are not leveraging cc1.4xlarge or // cg1.4xlarge in this example. /* SpotPlacement pg = new SpotPlacement(); pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP"); launchSpecification.setPlacement(pg); */ //*************************** Add the launch specification ************************// // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); //============================================================================================// //=========================== Getting the Request ID from the Request ========================// //============================================================================================// // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest); List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests(); // Setup an arraylist to collect all of the request ids we want to watch hit the running // state. ArrayList<String> spotInstanceRequestIds = new ArrayList<String>(); // Add all of the request ids to the hashset, so we can determine when they hit the // active state. for (SpotInstanceRequest requestResponse : requestResponses) { System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId()); spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId()); } //============================================================================================// //=========================== Determining the State of the Spot Request ======================// //============================================================================================// // Create a variable that will track whether there are any requests still in the open state. boolean anyOpen; // Initialize variables. ArrayList<String> instanceIds = new ArrayList<String>(); do { // Create the describeRequest with tall of the request id to monitor (e.g. that we started). DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest(); describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds); // Initialize the anyOpen variable to false which assumes there are no requests open unless // we find one that is still open. anyOpen = false; try { // Retrieve all of the requests we want to monitor. DescribeSpotInstanceRequestsResult describeResult = ec2 .describeSpotInstanceRequests(describeRequest); List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests(); // Look through each request and determine if they are all in the active state. for (SpotInstanceRequest describeResponse : describeResponses) { // If the state is open, it hasn't changed since we attempted to request it. // There is the potential for it to transition almost immediately to closed or // cancelled so we compare against open instead of active. if (describeResponse.getState().equals("open")) { anyOpen = true; break; } // Add the instance id to the list we will eventually terminate. instanceIds.add(describeResponse.getInstanceId()); } } catch (AmazonServiceException e) { // If we have an exception, ensure we don't break out of the loop. // This prevents the scenario where there was blip on the wire. anyOpen = true; } try { // Sleep for 60 seconds. Thread.sleep(60 * 1000); } catch (Exception e) { // Do nothing because it woke up early. } } while (anyOpen); //============================================================================================// //====================================== Canceling the Request ==============================// //============================================================================================// try { // Cancel requests. CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest( spotInstanceRequestIds); ec2.cancelSpotInstanceRequests(cancelRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error cancelling instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } //============================================================================================// //=================================== Terminating any Instances ==============================// //============================================================================================// try { // Terminate instances. TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds); ec2.terminateInstances(terminateRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } }
From source file:advanced.InlineTaggingCodeSampleApp.java
License:Open Source License
/** * @param args/*from w w w. j a v a2s .co m*/ */ public static void main(String[] args) { //============================================================================================// //=============================== Submitting a Request =======================================// //============================================================================================// // Retrieves the credentials from an AWSCredentials.properties file. AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( InlineTaggingCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties")); } catch (IOException e1) { System.out.println("Credentials were not properly entered into AwsCredentials.properties."); System.out.println(e1.getMessage()); System.exit(-1); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro) // and the latest Amazon Linux AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-8c1fece5"); launchSpecification.setInstanceType("t1.micro"); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Add the launch specifications to the request. requestRequest.setLaunchSpecification(launchSpecification); //============================================================================================// //=========================== Getting the Request ID from the Request ========================// //============================================================================================// // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest); List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests(); // Setup an arraylist to collect all of the request ids we want to watch hit the running // state. ArrayList<String> spotInstanceRequestIds = new ArrayList<String>(); // Add all of the request ids to the hashset, so we can determine when they hit the // active state. for (SpotInstanceRequest requestResponse : requestResponses) { System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId()); spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId()); } //============================================================================================// //====================================== Tag the Spot Requests ===============================// //============================================================================================// // Create the list of tags we want to create ArrayList<Tag> requestTags = new ArrayList<Tag>(); requestTags.add(new Tag("keyname1", "value1")); // Create a tag request for requests. CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest(); createTagsRequest_requests.setResources(spotInstanceRequestIds); createTagsRequest_requests.setTags(requestTags); // Try to tag the Spot request submitted. try { ec2.createTags(createTagsRequest_requests); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } //============================================================================================// //=========================== Determining the State of the Spot Request ======================// //============================================================================================// // Create a variable that will track whether there are any requests still in the open state. boolean anyOpen; // Initialize variables. ArrayList<String> instanceIds = new ArrayList<String>(); do { // Create the describeRequest with tall of the request id to monitor (e.g. that we started). DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest(); describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds); // Initialize the anyOpen variable to false which assumes there are no requests open unless // we find one that is still open. anyOpen = false; try { // Retrieve all of the requests we want to monitor. DescribeSpotInstanceRequestsResult describeResult = ec2 .describeSpotInstanceRequests(describeRequest); List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests(); // Look through each request and determine if they are all in the active state. for (SpotInstanceRequest describeResponse : describeResponses) { // If the state is open, it hasn't changed since we attempted to request it. // There is the potential for it to transition almost immediately to closed or // cancelled so we compare against open instead of active. if (describeResponse.getState().equals("open")) { anyOpen = true; break; } // Add the instance id to the list we will eventually terminate. instanceIds.add(describeResponse.getInstanceId()); } } catch (AmazonServiceException e) { // If we have an exception, ensure we don't break out of the loop. // This prevents the scenario where there was blip on the wire. anyOpen = true; } try { // Sleep for 60 seconds. Thread.sleep(60 * 1000); } catch (Exception e) { // Do nothing because it woke up early. } } while (anyOpen); //============================================================================================// //====================================== Tag the Spot Instances ===============================// //============================================================================================// // Create the list of tags we want to create ArrayList<Tag> instanceTags = new ArrayList<Tag>(); instanceTags.add(new Tag("keyname1", "value1")); // Create a tag request for instances. CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest(); createTagsRequest_instances.setResources(instanceIds); createTagsRequest_instances.setTags(instanceTags); // Try to tag the Spot instance started. try { ec2.createTags(createTagsRequest_instances); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } //============================================================================================// //====================================== Canceling the Request ==============================// //============================================================================================// try { // Cancel requests. CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest( spotInstanceRequestIds); ec2.cancelSpotInstanceRequests(cancelRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error cancelling instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } //============================================================================================// //=================================== Terminating any Instances ==============================// //============================================================================================// try { // Terminate instances. TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds); ec2.terminateInstances(terminateRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } }
From source file:advanced.Requests.java
License:Open Source License
/** * The only information needed to create a client are security credentials * consisting of the AWS Access Key ID and Secret Access Key. All other * configuration, such as the service endpoints, are performed * automatically. Client parameters, such as proxies, can be specified in an * optional ClientConfiguration object when constructing a client. * * @see com.amazonaws.auth.BasicAWSCredentials * @see com.amazonaws.auth.PropertiesCredentials * @see com.amazonaws.ClientConfiguration *//*ww w .j a v a 2s . co m*/ private void init(String instanceType, String amiID, String bidPrice, String securityGroup) throws Exception { AWSCredentials credentials = new PropertiesCredentials( InlineTaggingCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties")); ec2 = new AmazonEC2Client(credentials); this.instanceType = instanceType; this.amiID = amiID; this.bidPrice = bidPrice; this.securityGroup = securityGroup; this.deleteOnTermination = true; this.placementGroupName = null; }