Example usage for com.amazonaws AmazonServiceException getRequestId

List of usage examples for com.amazonaws AmazonServiceException getRequestId

Introduction

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

Prototype

public String getRequestId() 

Source Link

Document

Returns the AWS request ID that uniquely identifies the service request the caller made.

Usage

From source file:com.stockcloud.updatestock.java

License:Open Source License

public void update(String stockName) throws Exception {
    init();//from w w  w  . java2  s . co m
    String csvString;
    URL url = null;
    URLConnection urlConn = null;
    InputStreamReader inStream = null;
    BufferedReader buff = null;
    // static AmazonDynamoDBClient dynamoDB;
    // String jb=symbol.substring(0, 3)+"+"+symbol.substring(3, 7);
    // System.out.println(jb);
    // String[] newsymbol=symbol.split(",");
    int i = 0;
    String symbol = stockName;
    // String symbol[] = { "ABT", "ABBV", "ACE", "ACN", "ACT", "ADBE",
    // "ADT",
    // "AET", "AFL", "ARG", "AA", "ALL", "ALTR", "AMZN", "AAPL",
    // "BLL", "BAC", "BMS", "BBY", "BLK", "BSX", "CA", "COF", "CCL",
    // "CAT", "CERN", "CVX", "CSCO", "COH", "KO", "COST", "DVN",
    // "DTV", "DG", "DOV", "DOW", "DUK", "EBAY", "EOG", "EMR", "EFX",
    // "EQR", "EXPE", "ESRX", "FB", "FE", "FLIR", "FMC", "F", "FOSL",
    // "GME", "GPS", "GD", "GE", "GIS", "GS", "GOOG", "HOG", "HRS",
    // "HCP", "HAS", "HES", "HD", "HST", "HUM", "ITW", "INTC", "ICE",
    // "IBM", "INTU", "IVZ", "JOY", "JNPR", "KEY", "KMI", "KLAC",
    // "KSS", "KR", "LB", "LRCX", "LM", "LEN", "LNC", "LOW", "MAC",
    // "MMM", "M", "MAR", "MA", "MCD", "MRK", "MET", "MU", "MSFT",
    // "MNST", "MS", "MOS", "MUR", "MYL" };

    // String
    // Num[]={"1","2","3","4","5","6","7","8","9","10","11","12","13","14",
    // "15","16","17","18","19","20","21","22","23","24","25","26","27","28",
    // "29","30","3","2","3","4","5","6","7","8","9","10","1","2","3","4","5",
    // "6","7","8","9","10","1","2","3","4","5","6","7","8","9","10","1","2",
    // "3","4","5","6","7","8","9","10","1","2","3","4","5","6","7","8","9",
    // "10","1","2","3","4","5","6","7","8","9","10",}

    // loop to get the current data of every stocks(100)

    url = new URL("http://quote.yahoo.com/d/quotes.csv?s=" + symbol + "&f=osl1d1t1c1ohgv&e=.csv");
    urlConn = url.openConnection();
    inStream = new InputStreamReader(urlConn.getInputStream());
    buff = new BufferedReader(inStream);
    // get the quote as a csv string
    csvString = buff.readLine();
    // while(csvString!=null)

    // {
    // parse the csv string
    StringTokenizer tokenizer = new StringTokenizer(csvString, ",");
    String open = tokenizer.nextToken();
    String ticker = tokenizer.nextToken();
    String price = tokenizer.nextToken();
    String tradeDate = tokenizer.nextToken();
    String tradeTime = tokenizer.nextToken();

    System.out
            .println("Symbol: " + ticker + " Price: " + price + " Date: " + tradeDate + " Time: " + tradeTime);

    // table
    try {
        String tableName = symbol + "current";

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

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.waitForTableToBecomeActive(dynamoDB, tableName);
        }
        Map<String, AttributeValue> item = newItem(ticker, price, tradeDate, tradeTime, open);
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

    }

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

    inStream.close();
    buff.close();

}

From source file:com.supprema.utils.S3Sample.java

License:Open Source License

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

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

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

    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:com.topera.epoch.service.S3Util.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*  ww  w.ja v a 2  s .  c o  m*/
     * Create your credentials file at ~/.aws/credentials (C:\Users\USER_NAME\.aws\credentials for Windows users) 
     * and save the following lines after replacing the underlined values with your own.
     *
     * [default]
     * aws_access_key_id = YOUR_ACCESS_KEY_ID
     * aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
     */
    AWSCredentials creds = new AWSCredentials() {

        public String getAWSSecretKey() {
            // TODO Auto-generated method stub
            return "5VVtmI7vcecuVbw8JsG4uo2O1/9RwwLHrTT01Itz";
        }

        public String getAWSAccessKeyId() {
            // TODO Auto-generated method stub
            return "AKIAJCMYALI46A2DIPRQ";
        }
    };

    AmazonS3 s3 = new AmazonS3Client(creds);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    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:com.tweettrends.pravar.FilterStreamExample.java

License:Apache License

public static void main(String[] args) {
    final SimpleQueueService simpleQueueService = new SimpleQueueService();
    final List<Future<String>> results = new ArrayList<Future<String>>();
    final HashMap<Future<String>, Message> map = new HashMap<Future<String>, Message>(100);
    SimpleNotificationService simpleNotificationService = new SimpleNotificationService();
    simpleNotificationService.subscribeToTopic();

    try {//from  www .j  a v  a 2 s.co  m
        //simpleQueueService.createQueue();
        simpleQueueService.listQueues();
    } 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());
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                FilterStreamExample.run("9sB7Y7zyxFTgEpk87ZwuZMFZR",
                        "TPvVJJ09FhQeduDR10xJw8t5LJ4i75uu6GYQefVtHt7ebUTgZi",
                        "840399362987560960-MTKPBj2U67boTVP4ug6LWiUdvksF0gO",
                        "adanfdOhMgPmil1TsWpD1vKvfdY6ErRVX2xCqPS6NgaEF", simpleQueueService);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }).start();

    ExecutorService pool = Executors.newCachedThreadPool();

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Entered runnable");
            while (true) {
                Iterator<Future<String>> iterator = results.iterator();

                try {
                    sharedSemaphore.acquire();
                    while (iterator.hasNext()) {
                        Future<String> result = iterator.next();
                        String sentiment = result.get();
                        Message message = map.get(result);
                        // send sentiment and message to SNS
                        System.out.println("Notifying SNS");
                        //simpleNotificationService.publishToTopic(message.getBody());
                        iterator.remove();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } finally {
                    sharedSemaphore.release();
                }

            }
        }
    });
    thread.start();

    while (true) {
        List<Message> messages = simpleQueueService.receiveMessages();
        if (messages != null) {
            System.out.println("Received Messages!");

            for (Message msg : messages) {
                System.out.println("Message body : " + msg.getBody());
            }
            simpleQueueService.deleteMessages(messages);

            for (Message message : messages) {
                Worker worker = new Worker(message);
                Future<String> result = pool.submit(worker);

                try {
                    sharedSemaphore.acquire();
                    results.add(result);
                    map.put(result, message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    sharedSemaphore.release();
                }

            }
        }
    }

}

From source file:com.ub.ml.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*from  w  w  w  . j a v  a  2s .c o m*/
     * Create your credentials file at ~/.aws/credentials (C:\Users\USER_NAME\.aws\credentials for Windows users) 
     * and save the following lines after replacing the underlined values with your own.
     *
     * [default]
     * aws_access_key_id = YOUR_ACCESS_KEY_ID
     * aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
     */

    AmazonS3 s3 = new AmazonS3Client();
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    s3.setRegion(usWest2);

    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:com.uiintl.backup.agent.AwsBackupAgent.java

License:Open Source License

void handleAwsException(AmazonClientException ace) {

    if (ace instanceof AmazonServiceException) {
        AmazonServiceException ase = (AmazonServiceException) ace;

        logger.error(//from   www. j  av  a2s  .c  o  m
                "Caught an AmazonServiceException, which means your request made it to Amazon S3, but was rejected with an error response for some reason.");
        logger.error("Error Message: {}", ase.getMessage());
        logger.error("HTTP Status Code: {}", ase.getStatusCode());
        logger.error("AWS Error Code: {}", ase.getErrorCode());
        logger.error("Error Type: {}", ase.getErrorType());
        logger.error("Request ID: {}", ase.getRequestId());
        logger.error("Stacktrace: ", ase);
    } else {
        logger.error(
                "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.");
        logger.error("Error Message: {}", ace.getMessage());
    }
}

From source file:com.uiintl.backup.agent.samples.S3Sample.java

License:Open Source License

public static void main2(String[] args) throws IOException {
    /*//ww w  .jav a  2  s  .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
     */
    AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.AP_SOUTHEAST_2);
    s3.setRegion(usWest2);

    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:com.vb.services.database.rds.MySQLDBUtils.java

private void updateMySQLDBInstanceSpecificationsConfig() {

    MySQLDBInstanceSpecificationsConfig mysqlDBInstanceSpecificationsConfig = createDefaultDBInstanceSpecificationsConfig();
    this.mysqlDB.setDbInstanceSpecificationsConfig(mysqlDBInstanceSpecificationsConfig);

    try {/* w  w  w. j  a v  a2  s  .  co m*/
        this.createDBInstanceRequest.setEngine(this.mysqlDB.getDbInstanceSpecificationsConfig().getDbEngine());
        this.createDBInstanceRequest
                .setLicenseModel(this.mysqlDB.getDbInstanceSpecificationsConfig().getLicenceModel());
        this.createDBInstanceRequest
                .setEngineVersion(this.mysqlDB.getDbInstanceSpecificationsConfig().getDbVersion());
        this.createDBInstanceRequest
                .setDBInstanceClass(this.mysqlDB.getDbInstanceSpecificationsConfig().getDbInstanceClass());
        this.createDBInstanceRequest
                .setMultiAZ(this.mysqlDB.getDbInstanceSpecificationsConfig().getMultiAZDeployment());
        this.createDBInstanceRequest
                .setStorageType(this.mysqlDB.getDbInstanceSpecificationsConfig().getStorageType());
        this.createDBInstanceRequest
                .setAllocatedStorage(this.mysqlDB.getDbInstanceSpecificationsConfig().getAllocatedStorage());
    } catch (AmazonServiceException ase) {
        System.out.println("ERROR : error during MySQLDBInstanceSpecificationsConfig setup.");
        System.out.println("Caught an AmazonServiceException");
        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());
        ase.printStackTrace();
    } catch (AmazonClientException ace) {
        System.out.println("ERROR : error during MySQLDBInstanceSpecificationsConfig setup.");
        System.out.println("Caught an AmazonClientException");
        System.out.println("Error Message: " + ace.getMessage());
        ace.printStackTrace();
    }
}

From source file:com.vb.services.database.rds.MySQLDBUtils.java

private void updateMySQLDBSettingsConfig(String dbInstanceIdentifier, String masterUserName,
        String masterPassword) {/*from   w w  w.  j  ava2s  .  c  o m*/
    MySQLDBSettingsConfig mysqlDBSettingsConfig = createDBSettingsConfig(dbInstanceIdentifier, masterUserName,
            masterPassword);
    this.mysqlDB.setDbSettingsConfig(mysqlDBSettingsConfig);

    try {
        this.createDBInstanceRequest
                .setDBInstanceIdentifier(this.mysqlDB.getDbSettingsConfig().getDbInstanceIdentifier());
        this.createDBInstanceRequest.setMasterUsername(this.mysqlDB.getDbSettingsConfig().getMasterUserName());
        this.createDBInstanceRequest
                .setMasterUserPassword(this.mysqlDB.getDbSettingsConfig().getMasterPassword());
    } catch (AmazonServiceException ase) {
        System.out.println("ERROR : error during MySQLDBSettingsConfig setup.");
        System.out.println("Caught an AmazonServiceException");
        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());
        ase.printStackTrace();
    } catch (AmazonClientException ace) {
        System.out.println("ERROR : error during MySQLDBSettingsConfig setup.");
        System.out.println("Caught an AmazonClientException");
        System.out.println("Error Message: " + ace.getMessage());
        ace.printStackTrace();
    }

}

From source file:com.vb.services.database.rds.MySQLDBUtils.java

private void updateMySQLDBNetworkSecurityConfig() {

    MySQLDBNetworkSecurityConfig mysqlDBNetworkSecurityConfig = new MySQLDBNetworkSecurityConfig();
    this.mysqlDB.setDbNetworkSecurityConfig(mysqlDBNetworkSecurityConfig);

    try {/*  w  w w. ja  v  a 2s  . c  o m*/

    } catch (AmazonServiceException ase) {
        System.out.println("ERROR : error during MySQLDBNetworkSecurityConfig setup.");
        System.out.println("Caught an AmazonServiceException");
        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());
        ase.printStackTrace();
    } catch (AmazonClientException ace) {
        System.out.println("ERROR : error during MySQLDBNetworkSecurityConfig setup.");
        System.out.println("Caught an AmazonClientException");
        System.out.println("Error Message: " + ace.getMessage());
        ace.printStackTrace();
    }
}