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:SimpleQueueServiceMultiThread3.java

License:Open Source License

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

    /*/* ww  w  . j  ava 2s  .com*/
     * 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,clientConfig);
    sqs = new AmazonSQSClient(credentials);

    Region apSouthEast1 = Region.getRegion(Regions.AP_SOUTHEAST_1);
    sqs.setRegion(apSouthEast1);

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

    //Define thread pool size
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);

    //create a list to hold the Future object associated with Callable
    List<Future<Long>> list = new ArrayList<Future<Long>>();

    //Create Callable instance
    Callable<Long> callable = new SimpleQueueServiceMultiThread3();

    for (int i = 0; i < threadSize; i++) {

        //submit Callable tasks to be executed by thread pool
        Future<Long> future = executor.submit(callable);

        //add Future to the list, we can get return value using Future
        list.add(future);

    }

    for (Future<Long> fut : list) {

        try {
            // Future.get() waits for task to get completed
            System.out.println("Time difference : " + fut.get());

            long timeDiff = fut.get().longValue();

            totalTime = Long.valueOf(totalTime + timeDiff);

            if (timeDiff >= maxTime) {
                maxTime = timeDiff;
            }

            if (minTime == 0L && timeDiff >= minTime) {
                minTime = timeDiff;
                //}else if (timeDiff <= minTime && timeDiff != 0L) {
            } else if (timeDiff <= minTime) {
                minTime = timeDiff;
            }

        } catch (InterruptedException | ExecutionException e) {

            e.printStackTrace();

        }
    }

    if (totalTime >= 0L) {

        averageTime = totalTime / threadSize;

    }

    System.out.println("Total Time : " + Long.valueOf(totalTime).toString());
    System.out.println("Max Time : " + Long.valueOf(maxTime).toString());
    System.out.println("Min Time : " + Long.valueOf(minTime).toString());
    System.out.println("Average Time : " + Long.valueOf(averageTime).toString());

    //shut down the executor service now
    executor.shutdown();

}

From source file:SampleKinesisApplication.java

License:Open Source License

private static void configure(String propertiesFile) throws IOException {

    if (propertiesFile != null) {
        loadProperties(propertiesFile);/*from   ww  w. ja v a 2  s .  c  om*/
    }

    // ensure the JVM will refresh the cached IP values of AWS resources (e.g. service endpoints).
    java.security.Security.setProperty("networkaddress.cache.ttl", "60");

    String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID();
    LOG.info("Using workerId: " + workerId);

    // Get credentials from IMDS. If unsuccessful, get them from the credential profiles file.
    AWSCredentialsProvider credentialsProvider = null;
    try {
        credentialsProvider = new InstanceProfileCredentialsProvider();
        // Verify we can fetch credentials from the provider
        credentialsProvider.getCredentials();
        LOG.info("Obtained credentials from the IMDS.");
    } catch (AmazonClientException e) {
        LOG.info("Unable to obtain credentials from the IMDS, trying classpath properties", e);
        credentialsProvider = new ProfileCredentialsProvider();
        // Verify we can fetch credentials from the provider
        credentialsProvider.getCredentials();
        LOG.info("Obtained credentials from the properties file.");
    }

    LOG.info("Using credentials with access key id: "
            + credentialsProvider.getCredentials().getAWSAccessKeyId());

    kinesisClientLibConfiguration = new KinesisClientLibConfiguration(applicationName, streamName,
            credentialsProvider, workerId).withInitialPositionInStream(initialPositionInStream);
}

From source file:awskinesis.AmazonKinesisApplicationSample.java

License:Apache License

private static void init() {
    // Ensure the JVM will refresh the cached IP values of AWS resources (e.g. service endpoints).
    java.security.Security.setProperty("networkaddress.cache.ttl", "60");

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

From source file:awskinesis.AmazonKinesisRecordProducerSample.java

License:Apache License

private static void init() throws Exception {
    /*//w w w  . j a  v a 2  s  .  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);
    }

    kinesis = new AmazonKinesisClient(credentials);
    kinesis.setEndpoint("kinesis.cn-north-1.amazonaws.com.cn");
}

From source file:cloudworker.RemoteWorker.java

License:Apache License

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

    ec2 = new AmazonEC2Client(credentials);
    sqs = new AmazonSQSClient(credentials);

    Region usEast1 = Region.getRegion(Regions.US_EAST_1);

    ec2.setRegion(usEast1);
    sqs.setRegion(usEast1);

    dynamoDB = new DynamoDBService(credentials);

}

From source file:com.amazon.kinesis.streaming.agent.AgentAWSCredentialsProviderChain.java

License:Open Source License

public AgentAWSCredentialsProviderChain(AgentConfiguration config) {
    super(new AgentAWSCredentialsProvider(config), new EnvironmentVariableCredentialsProvider(),
            new SystemPropertiesCredentialsProvider(), new ContainerCredentialsProvider(),
            new ProfileCredentialsProvider(), new InstanceProfileCredentialsProvider());
}

From source file:com.arc.cloud.aws.s3.S3Sample.java

License:Open Source License

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

    /*//from  w w w. jav a  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);
    }

    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.atlassian.localstack.sample.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//from w w  w  .  j av a 2 s .c  o  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);
    }
    runTest(credentials);
}

From source file:com.casadocodigo.ecommerce.infra.AmazonFileSaver.java

public String write(Part part) {

    try {/*from w ww.ja  v a 2s  . c  om*/
        AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());

        String fileName = extractFilename(part.getHeader(CONTENT_DISPOSITION));

        OutputStream out = null;
        InputStream filecontent = null;

        File f = new File(fileName);

        out = new FileOutputStream(f);
        filecontent = part.getInputStream();

        int read;
        final byte[] bytes = new byte[1024];

        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

        s3client.putObject(BUCKET_NAME, fileName, f);

        return "";
    } catch (FileNotFoundException ex) {
        Logger.getLogger(AmazonFileSaver.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | AmazonClientException ex) {
        Logger.getLogger(AmazonFileSaver.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:com.casadocodigo.ecommerce.infra.AmazonFileSaver.java

public String write(String baseFolder, Part multipartFile) throws IOException {

    String fileName = extractFilename(multipartFile.getHeader(CONTENT_DISPOSITION));

    String path = baseFolder + File.separator + fileName;

    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());

    ObjectMetadata metaData = new ObjectMetadata();
    byte[] bytes = IOUtils.toByteArray(multipartFile.getInputStream());
    metaData.setContentLength(bytes.length);
    /*ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, byteArrayInputStream, metadata);
    client.putObject(putObjectRequest);*/

    s3client.putObject(new PutObjectRequest(BUCKET_NAME, path, multipartFile.getInputStream(), metaData)
            .withCannedAcl(CannedAccessControlList.PublicRead));

    /*s3client.putObject(BUCKET_NAME,fileName, 
        multipartFile.getInputStream(), metaData);*/
    return END_POINT + File.separator + BUCKET_NAME + File.separator + path;

}