Example usage for com.amazonaws AmazonServiceException getErrorCode

List of usage examples for com.amazonaws AmazonServiceException getErrorCode

Introduction

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

Prototype

public String getErrorCode() 

Source Link

Document

Returns the AWS error code represented by this exception.

Usage

From source file:RandomQuery2OnDynamoDB.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();/*from w ww  .  j  a v  a  2s .  com*/

    try {

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);
        long lStartTime = new Date().getTime();
        System.out.println("start time: " + lStartTime);
        Random rn = new Random();
        Long lItem = tableDescription.getItemCount();
        int iNoOfItems = lItem.intValue();
        int iPointOnePercent = (int) ((int) iNoOfItems * 0.001);
        int iOnePercent = (int) ((int) iNoOfItems * 0.01);
        System.out.println("TotalItems:" + iNoOfItems + "::0.1% of data is :: " + iPointOnePercent
                + "::1% of data is :" + iOnePercent);

        // Generating 25000 random queries for 0.1 to 1 % of the data
        for (int i = 0; i <= 24999; i++) {
            String randomInt = Integer.toString(rn.nextInt(iOnePercent - iPointOnePercent) + iPointOnePercent);
            HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
            Condition condition = new Condition().withComparisonOperator(ComparisonOperator.EQ.toString())
                    .withAttributeValueList(new AttributeValue().withN(randomInt));
            scanFilter.put("id", condition);
            ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
            ScanResult scanResult = dynamoDB.scan(scanRequest);
            System.out.println("Random No :" + randomInt + ":: Query no: " + (i + 1));

        }
        // calculate time difference for update file time
        long lEndTime = new Date().getTime();
        long difference = lEndTime - lStartTime;
        System.out.println("Elapsed milliseconds: " + difference);
        System.out.println("Elapsed seconds: " + difference * 0.001);
        System.out.println("Elapsed Minutes: " + (int) ((difference / (1000 * 60)) % 60));

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

From source file:SQS.java

License:Open Source License

public String createQueue(String name) {
    String myQueueUrl = null;/* w  w  w  .  j a  va 2  s . c o  m*/
    try {
        System.out.println("Creating a new SQS queue called " + name);
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(name);
        myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

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

From source file:SQS.java

License:Open Source License

public void sendMessage(String myQueueUrl, String message) {
    try {/*from  w  w w  .jav  a2 s.co  m*/
        //System.out.println("Sending a message");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, message));
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:Assignment1.java

License:Open Source License

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

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

    /*********************************************
     *  #1 Create Amazon Client object//w  ww  .  j a  va 2  s.co m
     **********************************************/
    ec2 = new AmazonEC2Client(credentials);

    // We assume that we've already created an instance. Use the id of the instance.
    //String instanceId = "i-4e6c2a3d"; //put your own instance id to test this code.

    try {

        CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest();

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

        CreateSecurityGroupResult createSecurityGroupResult = ec2
                .createSecurityGroup(createSecurityGroupRequest);

        IpPermission ipPermission = new IpPermission();

        ipPermission.withIpRanges("0.0.0.0/0", "150.150.150.150/32").withIpProtocol("tcp").withFromPort(22)
                .withToPort(22);
        AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();

        authorizeSecurityGroupIngressRequest.withGroupName("mini").withIpPermissions(ipPermission);
        ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

        CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();

        createKeyPairRequest.withKeyName("E3instance_key");

        CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);

        KeyPair keyPair = new KeyPair();
        keyPair = createKeyPairResult.getKeyPair();

        String privateKey = keyPair.getKeyMaterial();

        System.out.print(privateKey);

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

        /*********************************************
         * 
         *  #1.2 Create an Instance
         *  
         *********************************************/

        RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

        runInstancesRequest.withImageId("ami-ab844dc2").withInstanceType("t1.micro").withMinCount(2)
                .withMaxCount(2).withKeyName("E3instance_key").withSecurityGroups("mini");
        RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);

        System.out.println("\n#1.2 Create an Instance");

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

        String createdInstanceId = null;

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

        String myinstanceZone = resultInstance.get(0).getPlacement().getAvailabilityZone();
        String myinstanceZone1 = resultInstance.get(1).getPlacement().getAvailabilityZone();
        String myinstanceID = resultInstance.get(0).getInstanceId();
        String myinstanceID1 = resultInstance.get(1).getInstanceId();

        Thread.sleep(1000 * 1 * 60);

        /*********************************************
         *  #2.1 Create a volume
         *********************************************/
        //create a volume
        CreateVolumeRequest cvr = new CreateVolumeRequest();
        CreateVolumeRequest cvr1 = new CreateVolumeRequest();
        cvr.setAvailabilityZone(myinstanceZone);
        cvr1.setAvailabilityZone(myinstanceZone1);
        cvr.setSize(10); //size = 10 gigabytes
        cvr1.setSize(10);
        CreateVolumeResult volumeResult = ec2.createVolume(cvr);
        CreateVolumeResult volumeResult1 = ec2.createVolume(cvr1);
        String createdVolumeId = volumeResult.getVolume().getVolumeId();
        String createdVolumeId1 = volumeResult1.getVolume().getVolumeId();
        String[] volumeID = new String[2];
        volumeID[0] = createdVolumeId;
        volumeID[1] = createdVolumeId1;
        System.out.println("\n#2.1 Create a volume for each instance");

        Thread.sleep(1000 * 1 * 60);
        /*********************************************
         *  #2.2 Attach the volume to the instance
         *********************************************/
        AttachVolumeRequest avr = new AttachVolumeRequest();
        AttachVolumeRequest avr1 = new AttachVolumeRequest();
        avr.setInstanceId(myinstanceID);
        avr1.setInstanceId(myinstanceID1);
        avr.setVolumeId(createdVolumeId);
        avr1.setVolumeId(createdVolumeId1);
        avr.setDevice("/dev/sda2");
        avr1.setDevice("/dev/sda2");
        //avr.setVolumeId(createdVolumeId);
        //avr.setInstanceId(createdInstanceId);
        //avr.setDevice("/dev/sdf");
        ec2.attachVolume(avr);
        ec2.attachVolume(avr1);
        System.out.println("\n#2.2 Attach the volume");
        System.out.println("EBS volume has been attached and the volume ID is: " + createdVolumeId);
        System.out.println("EBS volume has been attached and the volume ID is: " + createdVolumeId1);

        Thread.sleep(1000 * 2 * 60);
        /***********************************
        *   #2.3 Monitoring (CloudWatch)
        *********************************/

        //create CloudWatch client
        AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(credentials);

        //create request message
        GetMetricStatisticsRequest statRequest = new GetMetricStatisticsRequest();

        //set up request message
        statRequest.setNamespace("AWS/EC2"); //namespace
        statRequest.setPeriod(60); //period of data
        ArrayList<String> stats = new ArrayList<String>();

        //Use one of these strings: Average, Maximum, Minimum, SampleCount, Sum 
        stats.add("Average");
        stats.add("Sum");
        statRequest.setStatistics(stats);

        //Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations  
        statRequest.setMetricName("CPUUtilization");

        // set time
        GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // 1 second ago
        Date endTime = calendar.getTime();
        calendar.add(GregorianCalendar.MINUTE, -10); // 10 minutes ago
        Date startTime = calendar.getTime();
        statRequest.setStartTime(startTime);
        statRequest.setEndTime(endTime);

        //specify an instance
        ArrayList<Dimension> dimensions = new ArrayList<Dimension>();

        String monitorInstanceId = null;
        int i = 0;
        String[] idleInstance = new String[2];

        for (Instance ins : resultInstance) {
            monitorInstanceId = ins.getInstanceId();
            dimensions.add(new Dimension().withName("InstanceId").withValue(monitorInstanceId));
            statRequest.setDimensions(dimensions);

            Thread.sleep(1000 * 3 * 60);
            //get statistics
            GetMetricStatisticsResult statResult = cloudWatch.getMetricStatistics(statRequest);

            //display
            System.out.println(statResult.toString());
            List<Datapoint> dataList = statResult.getDatapoints();
            Double averageCPU = null;
            Date timeStamp = null;
            for (Datapoint data : dataList) {
                averageCPU = data.getAverage();
                timeStamp = data.getTimestamp();
                System.out.println("Average CPU utlilization for last 1 minutes: " + averageCPU);
                //System.out.println("Total CPU utlilization for last 1 minutes: "+data.getSum());

                //Calendar vmTime=GregorianCalendar.getInstance();
                //vmTime.setTime(timeStamp);
                //vmTime.get(Calendar.HOUR_OF_DAY);
                if (averageCPU < 50 && i < 2) {
                    idleInstance[i] = monitorInstanceId;
                    i++;
                }
            }

        }
        System.out.println("\n" + i + " instance(s) idling.");
        /*********************************************
         *  #2.4 Detach the volume from the instance 
         *********************************************/

        DetachVolumeRequest dvr = new DetachVolumeRequest();
        DetachVolumeRequest dvr1 = new DetachVolumeRequest();
        dvr.setVolumeId(createdVolumeId);
        dvr1.setVolumeId(createdVolumeId1);
        dvr.setInstanceId(myinstanceID);
        dvr1.setInstanceId(myinstanceID1);
        dvr.setDevice("/dev/sda2");
        dvr1.setDevice("/dev/sda2");
        ec2.detachVolume(dvr);
        ec2.detachVolume(dvr1);
        System.out.println("\n#2.4 Detach the volume");

        Thread.sleep(1000 * 1 * 60);

        /*********************************************
          *  #2.5 Create new AMI for idle instance
          *********************************************/
        String[] idleAMIID = new String[2];
        int j = 0;
        for (j = 0; j < idleInstance.length; j++) {
            CreateImageRequest Im = new CreateImageRequest(idleInstance[j], "image" + j);

            //CreateImageRequest Im1=new CreateImageRequest(myinstanceID1, "image1");
            Im.setInstanceId(idleInstance[j]);
            //Im1.setInstanceId(myinstanceID1);

            CreateImageResult myAMI = ec2.createImage(Im);
            idleAMIID[j] = myAMI.getImageId();

            //CreateImageResult myAMI1= ec2.createImage(Im1); 
            System.out.println("\n#2.5 Create new AMI");
        }
        Thread.sleep(1000 * 1 * 60);
        /*********************************************
          * 
          *  # Terminate an Instance
          *  
          *********************************************/
        //System.out.println("#8 Terminate the Instance");

        // TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);

        //ec2.terminateInstances(tir);
        /*********************************************
          *  #2.6 Create new VMs
          *********************************************/
        RunInstancesRequest runNewInstancesRequest = new RunInstancesRequest();
        int m;
        String[] newCreatedInstanceId = new String[2];
        for (m = 0; m < j; m++)//j is the number of AMI created
        {
            runNewInstancesRequest.withImageId(idleAMIID[m]).withInstanceType("t1.micro").withMinCount(1)
                    .withMaxCount(1).withKeyName("E3instance_key").withSecurityGroups("mini");
            RunInstancesResult runNewInstancesResult = ec2.runInstances(runNewInstancesRequest);
            List<Instance> newResultInstance = runNewInstancesResult.getReservation().getInstances();

            String newInstanceId = null;

            for (Instance ins : newResultInstance) {
                newInstanceId = ins.getInstanceId();
            }
            newCreatedInstanceId[m] = newInstanceId;
            System.out.println("Using AMI, a new instance has been created: " + newCreatedInstanceId[m]);

        }
        Thread.sleep(1000 * 1 * 60);
        //System.out.println("\n#2.6 Create "+ m + " instance using AMI");

        /*********************************************
          *  #2.7 Attach the volume to the new instance
          *********************************************/
        int n;
        for (n = 0; n < idleInstance.length; n++) {
            AttachVolumeRequest new_avr = new AttachVolumeRequest();
            //AttachVolumeRequest new_avr1 = new AttachVolumeRequest();
            new_avr.setInstanceId(newCreatedInstanceId[n]);
            //avr1.setInstanceId(myinstanceID1);
            new_avr.setVolumeId(volumeID[n]);
            //avr1.setVolumeId(createdVolumeId1);
            new_avr.setDevice("/dev/sda2");
            //avr1.setDevice("/dev/sda2");
            //avr.setVolumeId(createdVolumeId);
            //avr.setInstanceId(createdInstanceId);
            //avr.setDevice("/dev/sdf");
            ec2.attachVolume(new_avr);
            //ec2.attachVolume(avr1);
            System.out.println("\n#2.7 Re-attach the volume");
            System.out.println("EBS volume has been attached and the volume ID is: " + volumeID[n]);
            //System.out.println("EBS volume has been attached and the volume ID is: "+createdVolumeId1);

            Thread.sleep(1000 * 1 * 60);
        }
        /************************************************
        *    #3 S3 bucket and object
        ***************************************************/
        s3 = new AmazonS3Client(credentials);

        //create bucket
        String bucketName = "lucinda.duan";
        s3.createBucket(bucketName);

        //set key
        String key = "object-name.txt";

        //set value
        File file = File.createTempFile("temp", ".txt");
        file.deleteOnExit();
        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write("This is a sample sentence.\r\nYes!");
        writer.close();

        //put object - bucket, key, value(file)
        s3.putObject(new PutObjectRequest(bucketName, key, file));

        //get object
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent()));
        String data = null;
        while ((data = reader.readLine()) != null) {
            System.out.println(data);
        }

        /*********************************************
         *  #4 shutdown client object
         *********************************************/
        // ec2.shutdown();
        // s3.shutdown();

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

}

From source file:MonitorTableCreator.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();/*from   w ww. j  ava2s  . c  o m*/
    long readCapacity = 2L;
    long writeCapacity = 2L;
    try {
        String tableName = "monitor";

        //          DeleteTableRequest deleteTableRequest = new DeleteTableRequest(tableName);
        //          dynamoDB.deleteTable(deleteTableRequest);
        //          
        //          waitForTableToBecomeAvailable(tableName);

        // Create a table with a primary hash key named 'name', which holds a string
        CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(new KeySchemaElement().withAttributeName("id").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("id")
                        .withAttributeType(ScalarAttributeType.N))
                .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(readCapacity)
                        .withWriteCapacityUnits(writeCapacity));
        TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                .getTableDescription();
        System.out.println("Created Table: " + createdTableDescription);

        // Wait for it to become active
        waitForTableToBecomeAvailable(tableName);

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

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

From source file:receiveSQS.java

License:Open Source License

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

    /*/*from   www  .  java2  s  .  c o m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * ().
     */

    BasicAWSCredentials credentials = new BasicAWSCredentials("AKIAI2ZCFS3NVEENXW5A",
            "tI/GgpSWDF/QrNVhtCRu1G+PX/10A2nJQH+yTOiv");
    try {
        //          credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (/Users/daniel/.aws/credentials), and is in valid format.", e);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);

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

    try {

        // List queues
        System.out.println("Listing all queues in your account.\n");
        for (String queueUrl : sqs.listQueues().getQueueUrls()) {
            System.out.println("  QueueUrl: " + queueUrl);

            System.out.println();
            // Receive messages
            System.out.println("Receiving messages from MyQueue.\n");
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl);
            System.out.println("Message size:");

            //*****************************************************

            //For some reason, we only get one message at a time and it does not loop over.

            //*****************************************************

            //ReceiveMessageResponse receiveMessageResponse = amazonSQSClient.ReceiveMessage(receiveMessageRequest);
            List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
            for (Message message : messages) {
                System.out.println("  Message");
                //System.out.println("    MessageId:     " + message.getMessageId());
                //System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
                //System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
                //System.out.println("    Body:          " + message.getBody());
                String[] tweetdata = message.getBody().split("\\|\\|");
                System.out.println(Arrays.toString(tweetdata));
                System.out.println("Deleting a message.\n");
                String messageRecieptHandle = messages.get(0).getReceiptHandle();
                sqs.deleteMessage(new DeleteMessageRequest(queueUrl, messageRecieptHandle));

            }
        }

        System.out.println();
        /*
                    // Delete a message
                
                    // Delete a queue
                    System.out.println("Deleting the test queue.\n");
                    sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));   
          */
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

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 ww w .  j av  a2s . co m
     * 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.InlineGettingStartedCodeSampleApp.java

License:Open Source License

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

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

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

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

    //*************************** Required Parameters Settings ************************// 
    // Request 1 x t1.micro instance with a bid price of $0.03. 
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest 
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-8c1fece5");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("GettingStartedGroup");
    launchSpecification.setSecurityGroups(securityGroups);

    //*************************** Bid Type Settings ************************// 
    // Set the type of the bid to persistent.
    requestRequest.setType("persistent");

    //*************************** Valid From/To Settings ************************// 
    // Set the valid start time to be two minutes from now.
    Calendar from = Calendar.getInstance();
    from.add(Calendar.MINUTE, 2);
    requestRequest.setValidFrom(from.getTime());

    // Set the valid end time to be two minutes and two hours from now.
    Calendar until = (Calendar) from.clone();
    until.add(Calendar.HOUR, 2);
    requestRequest.setValidUntil(until.getTime());

    //*************************** Launch Group Settings ************************// 
    // Set the launch group.
    requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP");

    //*************************** Availability Zone Group Settings ************************// 
    // Set the availability zone group.
    requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP");

    //*************************** Add the block device mapping ************************// 

    // Goal: Setup block device mappings to ensure that we will not delete
    // the root partition on termination.

    // Create the block device mapping to describe the root partition.
    BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
    blockDeviceMapping.setDeviceName("/dev/sda1");

    // Set the delete on termination flag to false.
    EbsBlockDevice ebs = new EbsBlockDevice();
    ebs.setDeleteOnTermination(Boolean.FALSE);
    blockDeviceMapping.setEbs(ebs);

    // Add the block device mapping to the block list.
    ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>();
    blockList.add(blockDeviceMapping);

    // Set the block device mapping configuration in the launch specifications.
    launchSpecification.setBlockDeviceMappings(blockList);

    //*************************** Add the availability zone ************************// 
    // Setup the availability zone to use. Note we could retrieve the availability 
    // zones using the ec2.describeAvailabilityZones() API. For this demo we will just use
    // us-east-1b.
    SpotPlacement placement = new SpotPlacement("us-east-1b");
    launchSpecification.setPlacement(placement);

    //*************************** Add the placement group ************************// 
    // Setup the placement group to use with whatever name you desire.
    // For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP".
    // Note: We have commented this out, because we are not leveraging cc1.4xlarge or
    // cg1.4xlarge in this example.
    /*
    SpotPlacement pg = new SpotPlacement();
    pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP");
    launchSpecification.setPlacement(pg);
    */

    //*************************** Add the launch specification ************************// 
    // Add the launch specification.
    requestRequest.setLaunchSpecification(launchSpecification);

    //============================================================================================//
    //=========================== Getting the Request ID from the Request ========================// 
    //============================================================================================//

    // Call the RequestSpotInstance API. 
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the 
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    //============================================================================================//
    //=========================== Determining the State of the Spot Request ======================// 
    //============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false  which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor. 
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    //============================================================================================//
    //====================================== Canceling the Request ==============================// 
    //============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=================================== Terminating any Instances ==============================// 
    //============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:advanced.InlineTaggingCodeSampleApp.java

License:Open Source License

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

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

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

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

    // Request 1 x t1.micro instance with a bid price of $0.03. 
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest 
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-8c1fece5");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("GettingStartedGroup");
    launchSpecification.setSecurityGroups(securityGroups);

    // Add the launch specifications to the request.
    requestRequest.setLaunchSpecification(launchSpecification);

    //============================================================================================//
    //=========================== Getting the Request ID from the Request ========================// 
    //============================================================================================//

    // Call the RequestSpotInstance API. 
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the 
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    //============================================================================================//
    //====================================== Tag the Spot Requests ===============================// 
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> requestTags = new ArrayList<Tag>();
    requestTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for requests.
    CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest();
    createTagsRequest_requests.setResources(spotInstanceRequestIds);
    createTagsRequest_requests.setTags(requestTags);

    // Try to tag the Spot request submitted.
    try {
        ec2.createTags(createTagsRequest_requests);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=========================== Determining the State of the Spot Request ======================// 
    //============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false  which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor. 
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    //============================================================================================//
    //====================================== Tag the Spot Instances ===============================// 
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> instanceTags = new ArrayList<Tag>();
    instanceTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for instances.
    CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest();
    createTagsRequest_instances.setResources(instanceIds);
    createTagsRequest_instances.setTags(instanceTags);

    // Try to tag the Spot instance started.
    try {
        ec2.createTags(createTagsRequest_instances);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //====================================== Canceling the Request ==============================// 
    //============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=================================== Terminating any Instances ==============================// 
    //============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:advanced.Requests.java

License:Open Source License

/**
 * The areOpen method will determine if any of the requests that were started are still
 * in the open state. If all of them have transitioned to either active, cancelled, or
 * closed, then this will return false. 
 * @return//from ww w. j av a 2 s  .c  o  m
 */
public boolean areAnyOpen() {
    //==========================================================================//
    //============== Describe Spot Instance Requests to determine =============//
    //==========================================================================//

    // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
    DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
    describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

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

    // Initialize variables.
    instanceIds = new ArrayList<String>();

    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) {
            System.out.println(" " + describeResponse.getSpotInstanceRequestId() + " is in the "
                    + describeResponse.getState() + " state.");

            // 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")) {
                return true;
            }

            // Add the instance id to the list we will eventually terminate.
            instanceIds.add(describeResponse.getInstanceId());
        }
    } catch (AmazonServiceException e) {
        // Print out the error.
        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());

        // 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.
        return true;
    }

    return false;
}