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:S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//  w w  w.  j av a2  s  .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(S3Sample.class.getResourceAsStream("AwsCredentials.properties")));

    String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    String key = "MyObjectKey";

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

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique,
         * so once a bucket name has been taken by any user, you can't create
         * another bucket with that same name.
         *
         * You can optionally specify a location for your bucket if you want to
         * keep your data closer to your applications or users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

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

        /*
         * Upload an object to your bucket - You can easily upload a file to
         * S3, or upload directly an InputStream if you know the length of
         * the data in the stream. You can also specify your own metadata
         * when uploading to S3, which allows you set a variety of options
         * like content-type and content-encoding, plus additional metadata
         * specific to your applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Download an object - When you download an object, you get all of
         * the object's metadata and a stream from which to read the contents.
         * It's important to read the contents of the stream as quickly as
         * possibly since the data is streamed directly from Amazon S3 and your
         * network connection will remain open until you read all the data or
         * close the input stream.
         *
         * GetObjectRequest also supports several other options, including
         * conditional downloading of objects based on modification times,
         * ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for
         * listing the objects in your bucket.  Keep in mind that buckets with
         * many objects might truncate their results when listing their objects,
         * so be sure to check if the returned object listing is truncated, and
         * use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
         * additional results.
         */
        System.out.println("Listing objects");
        ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket,
         * there is no way to undelete an object, so use caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be
         * deleted, so remember to delete any objects from your buckets before
         * you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, 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 S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:HW1.java

License:Open Source License

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

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

    /*********************************************
     * /*from   ww  w .  j  ava  2 s .c  om*/
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);
    ec2.setEndpoint("https://us-east-1.ec2.amazonaws.com");

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

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

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

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

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

    try {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        /***********************************
        *   #3 Monitoring (CloudWatch)
        *********************************/
        System.out.println();
        System.out.println("#6 set up cloudwatch");
        try {
            /* create CloudWatch client */
            AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(credentials);
            /* create request message1 */
            GetMetricStatisticsRequest statRequest1 = new GetMetricStatisticsRequest();
            GetMetricStatisticsRequest statRequest2 = new GetMetricStatisticsRequest();
            /* set up request message */
            statRequest1.setNamespace("AWS/EC2"); //namespace
            statRequest2.setNamespace("AWS/EC2"); //namespace
            statRequest1.setPeriod(60); //period of data
            statRequest2.setPeriod(60); //period of data
            ArrayList<String> stats = new ArrayList<String>();
            /* Use one of these strings: Average, Maximum, Minimum, SampleCount, Sum */
            stats.add("Average");
            stats.add("Sum");
            statRequest1.setStatistics(stats);
            statRequest2.setStatistics(stats);
            /* Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations  */
            statRequest1.setMetricName("CPUUtilization");
            statRequest2.setMetricName("CPUUtilization");
            /* set time */
            GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // 1 second ago
            Date endTime = calendar.getTime();
            calendar.add(GregorianCalendar.MINUTE, -10); // 10 minutes ago
            Date startTime = calendar.getTime();
            statRequest1.setStartTime(startTime);
            statRequest1.setEndTime(endTime);
            statRequest2.setStartTime(startTime);
            statRequest2.setEndTime(endTime);
            /* specify an instance */
            ArrayList<Dimension> dimensions1 = new ArrayList<Dimension>();
            dimensions1.add(new Dimension().withName("InstanceId").withValue(insId1));
            ArrayList<Dimension> dimensions2 = new ArrayList<Dimension>();
            dimensions2.add(new Dimension().withName("InstanceId").withValue(insId2));
            statRequest1.setDimensions(dimensions1);
            statRequest2.setDimensions(dimensions2);
            System.out.println("Set up cloud watch for instance: " + insId1 + " and instance: " + insId2);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        /* get the object from the first day */
        System.out.println();
        System.out.println("#9 Reading data from S3 stored on the first day");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent()));
        String data = null;
        while ((data = reader.readLine()) != null) {
            System.out.println(data);
        }

        /*********************************************
         *  
         *  #10 shutdown client object
         *  
         *********************************************/
        System.out.println("#10 shutdown client objects");
        ec2.shutdown();
        s3.shutdown();

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

}

From source file:AmazonDynamoDBSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();/* w w w .  ja  v  a 2 s  .c om*/

    try {
        String tableName = "storyTable";

        // Create table if it does not exist yet
        if (Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is already ACTIVE");
        } else {
            // Create a table with a primary hash key named 'name', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(
                            new KeySchemaElement().withAttributeName("storyID").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("storyID")
                            .withAttributeType(ScalarAttributeType.N))
                    .withProvisionedThroughput(
                            new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
            TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                    .getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.awaitTableToBecomeActive(dynamoDB, tableName);
        }

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);
        Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
        System.out.println(currentTimestamp);
        ByteBuffer b = createBody();
        int id1 = 1;
        int id2 = 2;
        double d1 = 0;
        double d2 = 1;
        Timestamp inputTimestamp = currentTimestamp;
        // Add an item
        Map<String, AttributeValue> item = newItem(id1, "JAM", "This is JAM", b, inputTimestamp, inputTimestamp,
                d1, d2);
        System.out.println("here");

        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        System.out.println("here2");
        System.out.println(item);
        System.out.println(putItemRequest);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("here3");
        System.out.println("Result: " + putItemResult);

        // Add another item
        item = newItem(id2, "JAM2", "This is JAM2", b, inputTimestamp, inputTimestamp, d1, d2);
        putItemRequest = new PutItemRequest(tableName, item);
        putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Scan items for movies with a year attribute greater than 1985
        //            HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        //            Condition condition = new Condition()
        //                .withComparisonOperator(ComparisonOperator.GT)
        //                .withAttributeValueList(new AttributeValue());
        //            scanFilter.put("year", condition);
        //            ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
        //            ScanResult scanResult = dynamoDB.scan(scanRequest);
        //            System.out.println("Result: " + scanResult);

    } 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:TweetSQS.java

License:Open Source License

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

    /*/* ww  w  .  ja va2s. c  o  m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * ().
     */
    AWSCredentials credentials = null;
    try {
        credentials = new PropertiesCredentials(
                TweetSQS.class.getResourceAsStream("AwsCredentials.properties"));
    } 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/aohong/.aws/credentials), and is in valid format.", e);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usEast1);

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

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called MyQueue.\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
        String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

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

        // Send a message
        System.out.println("Sending a message to MyQueue.\n");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my first message text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        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());
            for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }
        System.out.println();

        // Delete a message
        System.out.println("Deleting a message.\n");
        String messageRecieptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

        // 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:virtualIT.java

License:Open Source License

public static void main(String[] args) throws Exception {
    AWSCredentials credentials = new PropertiesCredentials(
            virtualIT.class.getResourceAsStream("AwsCredentials.properties"));
    int intialCounter = 0;
    int s;//ww  w. j  a  v a  2s .c  o  m
    virtualIT vIT = new virtualIT();
    /*********************************************
     * 
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);
    db = new AmazonDynamoDBClient(credentials);
    cloudWatch = new AmazonCloudWatchClient(credentials);
    autoScaleClient = new AmazonAutoScalingClient(credentials);
    vIT.deleteAutoScalingGroup(12345);
    try {
        System.out.println("Starting Virtual System Admin \n");
        System.out.println("Enter no of users want to login\n");
        Scanner getInput = new Scanner(System.in);
        s = getInput.nextInt();
        if (s != 0) {
            for (int j = 0; j < s; j++) {
                System.out.println("Enter UserId:\n");
                int getUserId = getInput.nextInt();
                if (getUserId != 0) {
                    vIT.userIds.add(getUserId);
                    vIT.StartUpGroup(getUserId);
                    vIT.cloudWatchMonitor(getUserId);
                }
            }

            Calendar cal = Calendar.getInstance();
            Date time = cal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

            vIT.currentHour = (sdf.format(Calendar.HOUR));
            System.out.println(sdf.format(Calendar.HOUR));
            /****
             * Entering Continuous Loop
             */
            for (int i = 0; i < vIT.userIds.size(); i++) {

                int userId = vIT.userIds.get(i);
                double cpu = vIT.mapUserCpu.get(userId);
                tempMin = cal.getTime();

                while (vIT.currentHour.equals(stopTime) || cpu < 5)
                    ;
                {

                    vIT.cloudWatchMonitor(userId);

                    /****************
                     * Entering Time end Group Keeps on looping 
                     */
                    vIT.TimeEndGroup();
                }
            }

        }
        /*********************************************
         * 
          *  #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());
        //    System.out.println("Key for the instance  "+keyName);
         }*/

        // Thread.currentThread().sleep(100000);

        //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 = ec2.describeInstances();
          reservations = describeInstancesRequest.getReservations();
          int k = reservations.size();
          Reservation totalReservations = reservations.get(k-1);
          Instance getFirstInstance = totalReservations.getInstances().get(0);
                 
          System.out.println("The private IP is: "+getFirstInstance.getPrivateIpAddress());
          System.out.println("The public IP is: "+getFirstInstance.getPublicIpAddress());*/

    } 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:RandomQuery1OnDynamoDB.java

License:Open Source License

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

    try {

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

        System.out.println("Table count :" + tableDescription.getItemCount());

        long lStartTime = new Date().getTime();
        System.out.println("start time: " + lStartTime);
        Random rn = new Random();
        // Scan items for movies with a year attribute greater than 1985
        Long lItem = tableDescription.getItemCount();
        int iNoOfItems = lItem.intValue();
        System.out.println("no of item " + lItem);
        for (int i = 0; i <= 49999; i++) {
            String randomInt = Integer.toString(rn.nextInt(iNoOfItems));
            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:InlineGettingStartedCodeApp.java

License:Open Source License

/**
 * @param args/*from www . j  av  a  2 s  .  c  o m*/
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

From source file:AmazonDynamoDBSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//from w w  w  .ja v  a  2  s . c o m

    try {
        String tableName = "my-favorite-movies-table";

        // Create a table with a primary key named 'name', which holds a string
        CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(
                        new KeySchema(new KeySchemaElement().withAttributeName("name").withAttributeType("S")))
                .withProvisionedThroughput(
                        new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(10L));
        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);

        // Add an item
        Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James",
                "Sara");
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Add another item
        item = newItem("Airplane", 1980, "*****", "James", "Billy Bob");
        putItemRequest = new PutItemRequest(tableName, item);
        putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Scan items for movies with a year attribute greater than 1985
        HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
                .withAttributeValueList(new AttributeValue().withN("1985"));
        scanFilter.put("year", condition);
        ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
        ScanResult scanResult = dynamoDB.scan(scanRequest);
        System.out.println("Result: " + scanResult);

    } 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:InlineTaggingCodeApp.java

License:Open Source License

/**
 * @param args//from  w  ww .j  a  va 2 s  .c o m
 */
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;/*w w  w.j  a va2  s .  c  om*/
    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());
    }
}