Example usage for com.amazonaws.auth ClasspathPropertiesFileCredentialsProvider ClasspathPropertiesFileCredentialsProvider

List of usage examples for com.amazonaws.auth ClasspathPropertiesFileCredentialsProvider ClasspathPropertiesFileCredentialsProvider

Introduction

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

Prototype

public ClasspathPropertiesFileCredentialsProvider() 

Source Link

Document

Creates a new ClasspathPropertiesFileCredentialsProvider that will attempt to load the AwsCredentials.properties file from the classpath to read AWS security credentials.

Usage

From source file:InlineTaggingCodeApp.java

License:Open Source License

/**
 * @param args//from   w w w . ja va 2  s . c o m
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    ec2.setRegion(usWest2);

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    // Request 1 x t1.micro instance with a bid price of $0.03.
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-700e4a19");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("ForAssignment2");
    launchSpecification.setSecurityGroups(securityGroups);

    // Add the launch specifications to the request.
    requestRequest.setLaunchSpecification(launchSpecification);

    //============================================================================================//
    //=========================== Getting the Request ID from the Request ========================//
    //============================================================================================//

    // Call the RequestSpotInstance API.
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    //============================================================================================//
    //====================================== Tag the Spot Requests ===============================//
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> requestTags = new ArrayList<Tag>();
    requestTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for requests.
    CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest();
    createTagsRequest_requests.setResources(spotInstanceRequestIds);
    createTagsRequest_requests.setTags(requestTags);

    // Try to tag the Spot request submitted.
    try {
        ec2.createTags(createTagsRequest_requests);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=========================== Determining the State of the Spot Request ======================//
    //============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false ??? which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor.
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    //============================================================================================//
    //====================================== Tag the Spot Instances ===============================//
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> instanceTags = new ArrayList<Tag>();
    instanceTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for instances.
    CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest();
    createTagsRequest_instances.setResources(instanceIds);
    createTagsRequest_instances.setTags(instanceTags);

    // Try to tag the Spot instance started.
    try {
        ec2.createTags(createTagsRequest_instances);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //====================================== Canceling the Request ==============================//
    //============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=================================== Terminating any Instances ==============================//
    //============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:CloudFormation.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*from   w  w  w .  ja  v  a 2  s  .  com*/
     * 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
     */
    AmazonCloudFormation stackbuilder = new AmazonCloudFormationClient(
            new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    stackbuilder.setRegion(usWest2);

    System.out.println("===========================================");
    System.out.println("Getting Started with AWS CloudFormation");
    System.out.println("===========================================\n");

    String stackName = "CloudFormationSampleStack";
    String logicalResourceName = "SampleNotificationTopic";

    try {
        // Create a stack
        CreateStackRequest createRequest = new CreateStackRequest();
        createRequest.setStackName(stackName);
        createRequest.setTemplateBody(
                convertStreamToString(CloudFormation.class.getResourceAsStream("CloudFormation.template")));
        System.out.println("Creating a stack called " + createRequest.getStackName() + ".");
        stackbuilder.createStack(createRequest);

        // Wait for stack to be created
        // Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(stackbuilder, stackName));

        // Show all the stacks for this account along with the resources for each stack
        for (Stack stack : stackbuilder.describeStacks(new DescribeStacksRequest()).getStacks()) {
            System.out.println(
                    "Stack : " + stack.getStackName() + " [" + stack.getStackStatus().toString() + "]");

            DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest();
            stackResourceRequest.setStackName(stack.getStackName());
            for (StackResource resource : stackbuilder.describeStackResources(stackResourceRequest)
                    .getStackResources()) {
                System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                        resource.getLogicalResourceId(), resource.getPhysicalResourceId());
            }
        }

        // Lookup a resource by its logical name
        DescribeStackResourcesRequest logicalNameResourceRequest = new DescribeStackResourcesRequest();
        logicalNameResourceRequest.setStackName(stackName);
        logicalNameResourceRequest.setLogicalResourceId(logicalResourceName);
        System.out.format("Looking up resource name %1$s from stack %2$s\n",
                logicalNameResourceRequest.getLogicalResourceId(), logicalNameResourceRequest.getStackName());
        for (StackResource resource : stackbuilder.describeStackResources(logicalNameResourceRequest)
                .getStackResources()) {
            System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                    resource.getLogicalResourceId(), resource.getPhysicalResourceId());
        }

        // Delete the stack
        DeleteStackRequest deleteRequest = new DeleteStackRequest();
        deleteRequest.setStackName(stackName);
        System.out.println("Deleting the stack called " + deleteRequest.getStackName() + ".");
        stackbuilder.deleteStack(deleteRequest);

        // Wait for stack to be deleted
        // Note that you could used SNS notifications on the original CreateStack call to track the progress of the stack deletion
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(stackbuilder, stackName));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS CloudFormation, 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 CloudFormation, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:AmazonS3Handler.java

License:Open Source License

public AmazonS3Handler() throws IOException {
    /*/*from   www .j a v a 2s.co 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
     */
    s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

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

From source file:CustomCredentialsProviderChain.java

License:Open Source License

public CustomCredentialsProviderChain() {
    super(new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider(),
            new ClasspathPropertiesFileCredentialsProvider(), new InstanceProfileCredentialsProvider());
}

From source file:awslabs.lab21.Lab21.java

License:Open Source License

/**
 * Controls the flow of the lab code execution.
 *//*from   w  w  w  .  jav a 2  s  .c o  m*/
public static void main(String[] args) {
    try {
        String bucketName = labBucketPrefix + UUID.randomUUID().toString().substring(0, 8);
        String testImage = "test-image.png";
        String publicTestImage = "public-test-image.png";
        String testImage2 = "test-image2.png";

        // Create an S3 client
        AmazonS3Client s3Client = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
        s3Client.setRegion(region);

        // Clean up leftovers from previous instances of this lab
        CleanupPreviousLabRuns(s3Client);

        // Create a bucket
        System.out.println("Creating bucket " + bucketName);
        labCode.createBucket(s3Client, bucketName, region);

        // Create an object in the bucket
        File sourceFile = new File(testImage);
        if (sourceFile.exists()) {
            System.out.println("Uploading object: " + testImage);
            labCode.putObject(s3Client, bucketName, testImage, testImage);
            System.out.println("Uploading complete.");
        } else {
            System.out.println("Source file " + testImage + " doesn't exist.");
            return;
        }

        sourceFile = new File(testImage2);
        if (sourceFile.exists()) {
            System.out
                    .println("Uploading another copy of the object (will be made publically available later).");
            labCode.putObject(s3Client, bucketName, testImage2, publicTestImage);
            System.out.println("Uploading complete.");
        } else {
            System.out.println("Source file " + testImage2 + " doesn't exist.");
            return;
        }

        // List objects in the bucket
        System.out.println("Listing items in bucket: " + bucketName);
        labCode.listObjects(s3Client, bucketName);
        System.out.println("Listing complete.");

        // Change the ACL on one of the objects to make it public
        System.out.println("Changing the ACL to make an object public");
        labCode.makeObjectPublic(s3Client, bucketName, publicTestImage);
        System.out.println("Done the object should be publically available now. Test this URL to confirm:");
        System.out.println("  http://" + bucketName + ".s3.amazonaws.com/" + publicTestImage);

        // Generate a pre-signed URL for an object to grant temporary access to the file.
        System.out.println("Generating presigned URL.");
        String presignedUrl = labCode.generatePreSignedUrl(s3Client, bucketName, testImage);
        System.out.println("Done. Test this URL to confirm:");
        System.out.println("  " + presignedUrl);

    } catch (Exception ex) {
        LabUtility.dumpError(ex);
    }

}

From source file:awslabs.lab22.Lab22.java

License:Open Source License

/**
 * Controls the flow of the lab code execution.
 *//*from  w ww .  j a va 2s .c o m*/
public static void main(String[] args) {
    try {
        // Create DynamoDB client and set the region to US East (Virginia)
        AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(
                new ClasspathPropertiesFileCredentialsProvider());
        ddbClient.setRegion(region);

        List<Account> accounts = new ArrayList<Account>();
        accounts.add(new Account().withCompany("Amazon.com").withEmail("johndoe@amazon.com").withFirst("John")
                .withLast("Doe").withAge("33"));
        accounts.add(new Account().withCompany("Asperatus Tech").withEmail("janedoe@amazon.com")
                .withFirst("Jane").withLast("Doe").withAge("24"));
        accounts.add(new Account().withCompany("Amazon.com").withEmail("jimjohnson@amazon.com").withFirst("Jim")
                .withLast("Johnson"));

        // Verify that the table schema is as we expect, and correct any
        // problems we find.
        if (!confirmTableSchema(ddbClient, tableName)) {
            System.out.print("Deleting. ");
            optionalLabCode.deleteTable(ddbClient, tableName);
            System.out.print("Rebuilding. ");
            optionalLabCode.buildTable(ddbClient, tableName);
            System.out.println("Done.");
        }

        System.out.println("Adding items to table.");
        // Create the accounts
        for (Account account : accounts) {
            labCode.createAccountItem(ddbClient, tableName, account);
            System.out.println("Added item: " + account.getCompany() + "/" + account.getEmail());
        }

        System.out.println("Requesting matches for Company == Amazon.com");
        QueryResult queryResult = labCode.lookupByHashKey(ddbClient, tableName, "Amazon.com");
        if (queryResult != null && queryResult.getCount() > 0) {
            // Record was found
            for (Map<String, AttributeValue> item : queryResult.getItems()) {
                System.out.println("Item Found-");

                for (Entry<String, AttributeValue> attribute : item.entrySet()) {
                    System.out.print("    " + attribute.getKey() + ":");
                    if (attribute.getKey().equals("Age")) {
                        System.out.println(attribute.getValue().getN());
                    } else {
                        System.out.println(attribute.getValue().getS());
                    }
                }
            }
        } else {
            System.out.println("No matches found.");
        }

        // Conditionally update a record
        System.out.print("Attempting update. ");
        labCode.updateIfMatch(ddbClient, tableName, "jimjohnson@amazon.com", "Amazon.com", "James", "Jim");
        System.out.println("Done.");
    } catch (Exception ex) {
        LabUtility.dumpError(ex);
    }
}

From source file:awslabs.lab31.Lab31.java

License:Open Source License

public static void main(String[] args) {
    try {//ww w . jav  a2 s .com
        // Create an SQS client
        AmazonSQSClient sqsClient = new AmazonSQSClient(new ClasspathPropertiesFileCredentialsProvider());
        sqsClient.setRegion(region);

        // Create an SNS client
        AmazonSNSClient snsClient = new AmazonSNSClient(new ClasspathPropertiesFileCredentialsProvider());
        snsClient.setRegion(region);

        String queueName = "Notifications";
        String topicName = "ClassroomEvent";

        // Creating the queue will fail if we've just deleted it and are recreating it
        // which is a possibility if you're tracking down a code error. If that happens,
        // pause and retry for up to a minute.
        System.out.println("Creating " + queueName + " queue.");

        Boolean retry = true, notified = false;
        // Create a timeout for 60-seconds from now.
        Date timeout = new Date(System.currentTimeMillis() + 60000L);
        String queueUrl = "";

        while (retry) {
            try {
                queueUrl = labCode.createQueue(sqsClient, queueName);
                retry = false;
            } catch (QueueDeletedRecentlyException ex) {
                if (new Date().before(timeout)) {
                    if (!notified) {
                        System.out.println(
                                "The attempt to recreate the queue failed because the queue was deleted too");
                        System.out.println("recently. Waiting and retrying for up to 1 minute.");
                        notified = true;
                    }
                    // Timeout hasn't expired yet, so wait and retry in 5 seconds.
                    System.out.print(".");
                    Thread.sleep(5000);
                } else {
                    System.out.println("Retry timeout expired. Aborting.");
                    throw ex;
                }
            }

        }
        if (notified) {
            System.out.println("Recovered.");
        }

        System.out.println("URL for new queue: " + queueUrl);

        // List SQS queues
        System.out.println("Getting ARN for " + queueName + " queue.");
        String queueArn = labCode.getQueueArn(sqsClient, queueUrl);
        System.out.println("ARN for queue: " + queueArn);

        // Create an SNS topic and get ARN
        System.out.println("Creating " + topicName + " topic.");
        String topicArn = labCode.createTopic(snsClient, topicName);
        System.out.println("New topic ARN: " + topicArn);

        System.out.println("Granting the notification topic permission to post in the queue.");
        optionalLabCode.grantNotificationPermission(sqsClient, queueArn, queueUrl, topicArn);
        System.out.println("Permission granted.");

        // Create an SNS subscription
        System.out.println("Creating SNS subscription.");
        labCode.createSubscription(snsClient, queueArn, topicArn);
        System.out.println("Subscription created.");

        // Publish message to topic
        String messageText = "This is the SNS topic notification body.";
        String messageSubject = "SNSTopicNotification";

        System.out.println("Publishing SNS topic notification.");
        labCode.publishTopicMessage(snsClient, topicArn, messageSubject, messageText);
        System.out.println("Notification published.");

        // Send a message to the "Notifications" queue
        messageText = "This is the message posted to the queue directly.";
        System.out.println("Posting message to queue directly.");
        labCode.postToQueue(sqsClient, queueUrl, messageText);
        System.out.println("Message posted.");

        // Read message from queue
        System.out.println("Reading messages from queue.");

        List<Message> messages = labCode.readMessages(sqsClient, queueUrl);
        // We expect two messages here
        if (messages.size() < 2) {
            // Try to read again and see if we've picked up the missing message(s).
            messages.addAll(labCode.readMessages(sqsClient, queueUrl));
            if (messages.size() < 2) {
                System.out
                        .println(">>WARNING<< We didn't receive the expected number of messages. Investigate.");
            } else {
                System.out.println();
                System.out.println(
                        "============================================================================");
                System.out
                        .println("PROBLEM: ReadMessages() had to be called twice to collect all the messages.");
                System.out.println("         Did you remember to set the MaxNumberOfMessages property in the ");
                System.out.println("         ReceiveMessageRequest object?");
                System.out.println(
                        "============================================================================");
                System.out.println();

            }
        }
        PrintAndRemoveMessagesInResponse(sqsClient, messages, queueUrl);

        // Locate and delete the SNS subscription
        System.out.println("Removing provisioned resources.");
        labCode.deleteSubscriptions(snsClient, topicArn);
        System.out.println("Subscriptions removed.");

        // Delete the SNS Topic
        labCode.deleteTopic(snsClient, topicArn);
        System.out.println("Topic deleted.");
        // Locate the previously created queue and delete
        labCode.deleteQueue(sqsClient, queueUrl);
        System.out.println("Queue deleted.");
    } catch (Exception ex) {
        LabUtility.dumpError(ex);
    }
}

From source file:com.app.dynamoDb.DynamoFacebookUsers.java

License:Open Source License

public DynamoFacebookUsers() {

    //   credentials = new ProfileCredentialsProvider("default").getCredentials();
    dynamoDB = new AmazonDynamoDBClient(new AWSCredentialsProviderChain(
            new InstanceProfileCredentialsProvider(), new ClasspathPropertiesFileCredentialsProvider()));
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    dynamoDB.setRegion(usWest2);/* w w  w .  j  av a2  s .  c  o m*/
}

From source file:com.app.dynamoDb.DynamoUser.java

License:Open Source License

public DynamoUser() {

    //credentials = new ProfileCredentialsProvider("default").getCredentials();
    dynamoDB = new AmazonDynamoDBClient(new AWSCredentialsProviderChain(
            new InstanceProfileCredentialsProvider(), new ClasspathPropertiesFileCredentialsProvider()));
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    dynamoDB.setRegion(usWest2);//w w  w  .  j ava  2s  .  c o  m
}

From source file:com.aws.credentials.AWSCredentialsProvider.java

License:Open Source License

public AWSCredentialsProvider() {

    super(new ClasspathPropertiesFileCredentialsProvider(), new InstanceProfileCredentialsProvider(),
            new SystemPropertiesCredentialsProvider(), new EnvironmentVariableCredentialsProvider());
}