Example usage for com.amazonaws AmazonServiceException getStatusCode

List of usage examples for com.amazonaws AmazonServiceException getStatusCode

Introduction

In this page you can find the example usage for com.amazonaws AmazonServiceException getStatusCode.

Prototype

public int getStatusCode() 

Source Link

Document

Returns the HTTP status code that was returned with this service exception.

Usage

From source file:EC2.java

License:Apache License

public List<String> getActiveSpotInstanceId(List<String> spotInstanceRequestIds) {
    DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
    describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

    System.out.println("Checking to determine if Spot Bids have reached the active state...");

    List<String> instanceIds = new ArrayList<String>();

    try {//from  w w  w .  j  av a2  s  .co m
        DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest);
        List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

        for (SpotInstanceRequest describeResponse : describeResponses) {
            System.out.println(" " + describeResponse.getSpotInstanceRequestId() + " is in the "
                    + describeResponse.getState() + " state.");

            if (describeResponse.getState().equals("open"))
                return null;

            if (describeResponse.getState().equals("active"))
                instanceIds.add(describeResponse.getInstanceId());
        }
    } catch (AmazonServiceException e) {
        System.out.println("Error when calling describeSpotInstances");
        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());

        return null;
    }
    return instanceIds;
}

From source file:EC2.java

License:Apache License

public void tagResources(List<String> resources, List<Tag> tags) {
    CreateTagsRequest createTagsRequest = new CreateTagsRequest();
    createTagsRequest.setResources(resources);
    createTagsRequest.setTags(tags);//from  w w w . j a  va2 s  .co  m
    try {
        ec2.createTags(createTagsRequest);
    } 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:EC2.java

License:Apache License

public void cancelRequest(List<String> spotInstanceRequestIds) {
    try {/*from   w  ww . j a  va2s .  c  o m*/
        System.out.println("Cancelling requests.");
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        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());
    }
}

From source file:EC2.java

License:Apache License

public void terminateInstances(List<String> instanceIDs) {
    try {//  ww  w. ja  v  a  2s. co m
        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:AwsEc2Demo.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("===========================================");

    init();/*from www.jav a2  s .  c om*/

    /*
     * Amazon EC2
     *
     * The AWS EC2 client allows you to create, delete, and administer
     * instances programmatically.
     *
     * In this sample, we use an EC2 client to get a list of all the
     * availability zones, and all instances sorted by reservation id.
     */
    try {
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");

        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();

        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
    } 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:PutFile.java

License:Apache License

public static void main(String[] args) throws IOException {
    /*/*from w  w w  .  j a v  a  2s .c  om*/
     * Important: Be sure to fill in your AWS access credentials in the
     * AwsCredentials.properties file before you try to run this sample.
     * http://aws.amazon.com/security-credentials
     */
    AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(

            PutFile.class.getResourceAsStream("AwsCredentials.properties")));
    String bucketName = "dtccTest";

    System.out.println("===========================================");
    System.out.println(" Amazon S3 Test");
    System.out.println("===========================================\n");

    try {

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();
        String fileName = "S3HWTest.zip";
        File file = new File(fileName);
        System.out.println("Uploading a new object to S3 from a file " + fileName + "\n");
        System.out.println("file.length() " + file.length() + "\n");

        long start = System.currentTimeMillis();
        PutObjectRequest request = new PutObjectRequest(bucketName, fileName, file);
        request.setCannedAcl(CannedAccessControlList.PublicRead);
        s3.putObject(request);
        System.out.println("Uploading done in " + (System.currentTimeMillis() - start) + " ms.\n");

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, whichmeans your request made it "
                + "to Amazon S3, but was rejected with an errorresponse for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, whichmeans the client encountered "
                + "a serious internal problem while trying tocommunicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:GetTestFile.java

License:Apache License

public static void main(String[] args) throws IOException {
    /*//from ww w.  ja  va  2s  . c o  m
     * Important: Be sure to fill in your AWS access credentials in the
     * AwsCredentials.properties file before you try to run this sample.
     * http://aws.amazon.com/security-credentials
     */
    AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(

            GetTestFile.class.getResourceAsStream("AwsCredentials.properties")));

    String bucketName = "dtccTest";

    String key = "largerfile.txt";

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================\n");

    try {

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        System.out.println("Downloading an object");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        System.out.println("ContentEncod: " + object.getObjectMetadata().getContentEncoding());
        System.out.println("ContentLengt: " + object.getObjectMetadata().getContentLength());
        System.out.println("ContentDisp: " + object.getObjectMetadata().getContentDisposition());

        displayTextInputStream(object.getObjectContent());

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, whichmeans your request made it "
                + "to Amazon S3, but was rejected with an errorresponse for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, whichmeans the client encountered "
                + "a serious internal problem while trying tocommunicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

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 .  j  a va  2  s . c om*/
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);

    /*********************************************
     * Added By Chenyun Zhang
     *  # Create an Amazon EC2 Security Group
     *  
     *********************************************/
    System.out.println("#1 Create an Amazon EC2 Security Group");
    CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest();

    createSecurityGroupRequest.withGroupName("JavaSecurityGroup").withDescription("My Java Security Group");

    CreateSecurityGroupResult createSecurityGroupResult = ec2.createSecurityGroup(createSecurityGroupRequest);

    /*********************************************
     * Added By Chenyun Zhang
     *  # Authorize Security Group Ingress
     *  
     *********************************************/
    System.out.println("#2 Authorize Security Group Ingress");

    ArrayList<IpPermission> ipPermission = new ArrayList<IpPermission>();

    //SSH
    IpPermission ipssh = new IpPermission();
    ipssh.setIpProtocol("tcp");
    ipssh.setFromPort(new Integer(22));
    ipssh.setToPort(new Integer(22));
    //ipssh.withIpRanges(ipRanges);
    ipssh.withIpRanges("72.69.22.123/32");
    ipPermission.add(ipssh);

    //HTTP
    IpPermission iphttp = new IpPermission();

    iphttp.setIpProtocol("tcp");
    iphttp.setFromPort(new Integer(80));
    iphttp.setToPort(new Integer(80));
    iphttp.withIpRanges("0.0.0.0/0");
    ipPermission.add(iphttp);

    //TCP
    IpPermission iptcp = new IpPermission();
    iptcp.setIpProtocol("tcp");
    iptcp.setFromPort(new Integer(49152));
    iptcp.setToPort(new Integer(49152));
    iptcp.withIpRanges("0.0.0.0/0");
    ipPermission.add(iptcp);

    AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();

    authorizeSecurityGroupIngressRequest.withGroupName("JavaSecurityGroup").withIpPermissions(ipPermission);

    ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    /*********************************************
     * Added By Chenyun Zhang
     *  # Create a Key Pair
     *  
     *********************************************/
    System.out.println("#3 Create a Key Pair");

    CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();

    createKeyPairRequest.withKeyName("HW2");

    CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);

    KeyPair keyPair = new KeyPair();

    keyPair = createKeyPairResult.getKeyPair();

    String privateKey = keyPair.getKeyMaterial();

    //Calling createKeyPair is the only way to obtain the private key programmatically.
    /*********************************************
     * Added By Chenyun Zhang
     *  # Download KeyPair
     *  
     *********************************************/
    PrintWriter Storekey = new PrintWriter(
            "/Users/Annabelle/Documents/NYU-POLY/3/Cloud Computing/HW2" + "/" + "Hw2" + ".pem", "UTF-8");
    Storekey.print(privateKey);
    Storekey.close();
    System.out.println("Already store the key!");

    try {

        /*********************************************
         * 
          *  #2 Describe Availability Zones.
          *  
          *********************************************/
        System.out.println("#2 Describe Availability Zones.");
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");

        /*********************************************
         * 
         *  #3 Describe Available Images
         *  
         *********************************************/
        System.out.println("#3 Describe Available Images");
        DescribeImagesResult dir = ec2.describeImages();
        List<Image> images = dir.getImages();
        System.out.println("You have " + images.size() + " Amazon images");

        /*********************************************
         *                 
         *  #4 Describe Key Pair
         *                 
         *********************************************/
        System.out.println("#9 Describe Key Pair");
        DescribeKeyPairsResult dkr = ec2.describeKeyPairs();
        System.out.println(dkr.toString());

        /*********************************************
         * 
         *  #5 Describe Current Instances
         *  
         *********************************************/
        System.out.println("#4 Describe Current Instances");
        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();
        // add all instances to a Set.
        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s).");
        for (Instance ins : instances) {

            // instance id
            String instanceId = ins.getInstanceId();

            // instance state
            InstanceState is = ins.getState();
            System.out.println(instanceId + " " + is.getName());
        }

        /*********************************************
         * 
         *  #6 Create an Instance
         *  
         *********************************************/
        System.out.println("#5 Create an Instance");
        String imageId = "ami-76f0061f"; //Basic 64-bit Amazon Linux AMI
        int minInstanceCount = 1; // create 1 instance
        int maxInstanceCount = 1;
        //RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        RunInstancesRequest rir = new RunInstancesRequest();
        rir.withImageId(imageId).withInstanceType("t1.micro").withMinCount(minInstanceCount)
                .withMaxCount(maxInstanceCount).withKeyName("HW2").withSecurityGroups("JavaSecurityGroup");
        RunInstancesResult result = ec2.runInstances(rir);

        /*********************************************
         * Added by Chenyun Zhang
         *  # Get the public Ip address
         *  
         *********************************************/
        //get instanceId from the result
        List<Instance> resultInstance = result.getReservation().getInstances();
        String createdInstanceId = null;
        for (Instance ins : resultInstance) {
            createdInstanceId = ins.getInstanceId();
            System.out.println("New instance has been created: " + ins.getInstanceId());

            //DescribeInstancesRequest and get ip
            String createdInstanceIp = null;
            while (createdInstanceIp == null) {
                System.out.println("Please waiting for 10 seconds!");
                Thread.sleep(10000);

                DescribeInstancesRequest newdescribeInstances = new DescribeInstancesRequest();
                DescribeInstancesResult newdescribeInstancesRequest = ec2
                        .describeInstances(newdescribeInstances);
                List<Reservation> newreservations = newdescribeInstancesRequest.getReservations();
                Set<Instance> allinstances = new HashSet<Instance>();
                for (Reservation reservation : newreservations) {
                    allinstances.addAll(reservation.getInstances());
                }

                for (Instance myinst : allinstances) {
                    String instanceId = myinst.getInstanceId();
                    if (instanceId.equals(createdInstanceId)) {
                        createdInstanceIp = myinst.getPublicIpAddress();
                    }
                }

            }
            System.out.println("Already get the Ip!");
            System.out.println("New instance's ip address is:" + createdInstanceIp);
            IP = createdInstanceIp;
        }

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

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

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

        /*********************************************
         *  Added By Chenyun Zhang
         *  # SSH connect into EC2
         *  
         *********************************************/

        Thread.sleep(100000);
        ssh con = new ssh();
        con.sshcon(IP);

        /*********************************************
         * 
         *  #8 Stop/Start an Instance
         *  
         *********************************************/
        System.out.println("#7 Stop the Instance");
        List<String> instanceIds = new LinkedList<String>();
        instanceIds.add(createdInstanceId);

        //stop
        StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
        //ec2.stopInstances(stopIR);

        //start
        StartInstancesRequest startIR = new StartInstancesRequest(instanceIds);
        //ec2.startInstances(startIR);

        /*********************************************
         * 
         *  #9 Terminate an Instance
         *  
         *********************************************/
        System.out.println("#8 Terminate the Instance");
        TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);
        //ec2.terminateInstances(tir);

        /*********************************************
         *  
         *  #10 shutdown client object
         *  
         *********************************************/
        ec2.shutdown();

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:EbsAttach.java

License:Open Source License

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

    init();/*w  w  w  .ja v  a  2 s .  c  o m*/

    try {
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");

        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();

        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        for (Instance ins : instances) {

            // instance id
            String instanceId = ins.getInstanceId();

            // instance state
            InstanceState is = ins.getState();
            System.out.println(instanceId + " " + is.getName());
        }

        System.out.println("Attached Instance id: " + attachedInsId);
        /*********************************************
         * 
         *  #1 Create New Volume
         *  
         *********************************************/
        System.out.println("===========================================");
        System.out.println("#1   Volume State before Creating");
        System.out.println("===========================================");

        DescribeVolumesResult describeVolumesResult = ec2.describeVolumes();
        List<Volume> volumes = describeVolumesResult.getVolumes();
        for (Volume volume : volumes) {
            String volumeId = volume.getVolumeId();
            String volumeAvbZone = volume.getAvailabilityZone();
            String volumeSize = String.valueOf(volume.getSize());
            String volumeState = volume.getState();
            System.out.println(volumeId + "\t" + volumeSize + "\t" + volumeAvbZone + "\t" + volumeState);
        }

        CreateVolumeRequest createVolumeRequest = new CreateVolumeRequest().withSize(4).withVolumeType("gp2")
                .withAvailabilityZone("us-east-1a");
        CreateVolumeResult createVolumeResult = ec2.createVolume(createVolumeRequest);
        String createdVolumeId = createVolumeResult.getVolume().getVolumeId();
        System.out.println("# Created a volume #  ID: " + createdVolumeId);
        /*********************************************
         * 
         *  #2 Attach the created new Volume
         *  
         *********************************************/
        System.out.println("===========================================");
        System.out.println("#2   Volume State after Creating");
        System.out.println("===========================================");

        describeVolumesResult = ec2.describeVolumes();
        volumes = describeVolumesResult.getVolumes();
        for (Volume volume : volumes) {
            String volumeId = volume.getVolumeId();
            String volumeAvbZone = volume.getAvailabilityZone();
            String volumeSize = String.valueOf(volume.getSize());
            String volumeState = volume.getState();
            System.out.println(volumeId + "\t" + volumeSize + "\t" + volumeAvbZone + "\t" + volumeState);
        }
        //wait new volume is available
        System.out.println("#   Waiting new Volume is available");
        boolean avail = false;
        while (true) {
            Thread.sleep(1000);
            describeVolumesResult = ec2.describeVolumes();
            volumes = describeVolumesResult.getVolumes();
            for (Volume volume : volumes) {
                if (volume.getVolumeId().equals(createdVolumeId) && volume.getState().equals("available")) {
                    avail = true;
                    break;
                }
            }
            if (avail)
                break;
        }
        System.out.println("New Volume is available now.");

        AttachVolumeRequest attachVolumeRequest = new AttachVolumeRequest().withVolumeId(createdVolumeId)
                .withInstanceId(attachedInsId).withDevice("/dev/sdn");
        AttachVolumeResult attachVolumeResult = ec2.attachVolume(attachVolumeRequest);
        VolumeAttachment volumeAttachment = attachVolumeResult.getAttachment();

        System.out.println(
                volumeAttachment.getVolumeId() + " is attached on " + volumeAttachment.getAttachTime());

        /*********************************************
         * 
         *  #3 SSh to instance and run command
         *  
         *********************************************/
        System.out.println("===========================================");
        System.out.println("#2   Ssh and mount disk");
        System.out.println("===========================================");

        Session session = null;
        Channel openChannel = null;
        String keyDir = KEYDIR;
        String user = "ec2-user";
        String host = publicDNSName;
        String command = "df -h;" + "sudo mkfs -t ext3 /dev/xvdn;" + "sudo mkdir /minihw3;"
                + "sudo mount /dev/xvdn /minihw3;" + "df -h";
        boolean isConnect = false;
        while (!isConnect) {
            JSch jsch = new JSch();
            System.out.println("Waiting 5 seconds for SSH being available.");
            Thread.sleep(5 * 1000);
            try {
                jsch.addIdentity(keyDir);
            } catch (JSchException e) {
                System.out.println(e.getMessage());
            }
            try {
                session = jsch.getSession(user, host, 22);
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.connect();
                System.out.println("SSH Connection Established.");
                isConnect = true;
                openChannel = session.openChannel("exec");

                ((ChannelExec) openChannel).setPty(true);

                ((ChannelExec) openChannel).setCommand(command);
                openChannel.setInputStream(null);
                ((ChannelExec) openChannel).setErrStream(System.err);

                int exitStatus = openChannel.getExitStatus();
                System.out.println("exit-status: " + exitStatus);
                InputStream in = openChannel.getInputStream();
                System.out.println("Exxcute remote cammand :" + command);
                openChannel.connect();

                byte[] tmp = new byte[1024];
                while (true) {
                    while (in.available() > 0) {
                        int i = in.read(tmp, 0, 1024);
                        if (i < 0)
                            break;
                        System.out.print(new String(tmp, 0, i));
                    }
                    if (openChannel.isClosed()) {
                        if (in.available() > 0)
                            continue;
                        System.out.println("exit-status: " + openChannel.getExitStatus());
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (Exception ee) {
                    }
                }
            } catch (JSchException | IOException e) {
                System.out.println(e.getMessage());
            } finally {
                if (openChannel != null && !openChannel.isClosed()) {
                    openChannel.disconnect();
                    System.out.println("Channel Disconnected");
                }
                if (session != null && session.isConnected()) {
                    session.disconnect();
                    System.out.println("Session Disconnected");
                }
            }

        }
    } 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

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

    System.out.println("===============================");
    System.out.println("AWS EC2 Instance Launch Progam");
    System.out.println("===============================");

    /*/*from  w ww . java2 s.  co m*/
    String pk = readFile("/Users/hps/.ssh/" + keyName + ".pem");
    try {
       Thread.sleep(5000);
       sshToInstance("52.1.49.155", "ec2-user", pk);
    } catch (Exception e) {
       System.out.println("Error: " + e);
    }
    */

    init();

    /*
     * Amazon EC2
     *
     * The AWS EC2 client allows you to create, delete, and administer
     * instances programmatically.
     *
     * In this sample, we use an EC2 client to get a list of all the
     * availability zones, and all instances sorted by reservation id.
     */
    try {
        //describeAvailabilityZones();
        describeCurrentInstances();
        //describeImages();
        //describeKeyPairs();

        createSecurityGroup(securityGroupName, securityGroupDescription);

        String privateKey = createKeyPair(keyName);
        String createdInstanceId = createInstance(imageId, instanceType, minInstanceCount, maxInstanceCount,
                keyName, securityGroupName);

        /* Wait for 10 seconds before trying to create a tag */
        Thread.sleep(10000);

        createTag(createdInstanceId, "Name", instanceNameTag);

        while (getInstanceState(createdInstanceId) != 16) {
            Thread.sleep(5000);
            System.out.println("Instance not running yet. Waiting.");
        }

        String createdInstanceIP = fetchInstancePublicIP(createdInstanceId);

        boolean connected = false;
        do {
            try {
                Thread.sleep(5000);
                sshToInstance(createdInstanceIP, loginUserName, privateKey);
                connected = true;
            } catch (Exception e) {
                //System.out.println("Error: " + e);
                System.out.println("Retrying");
            }
        } while (connected == false);

        changeInstanceState(createdInstanceId, instanceState.stop);

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

}