Example usage for com.amazonaws.services.ec2.model TerminateInstancesRequest TerminateInstancesRequest

List of usage examples for com.amazonaws.services.ec2.model TerminateInstancesRequest TerminateInstancesRequest

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model TerminateInstancesRequest TerminateInstancesRequest.

Prototype

public TerminateInstancesRequest(java.util.List<String> instanceIds) 

Source Link

Document

Constructs a new TerminateInstancesRequest object.

Usage

From source file:AwsSample.java

License:Open Source License

public static void main(String[] args) throws Exception {

    BasicAWSCredentials credentials = new BasicAWSCredentials("", "");

    /*********************************************
     * /*from w  w 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:InlineGettingStartedCodeSampleApp.java

License:Open Source License

public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

    /*//from w  w w  .  j  a  va 2s  .  c om
     * 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());
    }

}

From source file:HW1.java

License:Open Source License

public static void main(String[] args) throws Exception {

    AWSCredentials credentials = new PropertiesCredentials(
            HW1.class.getResourceAsStream("AwsCredentials.properties"));

    /*********************************************
     * /*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);
    ec2.setEndpoint("https://us-east-1.ec2.amazonaws.com");

    System.out.println("Please enter required group name and key name... (consider them to be the same)");
    Scanner scan = new Scanner(System.in);
    final String keyGroupName = scan.nextLine();

    /* create security group */
    CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest();
    createSecurityGroupRequest.withGroupName(keyGroupName).withDescription("My Java Security Group");
    CreateSecurityGroupResult createSecurityGroupResult = ec2.createSecurityGroup(createSecurityGroupRequest);

    /* set ip settings */
    IpPermission ipPermission = new IpPermission();
    /* authorize tcp, ssh 22 */
    ipPermission.withIpRanges("0.0.0.0/0").withIpProtocol("tcp").withFromPort(22)
            /* authorize http 80 */
            .withToPort(80);

    AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();
    authorizeSecurityGroupIngressRequest.withGroupName(keyGroupName).withIpPermissions(ipPermission);
    ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    /* create key pair */
    CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();
    createKeyPairRequest.withKeyName(keyGroupName);
    CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);
    KeyPair keyPair = new KeyPair();
    keyPair = createKeyPairResult.getKeyPair();
    String privateKey = keyPair.getKeyMaterial();
    PrintWriter file = new PrintWriter("/Users/will/.ssh/" + keyGroupName + ".pem");
    file.print(privateKey);
    file.close();
    Runtime.getRuntime().exec("chmod 400 /Users/will/.ssh/" + keyGroupName + ".pem");

    try {

        /*********************************************
         * 
         *  #2 Create two Instances
         *  
         *********************************************/
        System.out.println();
        System.out.println("#2 Create two new Instances");
        int ready_num = 0;
        String insDNS1 = new String();
        String insDNS2 = new String();
        String insId1 = new String();
        String insId2 = new String();
        String insZone1 = new String();
        String insZone2 = new String();

        String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI
        int minInstanceCount = 2; // create 2 instance
        int maxInstanceCount = 2;

        /* create instances */
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.withKeyName(keyGroupName).withSecurityGroups(keyGroupName);
        ec2.runInstances(rir);

        /* waiting for instance to start */
        System.out.println("Created instance, wait for pending...");

        DescribeInstancesResult describeInstancesRequest;
        List<Reservation> reservations;
        List<Instance> allInstances = new ArrayList<Instance>();

        while (ready_num < 2) {
            describeInstancesRequest = ec2.describeInstances();
            reservations = describeInstancesRequest.getReservations();
            for (Reservation reservation : reservations) {
                for (Instance ins : reservation.getInstances()) {
                    if (ins.getState().getName().compareTo("running") == 0
                            && ins.getPublicIpAddress() != null) {
                        if (allInstances.size() == 0 || (allInstances.size() > 0
                                && allInstances.get(0).getInstanceId().compareTo(ins.getInstanceId()) != 0)) {
                            ready_num++;
                            allInstances.add(ins);
                        }
                    }
                }
            }
        }

        System.out.println("You have " + allInstances.size() + " Amazon EC2 instance(s).");
        insId1 = allInstances.get(0).getInstanceId();
        insId2 = allInstances.get(1).getInstanceId();
        insDNS1 = allInstances.get(0).getPublicIpAddress();
        insDNS2 = allInstances.get(1).getPublicIpAddress();
        insZone1 = allInstances.get(0).getPlacement().getAvailabilityZone();
        insZone2 = allInstances.get(1).getPlacement().getAvailabilityZone();

        for (Instance ins : allInstances) {
            System.out.println("New instance has been created: " + ins.getInstanceId());
        }

        System.out.println("Both instances are running now:");
        System.out.println("Instance id1: " + insId1);
        System.out.println("IP: " + insDNS1);
        System.out.println("Zone: " + insZone1);
        System.out.println("Instance id1: " + insId2);
        System.out.println("IP: " + insDNS2);
        System.out.println("Zone: " + insZone2);
        System.out.println();

        /*********************************************
         *  #3 Check OR Create two volumes
         *********************************************/
        System.out.println();
        System.out.println("#3 Create volumes");
        String volume_name1 = createVolume(insZone1, null);
        String volume_name2 = createVolume(insZone2, null);

        /*********************************************
         *  #4 Attach the volume to the instance
         *********************************************/
        System.out.println();
        System.out.println("#4 Attach the volume to the instance");
        System.out.println("Wait for volumes to be available...");
        Thread.sleep(20000);

        /* attach instances to existing volume */
        attachVolume(insId1, volume_name1);
        attachVolume(insId2, volume_name2);

        /************************************************
        *  #5 S3 bucket and object
        ***************************************************/
        System.out.println();
        System.out.println("#5 S3 bucket and object");
        s3 = new AmazonS3Client(credentials);

        /* create bucket */
        String bucketName = "cloud-hw1-bucket";
        s3.createBucket(bucketName);

        /* set key */
        String key = "object-hw1.txt";

        /* set value */
        File new_file = File.createTempFile("temp", ".txt");
        new_file.deleteOnExit();
        Writer writer = new OutputStreamWriter(new FileOutputStream(new_file));
        writer.write("This is the file stored on the S3 storage on the first day!!!.");
        writer.close();

        /* put object - bucket, key, value(file) */
        s3.putObject(new PutObjectRequest(bucketName, key, new_file));
        System.out.println("Successfully put file temp.txt to S3, we will read it tomorrow...");
        System.out.println();

        /***********************************
        *   #3 Monitoring (CloudWatch)
        *********************************/
        System.out.println();
        System.out.println("#6 set up cloudwatch");
        try {
            /* create CloudWatch client */
            AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(credentials);
            /* create request message1 */
            GetMetricStatisticsRequest statRequest1 = new GetMetricStatisticsRequest();
            GetMetricStatisticsRequest statRequest2 = new GetMetricStatisticsRequest();
            /* set up request message */
            statRequest1.setNamespace("AWS/EC2"); //namespace
            statRequest2.setNamespace("AWS/EC2"); //namespace
            statRequest1.setPeriod(60); //period of data
            statRequest2.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");
            statRequest1.setStatistics(stats);
            statRequest2.setStatistics(stats);
            /* Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations  */
            statRequest1.setMetricName("CPUUtilization");
            statRequest2.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();
            statRequest1.setStartTime(startTime);
            statRequest1.setEndTime(endTime);
            statRequest2.setStartTime(startTime);
            statRequest2.setEndTime(endTime);
            /* specify an instance */
            ArrayList<Dimension> dimensions1 = new ArrayList<Dimension>();
            dimensions1.add(new Dimension().withName("InstanceId").withValue(insId1));
            ArrayList<Dimension> dimensions2 = new ArrayList<Dimension>();
            dimensions2.add(new Dimension().withName("InstanceId").withValue(insId2));
            statRequest1.setDimensions(dimensions1);
            statRequest2.setDimensions(dimensions2);
            System.out.println("Set up cloud watch for instance: " + insId1 + " and instance: " + insId2);

            /* !!!!!!!!!!!!here set for 10 loops for now */
            /* get statistics */
            for (int i = 0; i < 10; i++) {
                GetMetricStatisticsResult statResult1 = cloudWatch.getMetricStatistics(statRequest1);
                GetMetricStatisticsResult statResult2 = cloudWatch.getMetricStatistics(statRequest2);
                /* display */
                System.out.println("Instance 1: " + statResult1.toString());
                List<Datapoint> dataList = statResult1.getDatapoints();
                Double averageCPU = null;
                Date timeStamp = null;
                for (Datapoint d : dataList) {
                    averageCPU = d.getAverage();
                    timeStamp = d.getTimestamp();
                    System.out
                            .println("Instance 1 average CPU utlilization for last 10 minutes: " + averageCPU);
                    System.out.println("Instance 1 total CPU utlilization for last 10 minutes: " + d.getSum());
                }
                System.out.println();
                System.out.println("Instance 2: " + statResult1.toString());
                dataList = statResult2.getDatapoints();
                for (Datapoint d : dataList) {
                    averageCPU = d.getAverage();
                    timeStamp = d.getTimestamp();
                    System.out
                            .println("Instance 2 average CPU utlilization for last 10 minutes: " + averageCPU);
                    System.out.println("Instance 2 total CPU utlilization for last 10 minutes: " + d.getSum());
                }
            }

        } 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());
        }

        /***********************************
        *   # Copy script to 
        *       instance and run
        *********************************/
        System.out.println();
        System.out.println("Waiting for init and automatically SSH...");
        /* call runtime exec to run scp */
        execCmdRuby(insDNS1, keyGroupName);

        /***********************************
        *   # Save instances to image
        *********************************/
        System.out.println();
        System.out.println("******* Approaching 5:00 pm, create ami for instances *********");
        String imageId1;
        String imageId2;
        String snapshot1;
        String snapshot2;

        imageId1 = createAmiFromInstance(insId1, "image1", true);
        imageId2 = createAmiFromInstance(insId2, "image2", true);
        System.out.println("Created first image id: " + imageId1);
        System.out.println("Created second image id: " + imageId2);

        snapshot1 = createSnapShotFromVolume(volume_name1);
        snapshot2 = createSnapShotFromVolume(volume_name2);
        System.out.println("Created first snapshot id: " + snapshot1);
        System.out.println("Created second snapshot id: " + snapshot2);

        /*********************************************
         * 
         *  # Stop Instances
         *  
         *********************************************/
        System.out.println();
        System.out.println("#7 Stop & terminate the Instance");
        List<String> instanceIds = new LinkedList<String>();
        instanceIds.add(insId1);
        instanceIds.add(insId2);
        /* stop instances */
        StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
        ec2.stopInstances(stopIR);
        TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(tir);

        /*********************************************
         * 
         *  # Detach volumes
         *  
         *********************************************/
        System.out.println();
        System.out.println("Detach the volumes from the instances...");
        deatchVolume(insId1, volume_name1);
        deatchVolume(insId2, volume_name2);

        /*********************************************
          * 
          *  # Delete Volumes
          *  
          *********************************************/
        System.out.println();

        while (true) {
            if (getVolumeState(volume_name1).compareTo("available") == 0
                    && getVolumeState(volume_name2).compareTo("available") == 0)
                break;
        }
        System.out.println("Delete volumes...");
        Thread.sleep(10000);
        deleteVolume(volume_name1);
        deleteVolume(volume_name2);

        /*********************************************
          * 
          *  # Second day restore instances and volumes
          *  
          *********************************************/
        System.out.println();
        System.out.println("#8 Second day start up instances from stored amis...");
        String newInsId1 = "";
        String newInsId2 = "";
        String newInsIP1 = "";
        String newInsIP2 = "";
        String newInsZone1 = "";
        String newInsZone2 = "";

        newInsId1 = createInstanceFromImageId(imageId1, keyGroupName);
        newInsId2 = createInstanceFromImageId(imageId2, keyGroupName);
        System.out.println("Second day first instance has been restored with id: " + newInsId1);
        System.out.println("Second day second instance has been restored with id: " + newInsId2);
        newInsZone1 = getInstanceZone(newInsId1);
        newInsZone2 = getInstanceZone(newInsId2);
        System.out.println("New instance 1 zone: " + newInsZone1);
        System.out.println("New instance 2 zone: " + newInsZone2);
        newInsIP1 = getInstanceIP(newInsId1);
        newInsIP2 = getInstanceIP(newInsId2);
        System.out.println("New instance 1 IP: " + newInsIP1);
        System.out.println("New instance 2 IP: " + newInsIP2);

        Thread.sleep(120000);
        /* exec read */
        System.out.println();
        System.out.println("Now start to read the file stored yesterday...");
        execCmdRead(newInsIP1, keyGroupName);

        /*********************************************
         *  
         *  #9 Read data from S3
         *  
         *********************************************/

        /* get the object from the first day */
        System.out.println();
        System.out.println("#9 Reading data from S3 stored on the first day");
        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);
        }

        /*********************************************
         *  
         *  #10 shutdown client object
         *  
         *********************************************/
        System.out.println("#10 shutdown client objects");
        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:virtualIT.java

License:Open Source License

private void groupStopInstance(int userId, int n) throws InterruptedException {
    /*********************************************
      * //from  ww  w  .  ja va  2s.com
      *  #8 Stop/Start an Instance
      *  
      *********************************************/
    System.out.print("Stop Instance");
    //List<Instance> resultInstance = result.getReservation().getInstances();
    //List<String> instanceIds = new LinkedList<String>();
    //String createdInstanceId = null;
    //  for (Instance ins : resultInstance){   
    //     createdInstanceId = ins.getInstanceId();
    //  System.out.println("#7 Stop the Instance");
    //  instanceIds.add(createdInstanceId);  
    //  }
    String instanceId = mapUserInst.get(userId);
    List<String> instanceIds = new LinkedList<String>();
    instanceIds.add(instanceId);
    switch (n) {
    case 1:
        //stop
        StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
        ec2.stopInstances(stopIR);
        Thread.sleep(1000);
    case 2:
        //Start
        StartInstancesRequest startIR = new StartInstancesRequest(instanceIds);
        ec2.startInstances(startIR);
    case 3:
        //Terminate
        System.out.println("#8 Terminate the Instance");
        TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(tir);
        Thread.sleep(10000);
        mapUserInst.remove(userId);
    }
    System.out.print("Stop Instance done");

}

From source file:InlineGettingStartedCodeApp.java

License:Open Source License

/**
 * @param args/*  w w  w . j a  va2 s  . c  om*/
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    ec2.setRegion(usEast1);

    // 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-700e4a19");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("ForAssignment2");
    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:InlineTaggingCodeApp.java

License:Open Source License

/**
 * @param args/*  w  w w .  ja  va2  s.com*/
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    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-700e4a19");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("ForAssignment2");
    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:EC2.java

License:Apache License

public void terminateInstances(List<String> instanceIDs) {
    try {// w  ww  .  j a va2  s .  c  om
        System.out.println("Terminate instances");
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIDs);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        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:InlineTaggingCodeSampleApp.java

License:Open Source License

public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

    /*//from  w  ww  .ja va2s.  c  om
     * The ProfileCredentialsProvider will return your [haow2]
     * credential profile by reading from the credentials file located at
     * (/Users/Dawn/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("haow2").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/Dawn/.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());
    }

    //============================================================================================//
    //====================================== 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: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  ww  .ja v  a2 s  . co m*/
     *  #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:EC2InstanceLaunch.java

License:Open Source License

private static void changeInstanceState(String instanceId, instanceState state) {

    List<String> instanceIds = new LinkedList<String>();
    instanceIds.add(instanceId);//from   ww w  . j  av  a 2 s. c o m

    if (state == instanceState.stop) {
        //stop
        System.out.println("# Stop the Instance");
        StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
        ec2.stopInstances(stopIR);
    } else if (state == instanceState.start) {
        //start
        System.out.println("# Start the Instance");
        StartInstancesRequest startIR = new StartInstancesRequest(instanceIds);
        ec2.startInstances(startIR);
    } else if (state == instanceState.terminate) {
        //terminate
        System.out.println("# Terminate the Instance");
        TerminateInstancesRequest terminateIR = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateIR);
    } else if (state == instanceState.reboot) {
        //terminate
        System.out.println("# Reboot the Instance");
        RebootInstancesRequest rebootIR = new RebootInstancesRequest(instanceIds);
        ec2.rebootInstances(rebootIR);
    }

}