Example usage for com.amazonaws AmazonServiceException getErrorCode

List of usage examples for com.amazonaws AmazonServiceException getErrorCode

Introduction

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

Prototype

public String getErrorCode() 

Source Link

Document

Returns the AWS error code represented by this exception.

Usage

From source file:aws.sample.InlineGettingStartedCodeSampleApp.java

License:Open Source License

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

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

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

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

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

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

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("default");
    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());
    }

    // ============================================================================================//
    // =========================== 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:aws.sample.InlineTaggingCodeSampleApp.java

License:Open Source License

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

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

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

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

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

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

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("default");
    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(6 * 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:aws.sample.Requests.java

License:Open Source License

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

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

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

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

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

        // Look through each request and determine if they are all in the active state.
        for (SpotInstanceRequest describeResponse : describeResponses) {
            System.out.println(" " + describeResponse.getSpotInstanceRequestId() + " is in the "
                    + describeResponse.getState() + " state.");

            // If the state is open, it hasn't changed since we attempted to request it.
            // There is the potential for it to transition almost immediately to closed or
            // cancelled so we compare against open instead of active.
            if (describeResponse.getState().equals("open")) {
                return true;
            }

            // Add the instance id to the list we will eventually terminate.
            instanceIds.add(describeResponse.getInstanceId());
        }
    } catch (AmazonServiceException e) {
        // Print out the error.
        System.out.println("Error when calling describeSpotInstances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());

        // If we have an exception, ensure we don't break out of the loop.
        // This prevents the scenario where there was blip on the wire.
        return true;
    }

    return false;
}

From source file:aws.sample.Requests.java

License:Open Source License

/**
 * The cleanup method will cancel and active requests and terminate any running instances that were created using this object.
 *//*from   ww w  .  j av a 2 s  .  c o  m*/
public void cleanup() {
    // ==========================================================================//
    // ================= Cancel/Terminate Your Spot Request =====================//
    // ==========================================================================//
    try {
        // Cancel requests.
        System.out.println("Cancelling 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());
    }

    try {
        // Terminate instances.
        System.out.println("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());
    }

    // Delete all requests and instances that we have terminated.
    instanceIds.clear();
    spotInstanceRequestIds.clear();
}

From source file:aws.sample.S3Sample.java

License:Open Source License

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

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*from  ww  w  .  j  a  v  a2s. c  o m*/
     * Important: Be sure to fill in your AWS access credentials in the AwsCredentials.properties file before you try to run this sample. http://aws.amazon.com/security-credentials
     */
    AmazonSimpleDB sdb = new AmazonSimpleDBClient(
            new PropertiesCredentials(SimpleDBSample.class.getResourceAsStream("AwsCredentials.properties")));

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

    try {
        // Create a domain
        String myDomain = "MyStore";
        System.out.println("Creating domain called " + myDomain + ".\n");
        sdb.createDomain(new CreateDomainRequest(myDomain));

        // List domains
        System.out.println("Listing all domains in your account:\n");
        for (String domainName : sdb.listDomains().getDomainNames()) {
            System.out.println("  " + domainName);
        }
        System.out.println();

        // Put data into a domain
        System.out.println("Putting data into " + myDomain + " domain.\n");
        sdb.batchPutAttributes(new BatchPutAttributesRequest(myDomain, createSampleData()));

        // Select data from a domain
        // Notice the use of backticks around the domain name in our select expression.
        String selectExpression = "select * from `" + myDomain + "` where Category = 'Clothes'";
        System.out.println("Selecting: " + selectExpression + "\n");
        SelectRequest selectRequest = new SelectRequest(selectExpression);
        for (Item item : sdb.select(selectRequest).getItems()) {
            System.out.println("  Item");
            System.out.println("    Name: " + item.getName());
            for (Attribute attribute : item.getAttributes()) {
                System.out.println("      Attribute");
                System.out.println("        Name:  " + attribute.getName());
                System.out.println("        Value: " + attribute.getValue());
            }
        }
        System.out.println();

        // Delete values from an attribute
        System.out.println("Deleting Blue attributes in Item_O3.\n");
        Attribute deleteValueAttribute = new Attribute("Color", "Blue");
        sdb.deleteAttributes(
                new DeleteAttributesRequest(myDomain, "Item_03").withAttributes(deleteValueAttribute));

        // Delete an attribute and all of its values
        System.out.println("Deleting attribute Year in Item_O3.\n");
        sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03")
                .withAttributes(new Attribute().withName("Year")));

        // Replace an attribute
        System.out.println("Replacing Size of Item_03 with Medium.\n");
        List<ReplaceableAttribute> replaceableAttributes = new ArrayList<ReplaceableAttribute>();
        replaceableAttributes.add(new ReplaceableAttribute("Size", "Medium", true));
        sdb.putAttributes(new PutAttributesRequest(myDomain, "Item_03", replaceableAttributes));

        // Delete an item and all of its attributes
        System.out.println("Deleting Item_03.\n");
        sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03"));

        // Delete a domain
        System.out.println("Deleting " + myDomain + " domain.\n");
        sdb.deleteDomain(new DeleteDomainRequest(myDomain));
    } 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:aws.sample.SimpleQueueServiceSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*ww w .j a v  a 2 s . c  o  m*/
     * Important: Be sure to fill in your AWS access credentials in the AwsCredentials.properties file before you try to run this sample. http://aws.amazon.com/security-credentials
     */
    AmazonSQS sqs = new AmazonSQSClient(new PropertiesCredentials(
            SimpleQueueServiceSample.class.getResourceAsStream("/AwsCredentials.properties")));

    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:awslabs.lab22.SolutionCode.java

License:Open Source License

@Override
public TableDescription getTableDescription(AmazonDynamoDBClient ddbClient, String tableName) {
    try {//from w w  w .  j  a  v  a  2  s.co  m
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);

        DescribeTableResult describeTableResult = ddbClient.describeTable(describeTableRequest);

        return describeTableResult.getTable();
    } catch (AmazonServiceException ase) {
        // If the table isn't found, there's no problem.
        // If the error is something else, re-throw the exception to bubble it up to the caller.
        if (!ase.getErrorCode().equals("ResourceNotFoundException")) {
            throw ase;
        }
        return null;
    }
}

From source file:awslabs.lab41.Lab41.java

License:Open Source License

public void appMode_Run(LabVariables labVariables) throws InterruptedException, IOException {
    AWSCredentials credentials = getCredentials("appmode");

    Credentials devCredentials = null, prodCredentials = null;
    AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(credentials);
    //stsClient.setRegion(Lab41.region);

    System.out.println("\nAssuming developer role to retrieve developer session credentials.");
    Boolean retry;/* w ww. ja va  2s.  co m*/
    long start = System.currentTimeMillis();
    do {
        try {
            devCredentials = labCode.appMode_AssumeRole(stsClient, labVariables.getDevelopmentRoleArn(),
                    "dev_session");
            retry = false;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().equals("AccessDenied")) {
                // If we get access denied, the policy that we created hasn't fully propagated through STS
                // so we need to wait and retry. This code will retry for 30 seconds before timing out.
                long now = System.currentTimeMillis();
                if (now >= (start + 30 * 1000)) {
                    System.out.println();
                    throw ase; // Stop waiting.
                }
                retry = true;
                System.out.print(".");
                // Sleep for a second before trying again.
                Thread.sleep(1000);
            } else {
                throw ase;
            }
        }
    } while (retry);

    System.out.println("\nAssuming production role to retrieve production session credentials.");

    start = System.currentTimeMillis();
    do {
        try {
            prodCredentials = labCode.appMode_AssumeRole(stsClient, labVariables.getProductionRoleArn(),
                    "prod_session");
            retry = false;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().equals("AccessDenied")) {
                // If we get access denied, the policy that we created hasn't fully propagated through STS
                // so we need to wait and retry. This code will retry for 30 seconds before timing out.
                long now = System.currentTimeMillis();
                if (now >= (start + 30 * 1000)) {
                    System.out.println();
                    throw ase; // Stop waiting.
                }
                retry = true;
                System.out.print(".");
                // Sleep for a second before trying again.
                Thread.sleep(1000);
            } else {
                throw ase;
            }
        }
    } while (retry);

    System.out.println("\nCreating S3 client objects.");

    AmazonS3Client devS3Client = labCode.appMode_CreateS3Client(devCredentials, Lab41.region);
    AmazonS3Client prodS3Client = labCode.appMode_CreateS3Client(prodCredentials, Lab41.region);

    System.out.println("\nTesting Developer Session...");

    // Create the dev credentials.
    BasicSessionCredentials devSession = new BasicSessionCredentials(devCredentials.getAccessKeyId(),
            devCredentials.getSecretAccessKey(), devCredentials.getSessionToken());

    // Test services access using the dev credentials.
    System.out.println(
            "  IAM: " + (optionalLabCode.appMode_TestIamAccess(Lab41.region, devSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println(
            "  SQS: " + (optionalLabCode.appMode_TestSqsAccess(Lab41.region, devSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println(
            "  SNS: " + (optionalLabCode.appMode_TestSnsAccess(Lab41.region, devSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println("  S3:");
    for (String bucketName : labVariables.getBucketNames()) {
        testS3Client(devS3Client, bucketName);
    }

    System.out.println("\nTesting Production Session...");
    // Create the prod credentials.
    BasicSessionCredentials prodSession = new BasicSessionCredentials(prodCredentials.getAccessKeyId(),
            prodCredentials.getSecretAccessKey(), prodCredentials.getSessionToken());

    // Test services using the prod credentials.
    System.out.println(
            "  IAM: " + (optionalLabCode.appMode_TestIamAccess(Lab41.region, prodSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println(
            "  SQS: " + (optionalLabCode.appMode_TestSqsAccess(Lab41.region, prodSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println(
            "  SNS: " + (optionalLabCode.appMode_TestSnsAccess(Lab41.region, prodSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println("  S3:");
    for (String bucketName : labVariables.getBucketNames()) {
        testS3Client(prodS3Client, bucketName);
    }
}

From source file:awslabs.labutility.LabUtility.java

License:Open Source License

public static void dumpError(Exception ex) {
    if (ex instanceof AmazonServiceException) {
        AmazonServiceException ase = (AmazonServiceException) ex;
        System.out.println();//w w  w  .  j a  v  a2 s. c o m
        System.out.println("Caught an AmazonServiceException, which means your request made it AWS,");
        System.out.println("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());
        System.out.println("Stack trace:");
        ase.printStackTrace();
    } else if (ex instanceof AmazonClientException) {
        AmazonClientException ace = (AmazonClientException) ex;
        System.out.println();
        System.out.println("Caught an AmazonClientException, which means the client encountered");
        System.out.println("a problem without before communicating with the service.");
        System.out.println("Error Message: " + ace.getMessage());
        System.out.println("Stack trace:");
        ace.printStackTrace();
    } else {
        System.out.println();
        System.out.println("Caught exception [" + ex.getClass() + "].");
        System.out.println("Error Message: " + ex.getMessage());
        System.out.println("Cause: " + ex.getCause());
        System.out.println("Stack trace:");
        ex.printStackTrace();
    }
}