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

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

Introduction

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

Prototype

public Tag(String key, String value) 

Source Link

Document

Constructs a new Tag object.

Usage

From source file:DynamicProvisioner.java

License:Apache License

static long launchAndWaitUntilRunning(EC2 ec2, int num, double price)
        throws InterruptedException, UnsupportedEncodingException {
    long startTime = System.currentTimeMillis();
    List<String> sgs = new ArrayList<String>();
    for (String securityGroup : securityGroups)
        sgs.add(securityGroup);/*w w w . ja  v  a 2 s. co  m*/
    List<String> spotInstanceRequestIds = null;
    List<String> instanceIDs = null;
    boolean ifContinue = true;
    while (ifContinue) {
        spotInstanceRequestIds = ec2.launch(workerAMI, instanceType, num, price, sgs, keyName, userData,
                charset);
        long rTime = System.currentTimeMillis();
        while (instanceIDs == null) {
            if (System.currentTimeMillis() - rTime > newSpotInstanceRequestTolerateTime)
                break;
            instanceIDs = ec2.getActiveSpotInstanceId(spotInstanceRequestIds);
            Thread.sleep(1000 * 10);
        }
        if (instanceIDs == null || instanceIDs.size() == 0) {
            System.out.println("Request exceeded tolerance time or failed, update price to " + price
                    + " and restart request again!");
            ec2.cancelRequest(spotInstanceRequestIds);
            price += 0.5;
        } else {
            List<Tag> tags = new ArrayList<Tag>();
            tags.add(workerTag);
            tags.add(new Tag("Name", "remoteWorker"));
            ec2.tagResources(instanceIDs, tags);
            long iTime = System.currentTimeMillis();
            ifContinue = false;
            while (ec2.ifInstancePending(instanceIDs)) {
                if (System.currentTimeMillis() - iTime > newSpotInstanceStartTolerateTime) {
                    System.out.println("Instance-starting exceeded tolerance time, restart request again!");
                    ec2.cancelRequest(spotInstanceRequestIds);
                    //                  ec2.terminateInstances(instanceIDs);
                    ifContinue = true;
                }
                Thread.sleep(1000 * 10);
            }

        }
    }
    return System.currentTimeMillis() - startTime;
}

From source file:AwsSample.java

License:Open Source License

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

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

    /*********************************************
     * //from www .j a va  2  s . co 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:AWS.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    // Group handealing

    List<String> groupID = new ArrayList<String>();
    String Temp_Group = "sg-aa5efdcf";

    groupID.add(Temp_Group);//wait to out our instance into this group

    System.out.println("#5 Create an Instance");
    String imageId = "ami-08be1f7f";//  
    int minInstanceCount = 1; // create 1 instance
    int maxInstanceCount = 1;
    RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);

    rir.setInstanceType("t2.micro");
    rir.setKeyName("14_LP1_KEY_D7001D_aledem-4");// give the instance the key we just created
    // rir.setSecurityGroups(groupName);// set the instance in the group we just created
    rir.setSecurityGroupIds(groupID);//from  w  w w .  j  a  v a 2 s  . co m
    rir.setSubnetId("subnet-47ca2d1e");

    RunInstancesResult result = ec2client.runInstances(rir);

    /***********to make sure the instance's state is "running instead of "pending",**********/
    /***********we wait for a while                                                **********/
    System.out.println("waiting");
    try {
        Thread.currentThread().sleep(60000);
    } catch (InterruptedException ex) {
        Logger.getLogger(AWS.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("OK");

    List<Instance> resultInstance = result.getReservation().getInstances();

    String createdInstanceId = null;
    for (Instance ins : resultInstance) {

        createdInstanceId = ins.getInstanceId();
        String createdInstanceIp = ins.getPublicDnsName();

        System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID

    }

    System.out.println("#6 Create a 'tag' for the new instance.");
    List<String> resources = new LinkedList<>();
    List<Tag> tags = new LinkedList<>();
    Tag nameTag = new Tag("Name", "FromCoordinator");

    resources.add(createdInstanceId);
    tags.add(nameTag);

    CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
    ec2client.createTags(ctr);

    fetchInstanceInfo(createdInstanceId);
}

From source file:InlineTaggingCodeApp.java

License:Open Source License

/**
 * @param args/*  ww w.  j  a v  a 2 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 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:AwsHori.java

License:Open Source License

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

    // initialize/determine parameters
    String instanceType = "m3.medium";
    String lgAmi = "ami-8ac4e9e0";
    String dcAmi = "ami-349fbb5e";
    String bidPrice = "0.1";
    String securityGroup = "Project2";
    String lgDns = null; // load generator DNS
    String dcDns = null; // data center DNS
    String dashboardUrl = null; // the URL for dashboard
    String testId = null;/*from w w  w . j  av  a  2s .  c o  m*/
    int rps = 0; // total RPS

    // create a list of tags
    ArrayList<Tag> requestTags = new ArrayList<Tag>();
    requestTags.add(new Tag("Project", "2.1"));

    // create a security group
    SecurityGroup proj2 = new SecurityGroup(securityGroup);

    try {

        // create a load generator instance and return its DNS
        Requests requestsLg = new Requests(instanceType, lgAmi, bidPrice, securityGroup, requestTags);
        lgDns = requestsLg.submitRequests();

        // submit and start the test
        String submissionUrl = "http://" + lgDns
                + "/password?passwd=0WSb4ufhYI7SkxfLWnnIWU0MC1NdcNKT&andrewId=jiabeip";
        sendGET(submissionUrl);

        // create the first data center instance and return its DNS
        Requests requestsDc1 = new Requests(instanceType, dcAmi, bidPrice, securityGroup, requestTags);
        dcDns = requestsDc1.submitRequests();

        // add the data center to the test and find our test ID
        String firstDataCenter = "http://" + lgDns + "/test/horizontal?dns=" + dcDns;
        testId = sendGET(firstDataCenter);
        System.out.println("Test ID is: " + testId);

        // get the dashboard URL
        dashboardUrl = "http://" + lgDns + "/log?name=test." + testId + ".log";

        // waiting period between instance creations
        Thread.sleep(WAIT_CYCLE);

        // create more data centers until RPS reaches 4000
        do {

            // create new instances 
            Requests requestsDcMore = new Requests(instanceType, dcAmi, bidPrice, securityGroup, requestTags);
            dcDns = requestsDcMore.submitRequests();

            // add new instance to the test
            String scaleOut = "http://" + lgDns + "/test/horizontal/add?dns=" + dcDns;
            sendGET(scaleOut);

            // get RPS from the dashboard
            rps = getRps(dashboardUrl);
            System.out.println("Current RPS: " + rps);

            Thread.sleep(WAIT_CYCLE);
        } while (rps < 4000);

        System.out.println("Test complete!");

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

From source file:InlineTaggingCodeSampleApp.java

License:Open Source License

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

    /*/*www  .j  a v a  2 s .co  m*/
     * 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 w  w. j a  v  a2  s .  c  o 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 createTag(String instanceId, String tagName, String tagValue) {
    System.out.println("# Create a 'tag' for the new instance.");
    List<String> resources = new LinkedList<String>();
    List<Tag> tags = new LinkedList<Tag>();
    Tag nameTag = new Tag(tagName, tagValue);

    resources.add(instanceId);//from w  w w.j  a  v  a2  s  . com
    tags.add(nameTag);

    CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
    ec2.createTags(ctr);

}

From source file:advanced.GettingStartedApp.java

License:Open Source License

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

    System.out.println("===========================================");
    System.out.println("Welcome to the AWS Java SDK!");
    System.out.println("===========================================");

    /*//from   w w w .  java  2s  .com
     * Amazon EC2
     *
     * The AWS EC2 client allows you to create, delete, and administer
     * instances programmatically.
     *
     * In this sample, we use an EC2 client to submit a Spot request,
     * wait for it to reach the active state, and then cancel and terminate
     * the associated instance.
     */
    try {
        // Setup the helper object that will perform all of the API calls.
        Requests requests = new Requests("t1.micro", "ami-8c1fece5", "0.03", "GettingStartedGroup");

        // Submit all of the requests.
        requests.submitRequests();

        // Create the list of tags we want to create and tag any associated requests.
        ArrayList<Tag> tags = new ArrayList<Tag>();
        tags.add(new Tag("keyname1", "value1"));
        requests.tagRequests(tags);

        // Initialize the timer to now.
        Calendar startTimer = Calendar.getInstance();
        Calendar nowTimer = null;

        // Loop through all of the requests until all bids are in the active state 
        // (or at least not in the open state).
        do {
            // Sleep for 60 seconds.
            Thread.sleep(SLEEP_CYCLE);

            // Initialize the timer to now, and then subtract 15 minutes, so we can 
            // compare to see if we have exceeded 15 minutes compared to the startTime. 
            nowTimer = Calendar.getInstance();
            nowTimer.add(Calendar.MINUTE, -15);
        } while (requests.areAnyOpen() && !nowTimer.after(startTimer));

        // If we couldn't launch Spot within the timeout period, then we should launch an On-Demand
        // Instance.
        if (nowTimer.after(startTimer)) {
            // Cancel all requests because we timed out.
            requests.cleanup();

            // Launch On-Demand instances instead
            requests.launchOnDemand();
        }

        // Tag any created instances.
        requests.tagInstances(tags);

        // Cancel all requests and terminate all running instances.
        requests.cleanup();
    } 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());
    }
}

From source file:advanced.InlineTaggingCodeSampleApp.java

License:Open Source License

/**
 * @param args/*  w w  w. j  ava2  s.  co  m*/
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================// 
    //============================================================================================//

    // Retrieves the credentials from an AWSCredentials.properties file.
    AWSCredentials credentials = null;
    try {
        credentials = new PropertiesCredentials(
                InlineTaggingCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties"));
    } catch (IOException e1) {
        System.out.println("Credentials were not properly entered into AwsCredentials.properties.");
        System.out.println(e1.getMessage());
        System.exit(-1);
    }

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

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

}