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:com.onemenu.server.util.awsnotification.SNSMobilePush.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*// w  ww  . j a  v a 2  s.c o  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.getClassLoader().getResourceAsStream("AwsCredentials.properties")));

    sns.setEndpoint("https://sns.us-west-2.amazonaws.com");
    System.out.println("===========================================\n");
    System.out.println("Getting Started with Amazon SNS");
    System.out.println("===========================================\n");
    try {
        SNSMobilePush sample = new SNSMobilePush(sns);
        sample.demoAppleSandboxAppNotification();
    } 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());
    }
}

From source file:com.pinterest.arcee.aws.EC2HostInfoDAOImpl.java

License:Apache License

private Collection<String> handleInvalidInstanceId(AmazonServiceException ex) throws Exception {
    List<String> instanceIds = new ArrayList<>();
    if (ex.getErrorCode().equals(INSTANCE_MALFORMED_ERROR)) {
        Matcher matcher = MALFORMED_INSTANCE_ID_PATTERN.matcher(ex.getErrorMessage());
        while (matcher.find()) {
            instanceIds.add(matcher.group("id"));
        }//from w w  w. j a v  a  2  s  . c  o  m
    } else if (ex.getErrorCode().equals(INSTANCE_NOT_FOUND_ERROR)) {
        Matcher matcher = NON_EXISTING_INSTANCE_ID_PATTERN.matcher(ex.getErrorMessage());
        while (matcher.find()) {
            instanceIds.remove(matcher.group(0));
        }
    } else {
        LOG.error(String.format("Ignore this error (Error Type: %s Error Code: %s, Error message: %s)",
                ex.getErrorType().toString(), ex.getErrorCode(), ex.getErrorMessage()));
    }
    return instanceIds;
}

From source file:com.qubole.presto.kinesis.s3config.S3TableConfigClient.java

License:Apache License

/**
 * Connect to S3 directory to look for new or updated table definitions and then
 * update the map.//from  ww w . j  ava 2 s.c om
 */
protected void updateTablesFromS3() {
    long now = System.currentTimeMillis();

    List<S3ObjectSummary> objectList = this.getObjectSummaries();
    AmazonS3Client s3client = this.clientManager.getS3Client();
    AmazonS3URI directoryURI = new AmazonS3URI(this.bucketUrl);

    for (S3ObjectSummary objInfo : objectList) {
        if (!this.internalMap.containsKey(objInfo.getKey())
                || objInfo.getLastModified().getTime() >= this.lastCheck) {
            // New or updated file, so we must read from AWS
            try {
                if (objInfo.getKey().endsWith("/")) {
                    continue;
                }

                log.info("Getting : %s - %s", objInfo.getBucketName(), objInfo.getKey());
                S3Object object = s3client
                        .getObject(new GetObjectRequest(objInfo.getBucketName(), objInfo.getKey()));

                StringBuilder resultStr = new StringBuilder("");
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(object.getObjectContent()))) {
                    boolean hasMore = true;
                    while (hasMore) {
                        String line = reader.readLine();
                        if (line != null) {
                            resultStr.append(line);
                        } else {
                            hasMore = false;
                        }
                    }

                    KinesisStreamDescription table = streamDescriptionCodec.fromJson(resultStr.toString());

                    internalMap.put(objInfo.getKey(), table);
                    log.info("Put table description into the map from %s", objInfo.getKey());
                } catch (IOException iox) {
                    log.error("Problem reading input stream from object.", iox);
                }
            } catch (AmazonServiceException ase) {
                StringBuilder sb = new StringBuilder();
                sb.append("Caught an AmazonServiceException, which means your request made it ");
                sb.append("to Amazon S3, but was rejected with an error response for some reason.\n");
                sb.append("Error Message:    " + ase.getMessage());
                sb.append("HTTP Status Code: " + ase.getStatusCode());
                sb.append("AWS Error Code:   " + ase.getErrorCode());
                sb.append("Error Type:       " + ase.getErrorType());
                sb.append("Request ID:       " + ase.getRequestId());
                log.error(sb.toString(), ase);
            } catch (AmazonClientException ace) {
                StringBuilder sb = new StringBuilder();
                sb.append("Caught an AmazonClientException, " + "which means the client encountered "
                        + "an internal error while trying to communicate" + " with S3, "
                        + "such as not being able to access the network.");
                sb.append("Error Message: " + ace.getMessage());
                log.error(sb.toString(), ace);
            }
        }
    } // end loop through object descriptions

    log.info("Completed updating table definitions from S3.");
    this.lastCheck = now;

    return;
}

From source file:com.rmn.qa.aws.AwsVmManager.java

License:Open Source License

/**
 * Attempts to run the {@link com.amazonaws.services.ec2.model.RunInstancesRequest RunInstancesRequest}, falling
 * back on alternative subnets if capacity is full in the current region.
 *
 * @param   request/*from  w ww  .j  a v a  2s.  com*/
 * @param   requestNumber
 *
 * @return
 *
 * @throws  NodesCouldNotBeStartedException
 */
private RunInstancesResult getResults(final RunInstancesRequest request, int requestNumber)
        throws NodesCouldNotBeStartedException {
    RunInstancesResult runInstancesResult;
    try {
        AmazonEC2Client localClient = getClient();
        if (localClient == null) {
            throw new RuntimeException("The client is not initialized");
        }
        runInstancesResult = localClient.runInstances(request);
    } catch (AmazonServiceException e) {

        // If there is insufficient capacity in this subnet / availability zone, then we want to try other
        // configured subnets
        if ("InsufficientInstanceCapacity".equals(e.getErrorCode())
                || "VolumeTypeNotAvailableInZone".equals(e.getErrorCode())) {
            log.error(String.format("Insufficient capacity in subnet [%s]: %s", request.getSubnetId(), e));
            requestNumber = requestNumber + 1;

            Properties awsProperties = getAwsProperties();
            String fallBackSubnetId = awsProperties
                    .getProperty(region + "_subnet_fallback_id_" + requestNumber);

            // Make sure and only try to recursively loop so as long as we have a valid fallback subnet id.  Logic
            // to also
            // prevent an accidental infinite loop
            if (fallBackSubnetId != null && requestNumber < 5) {
                log.info("Setting fallback subnet: " + fallBackSubnetId);

                // Modify the original request with the new subnet ID we're trying to fallback on
                request.withSubnetId(fallBackSubnetId);
            } else {
                throw new NodesCouldNotBeStartedException(
                        "Sufficient resources were not available in any of the availability zones");
            }

            return getResults(request, requestNumber);
        } else {

            // We got an error other than insufficient capacity, and should just throw it for the caller to handle
            throw e;
        }
    }

    return runInstancesResult;
}

From source file:com.rmn.qa.aws.AwsVmManager.java

License:Open Source License

/**
 * Terminates the specified instance./*from w  w w .  j av  a2  s. c  o  m*/
 *
 * @param  instanceId  Id of the instance to terminate
 */
public boolean terminateInstance(final String instanceId) {
    TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest();
    terminateRequest.withInstanceIds(instanceId);

    AmazonEC2Client localClient = getClient();
    if (localClient == null) {
        throw new RuntimeException("The client is not initialized");
    }
    TerminateInstancesResult result;
    try {
        result = localClient.terminateInstances(terminateRequest);
    } catch (AmazonServiceException ase) {
        // If the node was terminated outside of this plugin, handle the error appropriately
        if (ase.getErrorCode().equals("InvalidInstanceID.NotFound")) {
            log.error("Node not found when attempting to remove: " + instanceId);
            return false;
        } else {
            throw ase;
        }
    }
    List<InstanceStateChange> stateChanges = result.getTerminatingInstances();
    boolean terminatedInstance = false;
    for (InstanceStateChange stateChange : stateChanges) {
        if (instanceId.equals(stateChange.getInstanceId())) {
            terminatedInstance = true;

            InstanceState currentState = stateChange.getCurrentState();
            if (currentState.getCode() != 32 && currentState.getCode() != 48) {
                log.error(String.format(
                        "Machine state for id %s should be terminated (48) or shutting down (32) but was %s instead",
                        instanceId, currentState.getCode()));
                return false;
            }
        }
    }

    if (!terminatedInstance) {
        log.error("Matching terminated instance was not found for instance " + instanceId);
        return false;
    }

    log.info(String.format("Node [%s] successfully terminated", instanceId));
    return true;
}

From source file:com.rodosaenz.samples.aws.sqs.AwsSqsSimpleExample.java

License:Open Source License

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

    /*/*from  w  ww  . ja  v  a2s.  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_EAST_1);
    sqs.setRegion(usWest2);

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

    String queue_name = "com-rodosaenz-examples-aws-sqs";

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called " + queue_name + ".\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(queue_name);
        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 " + queue_name + ".\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);
        receiveMessageRequest.setMaxNumberOfMessages(1);
        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(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));

        //Get attributes
        GetQueueAttributesRequest request = new GetQueueAttributesRequest(myQueueUrl).withAttributeNames("All");
        final Map<String, String> attributes = sqs.getQueueAttributes(request).getAttributes();

        System.out.println("  Policy: " + attributes.get("Policy"));
        System.out.println("  MessageRetentionPeriod: " + attributes.get("MessageRetentionPeriod"));
        System.out.println("  MaximumMessageSize: " + attributes.get("MaximumMessageSize"));
        System.out.println("  CreatedTimestamp: " + attributes.get("CreatedTimestamp"));
        System.out.println("  VisibilityTimeout: " + attributes.get("VisibilityTimeout"));
        System.out.println("  QueueArn: " + attributes.get("QueueArn"));
        System.out.println("  ApproximateNumberOfMessages: " + attributes.get("ApproximateNumberOfMessages"));
        System.out.println("  ApproximateNumberOfMessagesNotVisible: "
                + attributes.get("ApproximateNumberOfMessagesNotVisible"));
        System.out.println("  DelaySeconds: " + attributes.get("DelaySeconds"));

        // 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:com.saife.sample.S3Sample.java

License:Apache License

/**
 * //from  w  w w.j  av  a  2  s. c  o m
 */
private void initS3() {
    // S3 credential identity
    final String me = "john.curtis@saife-tiprnet";

    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider(me).getCredentials();
    } catch (final 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 (/home/builder/.aws/credentials), and is in valid format.", e);
    }

    s3 = new AmazonS3Client(credentials);
    final Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    // define a bucket name
    bucketName = null;

    try {

        /*
         * List the buckets in your account
         */
        for (final Bucket bucket : s3.listBuckets()) {
            if (bucket.getName().startsWith("saife-test-bucket")) {
                bucketName = bucket.getName();
                System.out.println("Found Test Bucket:" + bucket.getName());
            }
        }

        /*
         * Create a globally unique bucket name if needed.
         */
        if (null == bucketName) {
            bucketName = "saife-test-bucket" + UUID.randomUUID();
            System.out.println("Creating bucket " + bucketName + "\n");
            s3.createBucket(bucketName);
        }
    } catch (final 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 (final 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());
    }

    System.out.println("S3 services are enabled.");
}

From source file:com.sjsu.backitup.AwsConsoleApp.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();/*  w ww .  ja v a2s  . co  m*/

    /*
     * Amazon EC2
     *
     * The AWS EC2 client allows you to create, delete, and administer
     * instances programmatically.
     *
     * In this sample, we use an EC2 client to get a list of all the
     * availability zones, and all instances sorted by reservation id.
     */
    try {
    } 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());
    }

    /*
     * Amazon SimpleDB
     *
     * The AWS SimpleDB client allows you to query and manage your data
     * stored in SimpleDB domains (similar to tables in a relational DB).
     *
     * In this sample, we use a SimpleDB client to iterate over all the
     * domains owned by the current user, and add up the number of items
     * (similar to rows of data in a relational DB) in each domain.
     */

    /*
     * Amazon S3
     *
     * The AWS S3 client allows you to manage buckets and programmatically
     * put and get objects to those buckets.
     *
     * In this sample, we use an S3 client to iterate over all the buckets
     * owned by the current user, and all the object metadata in each
     * bucket, to obtain a total object and space usage count. This is done
     * without ever actually downloading a single object -- the requests
     * work with object metadata only.
     */
    try {
        List<Bucket> buckets = s3.listBuckets();

        long totalSize = 0;
        int totalItems = 0;
        for (Bucket bucket : buckets) {
            /*
             * In order to save bandwidth, an S3 object listing does not
             * contain every object in the bucket; after a certain point the
             * S3ObjectListing is truncated, and further pages must be
             * obtained with the AmazonS3Client.listNextBatchOfObjects()
             * method.
             */
            ObjectListing objects = s3.listObjects(bucket.getName());
            do {
                for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                    totalSize += objectSummary.getSize();
                    totalItems++;
                }
                objects = s3.listNextBatchOfObjects(objects);
            } while (objects.isTruncated());
        }

        System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s), " + "containing " + totalItems
                + " objects with a total size of " + totalSize + " bytes.");
    } catch (AmazonServiceException ase) {
        /*
         * AmazonServiceExceptions represent an error response from an AWS
         * services, i.e. your request made it to AWS, but the AWS service
         * either found it invalid or encountered an error trying to execute
         * it.
         */
        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) {
        /*
         * AmazonClientExceptions represent an error that occurred inside
         * the client on the local host, either while trying to send the
         * request to AWS or interpret the response. For example, if no
         * network connection is available, the client won't be able to
         * connect to AWS to execute a request and will throw an
         * AmazonClientException.
         */
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.sjsu.cmpe281.team06.NovaMiaas.SimpleQueueServiceSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*from ww w . j av  a2s . c o m*/
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     *
     * 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 ClasspathPropertiesFileCredentialsProvider());
    Region usWest1 = Region.getRegion(Regions.US_WEST_1);
    sqs.setRegion(usWest1);

    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 new 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:com.sjsu.faceit.example.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//  w w  w .j  a  va  2  s .  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
     */
    System.out.println(new File(".").getAbsolutePath());
    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, "abc/" + key, new File("/Users/prayag/Desktop/2.jpg")));

        /*
         * 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, "abc/" + 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());
    }
}