Example usage for com.amazonaws.auth.profile ProfileCredentialsProvider ProfileCredentialsProvider

List of usage examples for com.amazonaws.auth.profile ProfileCredentialsProvider ProfileCredentialsProvider

Introduction

In this page you can find the example usage for com.amazonaws.auth.profile ProfileCredentialsProvider ProfileCredentialsProvider.

Prototype

public ProfileCredentialsProvider() 

Source Link

Document

Creates a new profile credentials provider that returns the AWS security credentials configured for the default profile.

Usage

From source file:com.hussi.aws.dynamoDB.AmazonDynamoDBSample.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials
 * consisting of the AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints, are performed
 * automatically. Client parameters, such as proxies, can be specified in an
 * optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.ProfilesConfigFile
 * @see com.amazonaws.ClientConfiguration
 *//*from   w ww.  ja v a  2s.  co m*/
private static void init() throws Exception {
    /*
     * 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();
        System.out.println("credentials.getAWSAccessKeyId()===>>>" + credentials.getAWSAccessKeyId());
        System.out.println("credentials.getAWSSecretKey()===>>>" + credentials.getAWSSecretKey());
        //System.exi   t(0);

    } 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);
    }
    dynamoDB = new AmazonDynamoDBClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    dynamoDB.setRegion(usWest2);
}

From source file:com.imos.sample.SampleS3.java

public static void main(String[] args) throws IOException {
    AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
    S3Object object = s3Client.getObject(new GetObjectRequest("inv.adminconsole.test", ""));
    InputStream objectData = object.getObjectContent();
    // Process the objectData stream.
    objectData.close();//from  w  w w  .j a v  a2  s.c om
}

From source file:com.intrinsicMetric.aws.AwsConsoleApp.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials
 * consisting of the AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints, are performed
 * automatically. Client parameters, such as proxies, can be specified in an
 * optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 */// w  w w. j  a va 2 s  .  c  o  m
private static void init() throws Exception {

    /*
     * 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);
    }
    ec2 = new AmazonEC2Client(credentials);
    s3 = new AmazonS3Client(credentials);
    sdb = new AmazonSimpleDBClient(credentials);
}

From source file:com.kirana.utils.GeneratePresignedUrlAndUploadObject.java

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

    System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
    System.setProperty(SDKGlobalConfiguration.ACCESS_KEY_ENV_VAR, "AKIAJ666LALJZHA6THGQ");
    System.setProperty(SDKGlobalConfiguration.SECRET_KEY_ENV_VAR, "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");
    //      AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider("kirana"));

    ProfilesConfigFile profile = new ProfilesConfigFile("AwsCredentials.properties");
    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
    s3client.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));

    try {/* www.  j a v a 2 s.c o  m*/
        System.out.println("Generating pre-signed URL.");
        java.util.Date expiration = new java.util.Date();
        long milliSeconds = expiration.getTime();
        milliSeconds += 1000 * 60 * 60; // Add 1 hour.
        expiration.setTime(milliSeconds);

        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName,
                objectKey);
        generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
        generatePresignedUrlRequest.setExpiration(expiration);

        //                        s3client.putObject(bucketName, objectKey, null);

        URL url = s3client.generatePresignedUrl(generatePresignedUrlRequest);
        UploadObject(url);

        System.out.println("Pre-Signed URL = " + url.toString());
    } catch (AmazonServiceException exception) {
        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: " + exception.getMessage());
        System.out.println("HTTP  Code: " + exception.getStatusCode());
        System.out.println("AWS Error Code:" + exception.getErrorCode());
        System.out.println("Error Type:    " + exception.getErrorType());
        System.out.println("Request ID:    " + exception.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("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.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.mateusz.mateuszsqs.SQSprocessor.java

public static void main(String[] args) throws AmazonClientException {
    System.out.println("Start process SQS");
    try {//from w  ww .  j av  a 2 s .  c  o  m
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        System.out.println("Error");
        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);
    }

    final Thread mainThread = new Thread(() -> {
        while (!Thread.currentThread().isInterrupted()) {
            AmazonSQS sqs = new AmazonSQSClient(credentials);
            Region usWest2 = Region.getRegion(Regions.US_WEST_2);
            sqs.setRegion(usWest2);

            AmazonS3 s3 = new AmazonS3Client(credentials);
            s3.setRegion(usWest2);

            List<String> filesList = SQSConfig.getMessages(sqs, sqsURL);

            for (String file : filesList) {
                String[] files = file.split(",");
                if (!file.equals("missing parameter: fileNames"))
                    for (int i = 0; i < files.length; i++) {
                        try {
                            SQSConfig.processFile(files[i], s3, bucketName);
                        } catch (IOException e) {
                            System.out.println("Error");
                            e.printStackTrace();
                        }
                    }

            }
            System.out.println("\nWaiting for messages.........\n");
        }
    });
    mainThread.start();
}

From source file:com.nike.cerberus.module.CerberusModule.java

License:Apache License

private static <M extends AmazonWebServiceClient> M createAmazonClientInstance(Class<M> clientClass,
        Region region) {/*from w  ww  .  j a  va 2 s  .c om*/
    String cerberusRoleToAssume = System.getenv(CERBERUS_ASSUME_ROLE_ARN) != null
            ? System.getenv(CERBERUS_ASSUME_ROLE_ARN)
            : "";
    String cerberusRoleToAssumeExternalId = System.getenv(CERBERUS_ASSUME_ROLE_EXTERNAL_ID) != null
            ? System.getenv(CERBERUS_ASSUME_ROLE_EXTERNAL_ID)
            : "";

    STSAssumeRoleSessionCredentialsProvider sTSAssumeRoleSessionCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(
            cerberusRoleToAssume, UUID.randomUUID().toString()).withExternalId(cerberusRoleToAssumeExternalId)
                    .build();

    AWSCredentialsProviderChain chain = new AWSCredentialsProviderChain(
            new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider(),
            new ProfileCredentialsProvider(), sTSAssumeRoleSessionCredentialsProvider,
            new InstanceProfileCredentialsProvider());
    return region.createClient(clientClass, chain, new ClientConfiguration());
}

From source file:com.razorfish.fluent.contentintelligence.core.servlets.SmartCropServlet.java

License:Apache License

@Override
protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    String[] selectors = request.getRequestPathInfo().getSelectors();

    int sizeX = Integer.parseInt(selectors[0]);
    int sizeY = Integer.parseInt(selectors[1]);
    String extension = request.getRequestPathInfo().getExtension();
    String imagePath = request.getRequestPathInfo().getResourcePath().substring(0,
            request.getRequestPathInfo().getResourcePath().indexOf("."));

    log.info("received" + Arrays.toString(selectors) + " : " + extension + " : " + imagePath);

    String type = getImageType(extension);
    if (type == null) {
        response.sendError(404, "Image type not supported");
        return;/*from www  . ja  va2s  .  c om*/
    }
    response.setContentType(type);

    ImageContext context = new ImageContext(request, type);

    Resource resource = context.request.getResourceResolver().getResource(imagePath + "." + extension);
    Asset asset = resource.adaptTo(Asset.class);

    log.info("asset : " + asset.getPath());

    log.info("resource : " + resource.getPath() + "type " + resource.getResourceType());
    Image image = new Image(resource);

    float x1 = 0, y1 = 0, x2 = 1, y2 = 1;

    if (isAsset(resource) || isRendition(resource)) {
        image.setFileReference(image.getPath());
        Rendition r = null;
        if (isAsset(resource)) {
            r = DamUtil.resolveToAsset(resource).getOriginal();
        } else {
            r = resource.adaptTo(Rendition.class);
        }
        byte[] data = new byte[(int) r.getSize()];

        int numbytesread = r.getStream().read(data);
        log.debug("Read : {} of {}", numbytesread, r.getSize());
        DetectFacesRequest dfrequest = new DetectFacesRequest()
                .withImage(
                        new com.amazonaws.services.rekognition.model.Image().withBytes(ByteBuffer.wrap(data)))
                .withAttributes(Attribute.ALL);

        AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(
                new ProfileCredentialsProvider().getCredentials());
        rekognitionClient.setSignerRegionOverride("us-east-1");

        DetectFacesResult result = rekognitionClient.detectFaces(dfrequest);

        List<FaceDetail> faceDetails = result.getFaceDetails();
        if (!faceDetails.isEmpty()) {
            log.info("result " + Arrays.toString(faceDetails.toArray()));
            x1 = faceDetails.get(0).getBoundingBox().getLeft();
            y1 = faceDetails.get(0).getBoundingBox().getTop();
            x2 = x1 + faceDetails.get(0).getBoundingBox().getWidth();
            y2 = y1 + faceDetails.get(0).getBoundingBox().getHeight();

        }
    }

    if (!image.hasContent()) {
        response.sendError(404);
        return;
    }

    Layer layer;
    try {
        log.info("image : " + image.getMimeType());
        layer = image.getLayer(true, false, true);
        int ratioY = layer.getHeight();
        int ratioX = layer.getWidth();

        if (sizeX > ratioX) {
            sizeX = ratioX;
        }

        if (sizeY > ratioY) {
            sizeY = ratioY;
        }

        log.info("baseline : " + sizeX + "," + sizeY);
        x1 = (int) Math.ceil(x1 * ratioX);
        y1 = (int) Math.ceil(y1 * ratioY);
        x2 = (int) Math.ceil(x2 * ratioX);
        y2 = (int) Math.ceil(y2 * ratioY);

        log.info("detected : " + (int) x1 + "," + (int) y1 + "," + (int) x2 + "," + (int) y2);
        log.info("calculated : " + (int) (x2 - x1) + "," + (int) (y2 - y1));

        // check if the crop target is bigger than bounding box, if so crop at a larger size
        if ((x2 - x1) < sizeX) {
            x1 = x1 - ((sizeX - (x2 - x1)) / 2);
            x2 = x2 + ((sizeX - (x2 - x1)) / 2);
            log.info("x adj : " + (int) x1 + "," + (int) y1 + "," + (int) x2 + "," + (int) y2);
            log.info("x adj : " + (int) (x2 - x1) + "," + (int) (y2 - y1));
        }

        if ((y2 - y1) < sizeY) {
            y1 = y1 - ((sizeY - (y2 - y1)) / 2);
            y2 = y2 + ((sizeY - (y2 - y1)) / 2);

            log.info("y adj : " + (int) x1 + "," + (int) y1 + "," + (int) x2 + "," + (int) y2);
            log.info("y adj : " + (int) (x2 - x1) + "," + (int) (y2 - y1));
        }

        //ensure we are still within the image boundaries   
        if (x1 < 0) {
            x2 = x2 - x1;
            x1 = 0;
        }
        if (y1 < 0) {
            y2 = y2 - y1;
            y1 = 0;
        }
        if (x2 > ratioX) {
            x1 = x1 - (x2 - ratioX);
            x2 = ratioX;
        }
        if (y2 > ratioY) {
            y1 = y1 - (y2 - ratioY);
            y2 = ratioY;
        }

        //TODO - handle negative values for bounding box - http://docs.aws.amazon.com/rekognition/latest/dg/API_BoundingBox.html
        log.info("resolved : " + (int) x1 + "," + (int) y1 + "," + (int) x2 + "," + (int) y2);
        layer.crop(ImageHelper.getCropRect((int) x1 + "," + (int) y1 + "," + (int) x2 + "," + (int) y2,
                image.getPath()));

        //after cropping the face, resize to the target size if needed
        layer.resize(sizeX, sizeY);
        //layer.crop(ImageHelper.getCropRect("225,121,525,421", image.getPath()));

        double quality = image.getMimeType().equals("image/gif") ? 255 : 1.0;
        layer.write(image.getMimeType(), quality, response.getOutputStream());
    } catch (RepositoryException e) {
        log.error("Could not create layer" + e);
        e.printStackTrace();
    }

    response.flushBuffer();
}

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

License:Open Source License

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

    /*/*from w  w w . ja va  2s. c om*/
     * 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.springboot.demo.framework.aws.s3.S3Sample.java

License:Open Source License

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

    /*/*from  w  w  w .j a  va  2s  . c o  m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials basicCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);

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

    /*
     * Create S3 Client
     */
    AmazonS3 s3 = AmazonS3ClientBuilder.defaultClient();
    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()));

        /*
         * Returns an URL for the object stored in the specified bucket and  key
         */
        URL url = s3.getUrl(bucketName, key);
        System.out.println("upload file url : " + url.toString());

        /*
         * 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.zhang.aws.dynamodb.AmazonDynamoDBSample.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials
 * consisting of the AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints, are performed
 * automatically. Client parameters, such as proxies, can be specified in an
 * optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.ProfilesConfigFile
 * @see com.amazonaws.ClientConfiguration
 *///from  w w  w  .j  a v  a 2s .co  m
private static void init() throws Exception {
    /*
     * 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);
    }
    dynamoDB = new AmazonDynamoDBClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    dynamoDB.setRegion(usWest2);
}