Example usage for com.amazonaws AmazonServiceException getMessage

List of usage examples for com.amazonaws AmazonServiceException getMessage

Introduction

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

Prototype

@Override
    public String getMessage() 

Source Link

Usage

From source file:SimpleDBPerformanceSample.java

License:Apache License

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

    AmazonSimpleDB sdb = new AmazonSimpleDBClient(
            new PropertiesCredentials(SimpleDBSample.class.getResourceAsStream("AwsCredentials.properties")));
    // ?[WGh|Cgw//from  w ww .j a  v a  2s. c o  m
    sdb.setEndpoint(args[0]);

    int roopCount = 100;
    long insertTimeSum = 0;
    long selectTimeSum = 0;
    long updateTimeSum = 0;
    long deleteTimeSum = 0;
    long startTime;
    long finishedTime;

    try {
        // h?C??
        String myDomain = "MyStore";
        sdb.createDomain(new CreateDomainRequest(myDomain));

        for (int i = 0; i < roopCount; i++) {
            // ?f?[^
            sdb.batchPutAttributes(new BatchPutAttributesRequest(myDomain, createSampleData()));

            // f?[^1?}(PutAttributes API)
            ReplaceableItem rItem = new ReplaceableItem("Item_06").withAttributes(
                    new ReplaceableAttribute("Category", "Car Parts", true),
                    new ReplaceableAttribute("Subcategory", "Exhaust", true),
                    new ReplaceableAttribute("Name", "O2 Sensor", true),
                    new ReplaceableAttribute("Make", "Audi", true),
                    new ReplaceableAttribute("Model", "TT Coupe", true),
                    new ReplaceableAttribute("Year", "2009", true),
                    new ReplaceableAttribute("Year", "2010", true),
                    new ReplaceableAttribute("Year", "2011", true));
            PutAttributesRequest putAttributesRequest = new PutAttributesRequest(myDomain, rItem.getName(),
                    rItem.getAttributes());
            startTime = System.currentTimeMillis();
            sdb.putAttributes(putAttributesRequest);
            finishedTime = System.currentTimeMillis();
            insertTimeSum += finishedTime - startTime;

            // f?[^?iSelect API)
            String selectExpression = "select * from `" + myDomain + "` where Category = 'Clothes'";
            SelectRequest selectRequest = new SelectRequest(selectExpression);
            startTime = System.currentTimeMillis();
            sdb.select(selectRequest);
            finishedTime = System.currentTimeMillis();
            selectTimeSum += finishedTime - startTime;

            // f?[^?X?V(PutAttributes API)
            List<ReplaceableAttribute> replaceableAttributes = new ArrayList<ReplaceableAttribute>();
            replaceableAttributes.add(new ReplaceableAttribute("Size", "Medium", true));
            startTime = System.currentTimeMillis();
            sdb.putAttributes(new PutAttributesRequest(myDomain, "Item_03", replaceableAttributes));
            finishedTime = System.currentTimeMillis();
            updateTimeSum += finishedTime - startTime;

            // f?[^??(DeleteAttributes API)
            startTime = System.currentTimeMillis();
            sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03"));
            finishedTime = System.currentTimeMillis();
            deleteTimeSum += finishedTime - startTime;

            // f?[^??
            sdb.batchDeleteAttributes(new BatchDeleteAttributesRequest(myDomain, deleteSampleData()));
        }
        // h?C??
        sdb.deleteDomain(new DeleteDomainRequest(myDomain));

        System.out.println("insert:AVG:" + (float) insertTimeSum / roopCount);
        System.out.println("select:AVG:" + (float) selectTimeSum / roopCount);
        System.out.println("update:AVG:" + (float) updateTimeSum / roopCount);
        System.out.println("delete:AVG:" + (float) deleteTimeSum / roopCount);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SimpleDB, 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 SimpleDB, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:AwsSQSDemo.java

License:Open Source License

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

    /*//from   w ww.  java 2 s .  co m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().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 (~/.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 {
        // 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 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:kinesisAlertAnalysis.java

License:Open Source License

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

    init();/*  w  ww. j  a  va  2s . c o m*/

    final String myStreamName = "alertsStream";
    final Integer myStreamSize = 1;

    /*
     * The ProfileCredentialsProvider will return your [awsReilly]
     * credential profile by reading from the credentials file located at
     * (/Users/johnreilly/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("jreilly").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/johnreilly/.aws/credentials), and is in valid format.", e);
    }

    // Describe the stream and check if it exists.
    DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest().withStreamName(myStreamName);
    try {
        StreamDescription streamDescription = kinesis.describeStream(describeStreamRequest)
                .getStreamDescription();
        System.out.printf("Stream %s has a status of %s.\n", myStreamName, streamDescription.getStreamStatus());

        if ("DELETING".equals(streamDescription.getStreamStatus())) {
            System.out.println("Stream is being deleted. This sample will now exit.");
            System.exit(0);
        }

        // Wait for the stream to become active if it is not yet ACTIVE.
        if (!"ACTIVE".equals(streamDescription.getStreamStatus())) {
            waitForStreamToBecomeAvailable(myStreamName);
        }
    } catch (ResourceNotFoundException ex) {
        System.out.printf("Stream %s does not exist. Creating it now.\n", myStreamName);

        // Create a stream. The number of shards determines the provisioned throughput.
        CreateStreamRequest createStreamRequest = new CreateStreamRequest();
        createStreamRequest.setStreamName(myStreamName);
        createStreamRequest.setShardCount(myStreamSize);
        kinesis.createStream(createStreamRequest);
        // The stream is now being created. Wait for it to become active.
        waitForStreamToBecomeAvailable(myStreamName);
    }

    // List all of my streams.
    ListStreamsRequest listStreamsRequest = new ListStreamsRequest();
    listStreamsRequest.setLimit(10);
    ListStreamsResult listStreamsResult = kinesis.listStreams(listStreamsRequest);
    List<String> streamNames = listStreamsResult.getStreamNames();
    while (listStreamsResult.isHasMoreStreams()) {
        if (streamNames.size() > 0) {
            listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1));
        }

        listStreamsResult = kinesis.listStreams(listStreamsRequest);
        streamNames.addAll(listStreamsResult.getStreamNames());
    }
    // Print all of my streams.
    System.out.println("List of my streams: ");
    for (int i = 0; i < streamNames.size(); i++) {
        System.out.println("\t- " + streamNames.get(i));
    }

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

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

    try {

        String thisQueue = "alertCache";
        String nextQueue = "alertReceive";

        // Receive messages
        System.out.println("Receiving messages from " + thisQueue + ".");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(thisQueue);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        System.out.println("Message count for " + thisQueue + ": " + messages.size() + "\n");

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

            // Write record to the stream
            long createTime = System.currentTimeMillis();
            PutRecordRequest putRecordRequest = new PutRecordRequest();
            putRecordRequest.setStreamName(myStreamName);
            putRecordRequest.setData(ByteBuffer.wrap(String.format(message.getBody(), createTime).getBytes()));
            putRecordRequest.setPartitionKey(String.format("partitionKey-%d", createTime));
            PutRecordResult putRecordResult = kinesis.putRecord(putRecordRequest);
            System.out.printf(
                    "Successfully put record, partition key : %s, ShardID : %s, SequenceNumber : %s.\n",
                    putRecordRequest.getPartitionKey(), putRecordResult.getShardId(),
                    putRecordResult.getSequenceNumber());

            // then send message to cache queue
            System.out.println("Sending messages to next queue.");
            sqs.sendMessage(new SendMessageRequest(nextQueue, message.getBody()));

            // delete message after sending to persist queue
            System.out.println("Deleting message from this queue.\n");
            String messageRecieptHandle = message.getReceiptHandle();
            sqs.deleteMessage(new DeleteMessageRequest(thisQueue, messageRecieptHandle));
        }

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

License:Open Source License

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

    /*/*from  w ww .  j  ava2s.  co  m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (/Users/zunzunwang/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (/Users/zunzunwang/.aws/credentials), and is in valid format.", e);
    }

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

    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 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 messageReceiptHandle = messages.get(10).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));

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

License:Open Source License

private static void scan(String tableName) {
    Table table = null;/* w  w w. ja  v  a2 s  . c om*/
    try {
        // Create table if it does not exist yet
        if (!Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is does not exist");
        } else {
            table = dynamo.getTable(tableName);
        }
        // select * from stock_eod where stockTicker = 'HCA' and v > 1000000;
        // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html
        Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
        expressionAttributeValues.put(":val", new AttributeValue().withN("1000000"));

        //Below is not recommended as stockTicker is part of the key
        expressionAttributeValues.put(":st", new AttributeValue().withS("HCA"));

        ScanRequest scanRequest = new ScanRequest().withTableName(tableName)
                .withFilterExpression("v > :val and stockTicker = :st")
                // select stockTicker, tradeDate, v from stock_eod where stockTicker = 'HCA' and v > 1000000;
                .withProjectionExpression("stockTicker,tradeDate,v")
                .withExpressionAttributeValues(expressionAttributeValues);

        ScanResult result = dynamoDB.scan(scanRequest);

        for (Map<String, AttributeValue> item : result.getItems()) {
            System.out.println(item);
        }

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

License:Open Source License

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

    AmazonS3 s3 = new AmazonS3Client(
            new PropertiesCredentials(BackupManager.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 {//from   ww  w .j a v  a  2  s.c o  m
        /*
         * 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:EC2LaunchWaitTerminate.java

License:Open Source License

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

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

    init();// ww  w. j  av  a 2s . c  o  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 get a list of all the
     * availability zones, and all instances sorted by reservation id, then 
     * create an instance, list existing instances again, wait a minute and 
     * the terminate the started instance.
     */
    try {
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");
        /* using AWS Ireland. 
         * TODO: Pick the zone where you have your AMI, sec group and keys */
        ec2.setEndpoint("ec2.us-west-2.amazonaws.com");
        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();

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

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        System.out.println("Starting a new instance.");
        RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

        /* TODO: configure to use your AMI, key and security group */
        runInstancesRequest.withImageId("ami-ede6128d").withInstanceType("t2.micro").withMinCount(1)
                .withMaxCount(1).withKeyName("CNV-lab-AWS").withSecurityGroups("CNV-ssh+http");
        RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);
        String newInstanceId = runInstancesResult.getReservation().getInstances().get(0).getInstanceId();
        describeInstancesRequest = ec2.describeInstances();
        reservations = describeInstancesRequest.getReservations();
        instances = new HashSet<Instance>();

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

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        System.out.println("Waiting 4 minutes. See your instance in the AWS console...");
        Thread.sleep(60000 * 4);
        System.out.println("Terminating the instance.");
        TerminateInstancesRequest termInstanceReq = new TerminateInstancesRequest();
        termInstanceReq.withInstanceIds(newInstanceId);
        ec2.terminateInstances(termInstanceReq);

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

License:Open Source License

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

    // initialize/determine parameters
    String instanceType = "m3.medium";
    String loadGeneratorAmi = "ami-8ac4e9e0";
    String dataCenterAmi = "ami-349fbb5e";
    String bidPrice = "0.1";
    String loadGeneratorDns = null; // load generator DNS
    String dashboardUrl = null; // the URL where we check our performance
    String testId = null;/*from w  w w .jav  a  2 s.c  o m*/

    // create project tag for instances
    ArrayList<com.amazonaws.services.ec2.model.Tag> loadGeneratorTags = new ArrayList<>();
    com.amazonaws.services.ec2.model.Tag loadGeneratorTag = new com.amazonaws.services.ec2.model.Tag("Project",
            "2.1");
    loadGeneratorTags.add(loadGeneratorTag);

    // create project tag for auto-scaling
    com.amazonaws.services.autoscaling.model.Tag asgTag = new com.amazonaws.services.autoscaling.model.Tag();
    asgTag.setKey("Project");
    asgTag.setValue("2.1");

    // create project tag for load balancer
    ArrayList<com.amazonaws.services.elasticloadbalancing.model.Tag> loadBalancerTags = new ArrayList<>();
    com.amazonaws.services.elasticloadbalancing.model.Tag loadBalancerTag = new com.amazonaws.services.elasticloadbalancing.model.Tag();
    loadBalancerTag.setKey("Project");
    loadBalancerTag.setValue("2.1");
    loadBalancerTags.add(loadBalancerTag);

    /**
     * =========================================================================
     * ================= Create security groups
     * =========================================================================
     * =================
     */

    String loadGeneratorSecurityName = "LoadGeneratorSGP2";
    String allPurposeSecurityName = "AllPurposeSGP2";
    SecurityGroup loadGeneratorSecurityGroup = new SecurityGroup(loadGeneratorSecurityName);
    SecurityGroup allPurposeSecurityGroup = new SecurityGroup(allPurposeSecurityName);

    /**
     * =========================================================================
     * ================= Grant permission and credentials
     * =========================================================================
     * =================
     */

    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("School").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 (C:\\Users\\Jiabei\\.aws\\credentials), and is in valid format.", e);
    }

    // set region
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    ec2.setRegion(usEast1);

    /**
     * =========================================================================
     * ================= Create a load generator and submit password
     * =========================================================================
     * =================
     */

    Requests requestsLg = new Requests(instanceType, loadGeneratorAmi, bidPrice, loadGeneratorSecurityName,
            loadGeneratorTags);
    loadGeneratorDns = requestsLg.submitRequests();
    String submissionUrl = "http://" + loadGeneratorDns
            + "/password?passwd=0WSb4ufhYI7SkxfLWnnIWU0MC1NdcNKT&andrewId=jiabeip";
    sendGET(submissionUrl);

    try {

        /**
         * =======================================================================
         * =================== Create a load balancer
         * =======================================================================
         * ===================
         */

        String loadBalancerDns = null;
        String loadBalancerName = "LoadBalancerProj2";
        String healthCheckPage = "/heartbeat?lg=" + loadGeneratorDns;
        AmazonElasticLoadBalancingClient loadBalancerClient = new AmazonElasticLoadBalancingClient(credentials);

        // configure a request
        CreateLoadBalancerRequest loadBalancerRequest = new CreateLoadBalancerRequest()
                .withAvailabilityZones("us-east-1b").withListeners(new Listener("HTTP", 80, 80))
                .withLoadBalancerName(loadBalancerName).withSecurityGroups(allPurposeSecurityGroup.getGroupId())
                .withTags(loadBalancerTags);

        CreateLoadBalancerResult loadBalancerResult = loadBalancerClient
                .createLoadBalancer(loadBalancerRequest);
        loadBalancerDns = loadBalancerResult.getDNSName();

        // configure health check setting
        HealthCheck loadBalancerHealthCheck = new HealthCheck().withTarget("HTTP:80" + healthCheckPage)
                .withTimeout(5).withInterval(30).withUnhealthyThreshold(2).withHealthyThreshold(10);

        ConfigureHealthCheckRequest healthCheckRequest = new ConfigureHealthCheckRequest()
                .withLoadBalancerName(loadBalancerName).withHealthCheck(loadBalancerHealthCheck);

        // attach health check setting to load balancer
        ConfigureHealthCheckResult healthCheckResult = loadBalancerClient
                .configureHealthCheck(healthCheckRequest);

        System.out.println("Load balancer created!\nDNS: " + loadBalancerDns);

        /**
         * =======================================================================
         * =================== Create launch configuration
         * =======================================================================
         * ===================
         */

        String launchConfigName = "LaunchConfigProj2";
        String autoScalingGroupName = "AutoScalingGroupProj2";

        AmazonAutoScalingClient autoScalingGroupClient = new AmazonAutoScalingClient(credentials);
        AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(credentials);

        System.out.println("Creating launch configuration...");

        // configure the request
        CreateLaunchConfigurationRequest launchConfigRequest = new CreateLaunchConfigurationRequest()
                .withImageId(dataCenterAmi).withInstanceType(instanceType)
                .withLaunchConfigurationName(launchConfigName)
                .withSecurityGroups(allPurposeSecurityGroup.getGroupId()).withSpotPrice(bidPrice)
                .withKeyName("primary");

        // enable detail monitoring
        InstanceMonitoring monitor = new InstanceMonitoring();
        monitor.setEnabled(true);
        launchConfigRequest.setInstanceMonitoring(monitor);

        // attach the configuration to the ASG client
        autoScalingGroupClient.createLaunchConfiguration(launchConfigRequest);

        System.out.println("Configuration complete!\nCreating auto-scaling group...");

        /**
         * =======================================================================
         * =================== Create auto-scaling group
         * =======================================================================
         * ===================
         */

        // configure ASG request
        CreateAutoScalingGroupRequest asgRequest = new CreateAutoScalingGroupRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withAvailabilityZones("us-east-1b")
                .withLoadBalancerNames(loadBalancerName).withNewInstancesProtectedFromScaleIn(false)
                .withTags(asgTag).withDefaultCooldown(120).withMinSize(1).withMaxSize(8).withDesiredCapacity(1) // Start
                // from
                // one
                .withHealthCheckGracePeriod(120).withHealthCheckType("ELB")
                .withLaunchConfigurationName(launchConfigName);

        // attach group configuration to ASG client
        autoScalingGroupClient.createAutoScalingGroup(asgRequest);

        /**
         * =======================================================================
         * =================== Create scaling up policy for ASG
         * =======================================================================
         * ===================
         */

        StepAdjustment upRule1 = new StepAdjustment().withMetricIntervalLowerBound(0.0)
                .withMetricIntervalUpperBound(25.0).withScalingAdjustment(1);

        StepAdjustment upRule2 = new StepAdjustment().withMetricIntervalLowerBound(25.0)
                .withMetricIntervalUpperBound(30.0).withScalingAdjustment(2);

        StepAdjustment upRule3 = new StepAdjustment().withMetricIntervalLowerBound(30.0)
                .withMetricIntervalUpperBound(null).withScalingAdjustment(3);

        String upPolicyName = "Scaling Up";

        PutScalingPolicyRequest scalingUpPolicy = new PutScalingPolicyRequest()
                .withAdjustmentType("ChangeInCapacity").withPolicyType("StepScaling")
                .withStepAdjustments(upRule1, upRule2, upRule3).withAutoScalingGroupName(autoScalingGroupName)
                .withPolicyName(upPolicyName).withEstimatedInstanceWarmup(120);

        StepAdjustment downRule1 = new StepAdjustment().withMetricIntervalLowerBound(-20.0)
                .withMetricIntervalUpperBound(-0.0).withScalingAdjustment(-1);

        StepAdjustment downRule2 = new StepAdjustment().withMetricIntervalLowerBound(-30.0)
                .withMetricIntervalUpperBound(-20.0).withScalingAdjustment(-2);

        StepAdjustment downRule3 = new StepAdjustment().withMetricIntervalLowerBound(null)
                .withMetricIntervalUpperBound(-30.0).withScalingAdjustment(-3);

        String downPolicyName = "Scaling Down";

        PutScalingPolicyRequest scalingDownPolicy = new PutScalingPolicyRequest().withAdjustmentType("")
                .withPolicyType("ChangeInCapacity").withStepAdjustments(downRule1, downRule2, downRule3)
                .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(downPolicyName)
                .withEstimatedInstanceWarmup(60);

        // attach policies to ASG and get ARN for setting alarm
        PutScalingPolicyResult scaleUpResult = autoScalingGroupClient.putScalingPolicy(scalingUpPolicy);
        String upArn = scaleUpResult.getPolicyARN();
        PutScalingPolicyResult scaleDownResult = autoScalingGroupClient.putScalingPolicy(scalingDownPolicy);
        String downArn = scaleDownResult.getPolicyARN();

        /**
         * =======================================================================
         * =================== Create alarms for policies
         * =======================================================================
         * ===================
         */

        String upAlarmName = "UpAlarm_Mild";
        String downAlarmName = "DownAlarm_Mild";
        Dimension dimension = new Dimension();
        dimension.setName("AutoScalingGroupName");
        dimension.setValue(autoScalingGroupName);

        PutMetricAlarmRequest upAlarmRequest = new PutMetricAlarmRequest().withAlarmName(upAlarmName)
                .withMetricName("CPUUtilization").withNamespace("AWS/EC2").withDimensions(dimension)
                .withStatistic(Statistic.SampleCount)
                .withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold).withThreshold(65.0)
                .withEvaluationPeriods(1).withPeriod(120).withAlarmActions(upArn);

        PutMetricAlarmRequest downAlarmRequest = new PutMetricAlarmRequest().withAlarmName(downAlarmName)
                .withNamespace("AWS/EC2").withDimensions(dimension).withMetricName("CPUUtilization")
                .withStatistic(Statistic.Average)
                .withComparisonOperator(ComparisonOperator.LessThanOrEqualToThreshold).withThreshold(60.0)
                .withEvaluationPeriods(1).withPeriod(120).withAlarmActions(downArn);

        cloudWatchClient.putMetricAlarm(upAlarmRequest);
        cloudWatchClient.putMetricAlarm(downAlarmRequest);

        System.out.println("All settings complete! \nReady for warmup...");

        /**
         * =======================================================================
         * =================== Warm up ELB
         * =======================================================================
         * ===================
         */

        String warmUpUrl = "http://" + loadGeneratorDns + "/warmup?dns=" + loadBalancerDns;
        sendGET(warmUpUrl);
        System.out.println("Warmup link: " + warmUpUrl);

        try {
            Thread.sleep(15 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Warmup complete!\nReady for battle...");

        /**
         * =======================================================================
         * =================== Start the test
         * =======================================================================
         * ===================
         */

        String testUrl = "http://" + loadGeneratorDns + "/junior?dns=" + loadBalancerDns;
        testId = sendGET(testUrl);
        System.out.println("Test ID is: " + testId);

        System.out.println("Test link: " + testUrl);

        try {
            Thread.sleep(60 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

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

        /**
         * =======================================================================
         * =================== Delete resources
         * =======================================================================
         * ===================
         */

        // clear ASG
        UpdateAutoScalingGroupRequest asgClearRequest = new UpdateAutoScalingGroupRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withMaxSize(0).withMinSize(0);
        autoScalingGroupClient.updateAutoScalingGroup(asgClearRequest);

        // delete policies
        DeletePolicyRequest upPolicyDeleteRequest = new DeletePolicyRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(upPolicyName);
        autoScalingGroupClient.deletePolicy(upPolicyDeleteRequest);

        DeletePolicyRequest downPolicyDeleteRequest = new DeletePolicyRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(downPolicyName);
        autoScalingGroupClient.deletePolicy(downPolicyDeleteRequest);
        System.out.println("Policies deleted...");

        // delete alarms
        DeleteAlarmsRequest alarmsDeleteRequest = new DeleteAlarmsRequest().withAlarmNames(upAlarmName,
                downAlarmName);
        cloudWatchClient.deleteAlarms(alarmsDeleteRequest);
        System.out.println("Alarms deleted...");

        // delete load balancer
        DeleteLoadBalancerRequest lgDeleteRequest = new DeleteLoadBalancerRequest()
                .withLoadBalancerName(loadBalancerName);
        loadBalancerClient.deleteLoadBalancer(lgDeleteRequest);
        System.out.println("Load generator deleted...");

        // delete ASG
        DeleteAutoScalingGroupRequest asgDeleteRequest = new DeleteAutoScalingGroupRequest()
                .withForceDelete(true).withAutoScalingGroupName(autoScalingGroupName);
        autoScalingGroupClient.deleteAutoScalingGroup(asgDeleteRequest);
        System.out.println("ASG deleted...");

        // delete launch configuration
        DeleteLaunchConfigurationRequest launchConfigDeleteRequest = new DeleteLaunchConfigurationRequest()
                .withLaunchConfigurationName(launchConfigName);
        autoScalingGroupClient.deleteLaunchConfiguration(launchConfigDeleteRequest);
        System.out.println("Launch configuration deleted...");

        // delete security group
        DeleteSecurityGroupRequest sgDeleteRequest = new DeleteSecurityGroupRequest()
                .withGroupName(allPurposeSecurityName);
        ec2.deleteSecurityGroup(sgDeleteRequest);
        System.out.println("Security group deleted...");

        /**
         * =======================================================================
         * =================== All done
         * =======================================================================
         * ===================
         */
        System.out.println("All done :)");

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

    } catch (Exception e) {
        System.out.println("Unexcepted error!");
        System.out.println(e.getMessage());
    }

}

From source file:TableCreator.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//from   w w  w . j a  v  a2  s .  com
    long readCapacity = Long.valueOf(args[0]);
    long writeCapacity = Long.valueOf(args[1]);
    try {
        String tableName = "messages";

        //          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("messageId").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("messageId")
                        .withAttributeType(ScalarAttributeType.S))
                .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:SNSMobilePush.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//from  ww  w. j a  v  a 2  s.co m
     * TODO: 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
     */
    AmazonSNS sns = new AmazonSNSClient(
            new PropertiesCredentials(SNSMobilePush.class.getResourceAsStream("AwsCredentials.properties")));

    sns.setEndpoint("https://sns.us-east-1.amazonaws.com");
    System.out.println("===========================================\n");
    System.out.println("Getting Started with Amazon SNS");
    System.out.println("===========================================\n");
    try {
        SNSMobilePush sample = new SNSMobilePush(sns);
        /* TODO: Uncomment the services you wish to use. */
        sample.demoAndroidAppNotification();
        // sample.demoKindleAppNotification();
        // sample.demoAppleAppNotification();
        // sample.demoAppleSandboxAppNotification();
        // sample.demoBaiduAppNotification();
        // sample.demoWNSAppNotification();
        // sample.demoMPNSAppNotification();
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SNS, 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 SNS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}