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:org.hashbang.util.AutoDiscoverQueue.java

License:Open Source License

private static AmazonSQS init() {

    /*/* w  ww .  j  a v  a  2s.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);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);
    return sqs;
}

From source file:org.jooby.internal.aws.CredentialsFactory.java

License:Apache License

private static LinkedList<AWSCredentialsProvider> chain() {
    LinkedList<AWSCredentialsProvider> chain = new LinkedList<>();
    chain.add(new EnvironmentVariableCredentialsProvider());
    chain.add(new SystemPropertiesCredentialsProvider());
    chain.add(new ProfileCredentialsProvider());
    chain.add(new EC2ContainerCredentialsProviderWrapper());
    return chain;
}

From source file:org.juneja.eventdemo.utils.AmazonSimpleQueueService.java

License:Open Source License

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

    /*/*from   w w  w.  j a  v a 2s. 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);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.DEFAULT_REGION);
    sqs.setRegion(usWest2);

    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("TestQueue_EventDriven_2");
        // String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

        GetQueueUrlResult queueResult = sqs.getQueueUrl("TestQueue_EventDriven_2");
        String myQueueUrl = queueResult.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 text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();

        System.out.println("Number of messages : " + messages.size());

        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:org.lambadaframework.wagon.AuthenticationInfoAWSCredentialsProviderChain.java

License:Apache License

AuthenticationInfoAWSCredentialsProviderChain(AuthenticationInfo authenticationInfo) {
    super(new InstanceProfileCredentialsProvider(), new ProfileCredentialsProvider(),
            new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider(),
            new InstanceProfileCredentialsProvider());
}

From source file:org.reswitchboard.utils.s3.access.App.java

License:Open Source License

public static void main(String[] args) {
    try {/*w ww  . j  av  a 2s.  com*/
        if (args.length == 0 || StringUtils.isNullOrEmpty(args[0]))
            throw new IllegalArgumentException("Bucket name can not be empty");

        String bucketName = args[0];
        String prefix = null;
        if (args.length > 1)
            prefix = args[1];

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

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName);

        if (!StringUtils.isNullOrEmpty(prefix))
            listObjectsRequest.setPrefix(prefix);

        ObjectListing objectListing;

        do {
            objectListing = s3client.listObjects(listObjectsRequest);
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                String key = objectSummary.getKey();
                System.out.println(" - " + key);

                for (int nAttempt = 1;; ++nAttempt) {
                    try {

                        AccessControlList acl = s3client.getObjectAcl(bucketName, key);
                        List<Grant> grants = acl.getGrantsAsList();
                        for (Grant grant : grants) {
                            //   System.out.println( "      Grant: " + grant.toString());

                            if (grant.getGrantee().equals(GroupGrantee.AllUsers)) {
                                System.out.println("      Revoking public access");

                                acl.revokeAllPermissions(GroupGrantee.AllUsers);
                                s3client.setObjectAcl(bucketName, key, acl);

                                break;
                            }
                        }

                        break;
                    } catch (Exception e) {
                        System.out.println("Error: " + e.toString());

                        if (nAttempt >= 10) {
                            throw new Exception("Maximum number of invalid attempts has been reeched");
                        }

                        // double back-off delay
                        Thread.sleep((long) (Math.pow(2, nAttempt) * 50));
                    }
                }

            }
            listObjectsRequest.setMarker(objectListing.getNextMarker());
        } while (objectListing.isTruncated());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.smap.notifications.interfaces.EmitDeviceNotification.java

License:Open Source License

public EmitDeviceNotification() {

    // get properties file
    try {/*from   w ww  .  j av a 2  s  . c o  m*/
        properties.load(new FileInputStream("/smap_bin/resources/properties/aws.properties"));
        tableName = properties.getProperty("userDevices_table");
        region = properties.getProperty("userDevices_region");
        platformApplicationArn = properties.getProperty("fieldTask_platform");
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error reading properties", e);
    }

    //create a new DynamoDB client
    dynamoDB = AmazonDynamoDBClient.builder().withRegion(region)
            .withCredentials(new ProfileCredentialsProvider()).build();

    //create a new SNS client
    AmazonSNS sns = AmazonSNSClient.builder().withRegion(region)
            .withCredentials(new ProfileCredentialsProvider()).build();

    // create a wraper
    snsClientWrapper = new AmazonSNSClientWrapper(sns);

}

From source file:org.zalando.stups.fullstop.plugin.example.ExamplePlugin.java

License:Apache License

private AmazonEC2Client getClientForAccount(final String accountId, final Region region) {
    AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(
            new ProfileCredentialsProvider());

    AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
            .withRoleArn("arn:aws:iam::ACCOUNT_ID:role/fullstop-role").withDurationSeconds(3600)
            .withRoleSessionName("fullstop-role");

    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);

    BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(
            assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());

    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(temporaryCredentials);
    amazonEC2Client.setRegion(region);/*from  w  ww.j a  v  a  2  s.  c  om*/

    return amazonEC2Client;
}

From source file:scheduler.SQSService.java

License:Apache License

public SQSService(String queueName) {
    /*//w  w w.  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);
    }

    sqs = new AmazonSQSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usEast1);

    // Create a queue or returns the URL of an existing one
    //System.out.println("Creating a new SQS queue called " + queueName);
    CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
    queueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

}

From source file:twitter.SimpleQueueServiceSample.java

License:Open Source License

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

    /*// w ww .  j a v  a2  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);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usEast1);

    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();
        System.out.println("queueUrl is:" + myQueueUrl);
        // 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");
        String id = "2";
        String tweet = "I am hungry";
        String workRequest = "{" + "  \"id\": \"" + id + "\"," + "  \"tweet\": \"" + tweet + "\"" + "}";
        sqs.sendMessage(new SendMessageRequest().withQueueUrl(myQueueUrl).withMessageBody(workRequest));

        //   sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        //            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        //            List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        Thread.sleep(5000);
        String id2 = "3";
        String t = "yes,it is";
        String workRequest1 = "{" + "  \"id\": \"" + id2 + "\"," + "  \"tweet\": \"" + t + "\"" + "}";
        sqs.sendMessage(new SendMessageRequest().withQueueUrl(myQueueUrl).withMessageBody(workRequest1));
        ReceiveMessageRequest receiveMessageRequest1 = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest1).getMessages();
        System.out.println("!!!!!" + messages.size());

        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:uk.co.keithj.postcodelookup.infrastructure.repository.SpringDataDynamoDBConfigurator.java

License:Apache License

/**
 * The AWS Credentials are retrieved from $USER_HOME/.aws/credentials or
 * from Instance Profile when on AWS./*from  www.  j  a  v  a2  s .  co  m*/
 * 
 * @return the AWS Credentials
 */
@Bean
public AWSCredentials amazonAWSCredentials() {
    if (useProfileCredentials) {
        return new ProfileCredentialsProvider().getCredentials();
    } else {
        return new InstanceProfileCredentialsProvider().getCredentials();
    }
}