List of usage examples for com.amazonaws.services.ec2 AmazonEC2Client AmazonEC2Client
AmazonEC2Client(AwsSyncClientParams clientParams)
From source file:ClienTopTen.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. * /*from w w w .java 2 s . c o m*/ * @see com.amazonaws.auth.BasicAWSCredentials * @see com.amazonaws.auth.PropertiesCredentials * @see com.amazonaws.ClientConfiguration */ private static void init() throws Exception { AWSCredentials credentials = new PropertiesCredentials( ClienTopTen.class.getResourceAsStream("AwsCredentials.properties")); ec2 = new AmazonEC2Client(credentials); // s3 = new AmazonS3Client(credentials); // sdb = new AmazonSimpleDBClient(credentials); }
From source file:AwsSdkSample.java
License:Open Source License
/** * The only information needed to create a client are security credentials - * your AWS Access Key ID and Secret Access Key. All other * configuration, such as the service endpoints have defaults provided. * * Additional client parameters, such as proxy configuration, 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 *//*from w ww . j av a2s. c o m*/ private static void init() throws Exception { /* * ProfileCredentialsProvider loads AWS security credentials from a * .aws/config file in your home directory. * * These same credentials are used when working with other AWS SDKs and the AWS CLI. * * You can find more information on the AWS profiles config file here: * http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html */ File configFile = new File(System.getProperty("user.home"), ".aws/credentials"); AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider( new ProfilesConfigFile(configFile), "default"); if (credentialsProvider.getCredentials() == null) { throw new RuntimeException("No AWS security credentials found:\n" + "Make sure you've configured your credentials in: " + configFile.getAbsolutePath() + "\n" + "For more information on configuring your credentials, see " + "http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html"); } ec2 = new AmazonEC2Client(credentialsProvider); s3 = new AmazonS3Client(credentialsProvider); }
From source file:Conductor.java
License:Open Source License
/** * Initialization of program "connect to DB, load configurations, connect to Amazon, run minimum encode servers we need etc". *//*w ww .j a v a 2 s . co m*/ private static void init() { /********************************************************************** ***************************** EC2 INITIALS *************************** **********************************************************************/ try { // System.out.println("Working Directory = " + System.getProperty("user.dir")); /********************************************************************* * ******************************************************************* * Loading Program config information. * ******************************************************************* *********************************************************************/ DefaultSettingsPath = System.getProperty("user.dir") + "/settings/"; config = new Properties(); config.load(new FileInputStream(DefaultSettingsPath + "conductor_initial_config.properties")); System.out.println("Program config info loaded: Ok."); //debugModeEnable = Boolean.parseBoolean(config.getProperty("DebugModeEnable")); DebugMessage = new Debuger(Boolean.parseBoolean(config.getProperty("DebugModeEnable"))); /********************************************************************** *********************** JERSEY SERVER INITIALS ********************************** **********************************************************************/ Authentication.getInstance().setAuthenticationInitials(config.getProperty("AdminUserName"), config.getProperty("AdminPassword"), config.getProperty("AdminSessionValidTimeInMinut")); UriRestServer = config.getProperty("UriRestServer"); System.out.println(UriRestServer); server = HttpServerFactory.create(UriRestServer); server.start(); DebugMessage.ShowInfo("Http Server started: Ok.", true); boolean blNeedSoftBoot = checkForSoftBoot(); /*##################################*/ blNeedSoftBoot = true; /********************************************************************** *********************** DB INITIALS ********************************* **********************************************************************/ if (!SQL.connect( config.getProperty("PostgraSQLServerAddress") + ":" + config.getProperty("PostgraSQLServerPort") + "/", config.getProperty("PostgraSQLUserName"), config.getProperty("PostgraSQLPassWord"), config.getProperty("MySqlDataBase"))) { throw new Exception(Constants._ERR_DBAccessError); } if (!blNeedSoftBoot) { SQL.query("DROP TABLE IF EXISTS " + config.getProperty("TableUploadSessions") + ", " + config.getProperty("TableInstanceServers")); SQL.query(config.getProperty("CreatTableUploadSessions")); SQL.query(config.getProperty("CreatTableInstanceServers")); DebugMessage.ShowInfo("Connect to db: Ok.", true); } //AWSCredentials credentials = new PropertiesCredentials(Conductor.class.getResourceAsStream("settings/"+ "AwsCredentials.properties")); AWSCredentials credentials = new PropertiesCredentials( Conductor.class.getResourceAsStream("AwsCredentials.properties")); ec2 = new AmazonEC2Client(credentials); // / Check available zones. if (GetCurrentAvailableZones().getAvailabilityZones().size() > 0) { DebugMessage.ShowInfo("Available zones access: Ok.", true); DebugMessage.ShowInfo( "Number of zones: " + GetCurrentAvailableZones().getAvailabilityZones().size(), true); int countAvailableZones = 0; for (int i = 0; i < GetCurrentAvailableZones().getAvailabilityZones().size(); i++) { //countAvailableZones DebugMessage.ShowInfo( "Zone " + "1: " + GetCurrentAvailableZones().getAvailabilityZones().get(i), true); // I do not know this algorithm is correct or not (lack of fucking AWS documents!) if (GetCurrentAvailableZones().getAvailabilityZones().get(i).getRegionName() .contains(config.getProperty("StringEndPointRegion"))) { if (GetCurrentAvailableZones().getAvailabilityZones().get(i).getState() .contentEquals("available")) { countAvailableZones++; } } } if (countAvailableZones != GetCurrentAvailableZones().getAvailabilityZones().size()) throw new Exception(Constants._ERR_CannotAccessZones); // Get number of running instances. int numberofrunninginstance = getNumberofInstances(0); DebugMessage.ShowInfo("You have " + numberofrunninginstance + " Amazon EC2 instance(s) running.", true); System.out.println("==========================================="); ec2.setEndpoint(config.getProperty("SetEndPointName")); System.out.println(getProcessJobsStatistic("UnderProcess")); System.out.println(getProcessJobsStatistic("Finished")); System.out.println(getProcessJobsStatistic("Waiting")); System.out.println(getProcessJobsStatistic("Unsuccess")); System.out.println(getProcessJobsStatistic("WaitingAndUnderProcess")); //System.in.read(); server.stop(0); System.exit(0); /* * There is not server ready or number of them is not * enough for initialization of system. So run some. */ if ((numberofrunninginstance < Integer.parseInt(config.getProperty("MinimumEssentialTiers"))) && (blNeedSoftBoot != false)) { /* * Calculating number of servers needed to be run as minimum * number transcoders in the initialization. */ int _numOfSrvNeedToRun = Integer.parseInt(config.getProperty("MinimumEssentialTiers")) - numberofrunninginstance; DebugMessage.ShowInfo("Number of needed transcoder instancess to run for initial stage: " + _numOfSrvNeedToRun, true); // CREATE EC2 INSTANCES RunInstancesRequest runInstancesRequest = new RunInstancesRequest() .withInstanceType(config.getProperty("InstanceType")) .withImageId(config.getProperty("InstanceAmiToRun")).withMinCount(_numOfSrvNeedToRun) .withMaxCount(_numOfSrvNeedToRun).withMonitoring(false) .withKeyName(config.getProperty("InstanceAmiToRunSecurityKey")) .withSecurityGroupIds(config.getProperty("InstanceAmiSecurityGroup")); RunInstancesResult runInstances = ec2.runInstances(runInstancesRequest); /* * Now waiting for 120s to servers to be run. Except after * timeout something is wrong. */ int counter = 0; boolean isRunning = true; int i; System.out.println("==========================================="); while (isRunning) // the loop { i = waitInitialInstancesTobeReady(); System.out.print("Number of current running servers in the waiting loop: " + i); // waits until all the servers be in running state. if (i == Integer.parseInt(config.getProperty("MinimumEssentialTiers"))) { System.out.println(""); System.out.println("Minimum transcoding servers added and finished. Continue ...."); isRunning = false; break; } counter++; // 24*5000 = 120 Second if (counter == Integer.parseInt(config.getProperty("TimeWaitInstanceBeOprational"))) { isRunning = false; throw new Exception(Constants._ERR_CannotRunInstance); } DebugMessage.ShowInfo("\r" + (counter * Integer.parseInt(config.getProperty("TickTimeTierBeReady"))) / 1000 + " second... ", true); Thread.sleep(Integer.parseInt(config.getProperty("TickTimeTierBeReady"))); // the timing mechanism } } else { DebugMessage.ShowInfo("No need to add any instance in initialization. Continue ....", true); } /* * Put recently added transcoding servers in the database as * pool of current available servers. */ //if (!LogTheServersInTheDB(0)) // throw new Exception(Constants._ERR_DBAccessError); } else { throw new Exception(Constants._ERR_CannotAccessZones); } } catch (Exception e) { e.printStackTrace(); String reflectErr; switch (e.getMessage()) { case Constants._ERR_CannotAccessZones: reflectErr = DebugMessage.ShowErrors("init()", e.getMessage(), "Can not access any available zone", true); Log_Report(reflectErr); System.exit(1); break; case Constants._ERR_DBAccessError: System.out.println("-> Err Critical: Can not connect to db error."); reflectErr = DebugMessage.ShowErrors("init()", e.getMessage(), "Can not connect to db error", true); Log_Report(reflectErr); System.exit(1); break; case Constants._ERR_CannotRunInstance: reflectErr = DebugMessage.ShowErrors("init()", e.getMessage(), "Can not run instaces.", true); Log_Report(reflectErr); System.exit(1); /* sendemail( config.getProperty("EmailSenderUsername"), config.getProperty("EmailSenderPassword"), config.getProperty("EmailSender"), config.getProperty("EmailRecipient"), "Conductor Can not run instaces in initial stage!", "Error High Critical:\nCan not run instaces in initial stage! In init function.");*/ break; default: reflectErr = DebugMessage.ShowErrors("init()", e.getMessage(), "Uncategorized error", true); Log_Report(reflectErr); System.exit(1); break; } } }
From source file:EC2LaunchWaitTerminate.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 *//*from w w w . j a v a 2 s. c o m*/ private static void init() throws Exception { /* * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (~/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider().getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (~/.aws/credentials), and is in valid format.", e); } ec2 = new AmazonEC2Client(credentials); }
From source file:AwsAuto.java
License:Open Source License
public static void main(String[] args) throws Exception { // initialize/determine parameters String instanceType = "m3.medium"; String loadGeneratorAmi = "ami-8ac4e9e0"; String dataCenterAmi = "ami-349fbb5e"; String bidPrice = "0.1"; String loadGeneratorDns = null; // load generator DNS String dashboardUrl = null; // the URL where we check our performance String testId = null;//from w w w . j a v a 2 s . c o m // create project tag for instances ArrayList<com.amazonaws.services.ec2.model.Tag> loadGeneratorTags = new ArrayList<>(); com.amazonaws.services.ec2.model.Tag loadGeneratorTag = new com.amazonaws.services.ec2.model.Tag("Project", "2.1"); loadGeneratorTags.add(loadGeneratorTag); // create project tag for auto-scaling com.amazonaws.services.autoscaling.model.Tag asgTag = new com.amazonaws.services.autoscaling.model.Tag(); asgTag.setKey("Project"); asgTag.setValue("2.1"); // create project tag for load balancer ArrayList<com.amazonaws.services.elasticloadbalancing.model.Tag> loadBalancerTags = new ArrayList<>(); com.amazonaws.services.elasticloadbalancing.model.Tag loadBalancerTag = new com.amazonaws.services.elasticloadbalancing.model.Tag(); loadBalancerTag.setKey("Project"); loadBalancerTag.setValue("2.1"); loadBalancerTags.add(loadBalancerTag); /** * ========================================================================= * ================= Create security groups * ========================================================================= * ================= */ String loadGeneratorSecurityName = "LoadGeneratorSGP2"; String allPurposeSecurityName = "AllPurposeSGP2"; SecurityGroup loadGeneratorSecurityGroup = new SecurityGroup(loadGeneratorSecurityName); SecurityGroup allPurposeSecurityGroup = new SecurityGroup(allPurposeSecurityName); /** * ========================================================================= * ================= Grant permission and credentials * ========================================================================= * ================= */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("School").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 (C:\\Users\\Jiabei\\.aws\\credentials), and is in valid format.", e); } // set region AmazonEC2 ec2 = new AmazonEC2Client(credentials); Region usEast1 = Region.getRegion(Regions.US_EAST_1); ec2.setRegion(usEast1); /** * ========================================================================= * ================= Create a load generator and submit password * ========================================================================= * ================= */ Requests requestsLg = new Requests(instanceType, loadGeneratorAmi, bidPrice, loadGeneratorSecurityName, loadGeneratorTags); loadGeneratorDns = requestsLg.submitRequests(); String submissionUrl = "http://" + loadGeneratorDns + "/password?passwd=0WSb4ufhYI7SkxfLWnnIWU0MC1NdcNKT&andrewId=jiabeip"; sendGET(submissionUrl); try { /** * ======================================================================= * =================== Create a load balancer * ======================================================================= * =================== */ String loadBalancerDns = null; String loadBalancerName = "LoadBalancerProj2"; String healthCheckPage = "/heartbeat?lg=" + loadGeneratorDns; AmazonElasticLoadBalancingClient loadBalancerClient = new AmazonElasticLoadBalancingClient(credentials); // configure a request CreateLoadBalancerRequest loadBalancerRequest = new CreateLoadBalancerRequest() .withAvailabilityZones("us-east-1b").withListeners(new Listener("HTTP", 80, 80)) .withLoadBalancerName(loadBalancerName).withSecurityGroups(allPurposeSecurityGroup.getGroupId()) .withTags(loadBalancerTags); CreateLoadBalancerResult loadBalancerResult = loadBalancerClient .createLoadBalancer(loadBalancerRequest); loadBalancerDns = loadBalancerResult.getDNSName(); // configure health check setting HealthCheck loadBalancerHealthCheck = new HealthCheck().withTarget("HTTP:80" + healthCheckPage) .withTimeout(5).withInterval(30).withUnhealthyThreshold(2).withHealthyThreshold(10); ConfigureHealthCheckRequest healthCheckRequest = new ConfigureHealthCheckRequest() .withLoadBalancerName(loadBalancerName).withHealthCheck(loadBalancerHealthCheck); // attach health check setting to load balancer ConfigureHealthCheckResult healthCheckResult = loadBalancerClient .configureHealthCheck(healthCheckRequest); System.out.println("Load balancer created!\nDNS: " + loadBalancerDns); /** * ======================================================================= * =================== Create launch configuration * ======================================================================= * =================== */ String launchConfigName = "LaunchConfigProj2"; String autoScalingGroupName = "AutoScalingGroupProj2"; AmazonAutoScalingClient autoScalingGroupClient = new AmazonAutoScalingClient(credentials); AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(credentials); System.out.println("Creating launch configuration..."); // configure the request CreateLaunchConfigurationRequest launchConfigRequest = new CreateLaunchConfigurationRequest() .withImageId(dataCenterAmi).withInstanceType(instanceType) .withLaunchConfigurationName(launchConfigName) .withSecurityGroups(allPurposeSecurityGroup.getGroupId()).withSpotPrice(bidPrice) .withKeyName("primary"); // enable detail monitoring InstanceMonitoring monitor = new InstanceMonitoring(); monitor.setEnabled(true); launchConfigRequest.setInstanceMonitoring(monitor); // attach the configuration to the ASG client autoScalingGroupClient.createLaunchConfiguration(launchConfigRequest); System.out.println("Configuration complete!\nCreating auto-scaling group..."); /** * ======================================================================= * =================== Create auto-scaling group * ======================================================================= * =================== */ // configure ASG request CreateAutoScalingGroupRequest asgRequest = new CreateAutoScalingGroupRequest() .withAutoScalingGroupName(autoScalingGroupName).withAvailabilityZones("us-east-1b") .withLoadBalancerNames(loadBalancerName).withNewInstancesProtectedFromScaleIn(false) .withTags(asgTag).withDefaultCooldown(120).withMinSize(1).withMaxSize(8).withDesiredCapacity(1) // Start // from // one .withHealthCheckGracePeriod(120).withHealthCheckType("ELB") .withLaunchConfigurationName(launchConfigName); // attach group configuration to ASG client autoScalingGroupClient.createAutoScalingGroup(asgRequest); /** * ======================================================================= * =================== Create scaling up policy for ASG * ======================================================================= * =================== */ StepAdjustment upRule1 = new StepAdjustment().withMetricIntervalLowerBound(0.0) .withMetricIntervalUpperBound(25.0).withScalingAdjustment(1); StepAdjustment upRule2 = new StepAdjustment().withMetricIntervalLowerBound(25.0) .withMetricIntervalUpperBound(30.0).withScalingAdjustment(2); StepAdjustment upRule3 = new StepAdjustment().withMetricIntervalLowerBound(30.0) .withMetricIntervalUpperBound(null).withScalingAdjustment(3); String upPolicyName = "Scaling Up"; PutScalingPolicyRequest scalingUpPolicy = new PutScalingPolicyRequest() .withAdjustmentType("ChangeInCapacity").withPolicyType("StepScaling") .withStepAdjustments(upRule1, upRule2, upRule3).withAutoScalingGroupName(autoScalingGroupName) .withPolicyName(upPolicyName).withEstimatedInstanceWarmup(120); StepAdjustment downRule1 = new StepAdjustment().withMetricIntervalLowerBound(-20.0) .withMetricIntervalUpperBound(-0.0).withScalingAdjustment(-1); StepAdjustment downRule2 = new StepAdjustment().withMetricIntervalLowerBound(-30.0) .withMetricIntervalUpperBound(-20.0).withScalingAdjustment(-2); StepAdjustment downRule3 = new StepAdjustment().withMetricIntervalLowerBound(null) .withMetricIntervalUpperBound(-30.0).withScalingAdjustment(-3); String downPolicyName = "Scaling Down"; PutScalingPolicyRequest scalingDownPolicy = new PutScalingPolicyRequest().withAdjustmentType("") .withPolicyType("ChangeInCapacity").withStepAdjustments(downRule1, downRule2, downRule3) .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(downPolicyName) .withEstimatedInstanceWarmup(60); // attach policies to ASG and get ARN for setting alarm PutScalingPolicyResult scaleUpResult = autoScalingGroupClient.putScalingPolicy(scalingUpPolicy); String upArn = scaleUpResult.getPolicyARN(); PutScalingPolicyResult scaleDownResult = autoScalingGroupClient.putScalingPolicy(scalingDownPolicy); String downArn = scaleDownResult.getPolicyARN(); /** * ======================================================================= * =================== Create alarms for policies * ======================================================================= * =================== */ String upAlarmName = "UpAlarm_Mild"; String downAlarmName = "DownAlarm_Mild"; Dimension dimension = new Dimension(); dimension.setName("AutoScalingGroupName"); dimension.setValue(autoScalingGroupName); PutMetricAlarmRequest upAlarmRequest = new PutMetricAlarmRequest().withAlarmName(upAlarmName) .withMetricName("CPUUtilization").withNamespace("AWS/EC2").withDimensions(dimension) .withStatistic(Statistic.SampleCount) .withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold).withThreshold(65.0) .withEvaluationPeriods(1).withPeriod(120).withAlarmActions(upArn); PutMetricAlarmRequest downAlarmRequest = new PutMetricAlarmRequest().withAlarmName(downAlarmName) .withNamespace("AWS/EC2").withDimensions(dimension).withMetricName("CPUUtilization") .withStatistic(Statistic.Average) .withComparisonOperator(ComparisonOperator.LessThanOrEqualToThreshold).withThreshold(60.0) .withEvaluationPeriods(1).withPeriod(120).withAlarmActions(downArn); cloudWatchClient.putMetricAlarm(upAlarmRequest); cloudWatchClient.putMetricAlarm(downAlarmRequest); System.out.println("All settings complete! \nReady for warmup..."); /** * ======================================================================= * =================== Warm up ELB * ======================================================================= * =================== */ String warmUpUrl = "http://" + loadGeneratorDns + "/warmup?dns=" + loadBalancerDns; sendGET(warmUpUrl); System.out.println("Warmup link: " + warmUpUrl); try { Thread.sleep(15 * 60 * 1000); } catch (Exception e) { e.printStackTrace(); } System.out.println("Warmup complete!\nReady for battle..."); /** * ======================================================================= * =================== Start the test * ======================================================================= * =================== */ String testUrl = "http://" + loadGeneratorDns + "/junior?dns=" + loadBalancerDns; testId = sendGET(testUrl); System.out.println("Test ID is: " + testId); System.out.println("Test link: " + testUrl); try { Thread.sleep(60 * 60 * 1000); } catch (Exception e) { e.printStackTrace(); } System.out.println("Test finished!"); /** * ======================================================================= * =================== Delete resources * ======================================================================= * =================== */ // clear ASG UpdateAutoScalingGroupRequest asgClearRequest = new UpdateAutoScalingGroupRequest() .withAutoScalingGroupName(autoScalingGroupName).withMaxSize(0).withMinSize(0); autoScalingGroupClient.updateAutoScalingGroup(asgClearRequest); // delete policies DeletePolicyRequest upPolicyDeleteRequest = new DeletePolicyRequest() .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(upPolicyName); autoScalingGroupClient.deletePolicy(upPolicyDeleteRequest); DeletePolicyRequest downPolicyDeleteRequest = new DeletePolicyRequest() .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(downPolicyName); autoScalingGroupClient.deletePolicy(downPolicyDeleteRequest); System.out.println("Policies deleted..."); // delete alarms DeleteAlarmsRequest alarmsDeleteRequest = new DeleteAlarmsRequest().withAlarmNames(upAlarmName, downAlarmName); cloudWatchClient.deleteAlarms(alarmsDeleteRequest); System.out.println("Alarms deleted..."); // delete load balancer DeleteLoadBalancerRequest lgDeleteRequest = new DeleteLoadBalancerRequest() .withLoadBalancerName(loadBalancerName); loadBalancerClient.deleteLoadBalancer(lgDeleteRequest); System.out.println("Load generator deleted..."); // delete ASG DeleteAutoScalingGroupRequest asgDeleteRequest = new DeleteAutoScalingGroupRequest() .withForceDelete(true).withAutoScalingGroupName(autoScalingGroupName); autoScalingGroupClient.deleteAutoScalingGroup(asgDeleteRequest); System.out.println("ASG deleted..."); // delete launch configuration DeleteLaunchConfigurationRequest launchConfigDeleteRequest = new DeleteLaunchConfigurationRequest() .withLaunchConfigurationName(launchConfigName); autoScalingGroupClient.deleteLaunchConfiguration(launchConfigDeleteRequest); System.out.println("Launch configuration deleted..."); // delete security group DeleteSecurityGroupRequest sgDeleteRequest = new DeleteSecurityGroupRequest() .withGroupName(allPurposeSecurityName); ec2.deleteSecurityGroup(sgDeleteRequest); System.out.println("Security group deleted..."); /** * ======================================================================= * =================== All done * ======================================================================= * =================== */ System.out.println("All done :)"); } catch (AmazonServiceException ase) { // Write out any exceptions that may have occurred. 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()); } catch (Exception e) { System.out.println("Unexcepted error!"); System.out.println(e.getMessage()); } }
From source file:SecurityGroup.java
License:Open Source License
public void create(String groupName) { AWSCredentials credentials = null;/*from ww w .ja v a 2 s. co m*/ try { credentials = new ProfileCredentialsProvider("School").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 (C:\\Users\\Jiabei\\.aws\\credentials), and is in valid format.", e); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); Region usEast1 = Region.getRegion(Regions.US_EAST_1); ec2.setRegion(usEast1); // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(groupName, "Security created for P2"); CreateSecurityGroupResult result = ec2.createSecurityGroup(securityGroupRequest); System.out.println(String.format("Security group created: [%s]", result.getGroupId())); groupId = result.getGroupId(); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } // Create a range that you would like to populate. List<String> ipRanges = Collections.singletonList("0.0.0.0/0"); // Open all port IpPermission ipPermission = new IpPermission().withIpProtocol("-1").withFromPort(new Integer(0)) .withToPort(new Integer(65535)).withIpRanges(ipRanges); List<IpPermission> ipPermissions = Collections.singletonList(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( groupName, ipPermissions); ec2.authorizeSecurityGroupIngress(ingressRequest); System.out.println(String.format("Ingress port authroized: [%s]", ipPermissions.toString())); } catch (AmazonServiceException ase) { // Ignore because this likely means the zone has already been authorized. System.out.println(ase.getMessage()); } }
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/*from w ww .ja v a2 s . 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:AwsSample.java
License:Open Source License
public static void main(String[] args) throws Exception { BasicAWSCredentials credentials = new BasicAWSCredentials("", ""); /********************************************* * /*from ww w . j a v a 2 s . c o m*/ * #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
/** * 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 */// w w w.ja v a2 s .c om private static void init() throws Exception { AWSCredentials credentials = new PropertiesCredentials( AwsConsoleApp.class.getResourceAsStream("AwsCredentials.properties")); ec2 = new AmazonEC2Client(credentials); s3 = new AmazonS3Client(credentials); sdb = new AmazonSimpleDBClient(credentials); }
From source file:InlineGettingStartedCodeSampleApp.java
License:Open Source License
public static void main(String[] args) { //============================================================================================// //=============================== Submitting a Request =======================================// //============================================================================================// /*/* www.j av a 2 s . co m*/ * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (/Users/zunzunwang/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (/Users/zunzunwang/.aws/credentials), and is in valid format.", e); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); ec2.setRegion(usWest2); // 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()); } //============================================================================================// //=========================== 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()); } }