List of usage examples for com.amazonaws.auth ClasspathPropertiesFileCredentialsProvider ClasspathPropertiesFileCredentialsProvider
public ClasspathPropertiesFileCredentialsProvider()
AwsCredentials.properties
file from the classpath to read AWS security credentials. From source file:SimpleDBExample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*/* w w w. j ava 2 s. 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 */ AmazonSimpleDB sdb = new AmazonSimpleDBClient(new ClasspathPropertiesFileCredentialsProvider()); Region usWest2 = Region.getRegion(Regions.US_WEST_2); sdb.setRegion(usWest2); System.out.println("==========================================="); System.out.println("Getting Started with Amazon SimpleDB"); System.out.println("===========================================\n"); try { // Create a domain String myDomain = "MyStore"; System.out.println("Creating domain called " + myDomain + ".\n"); sdb.createDomain(new CreateDomainRequest(myDomain)); // List domains System.out.println("Listing all domains in your account:\n"); for (String domainName : sdb.listDomains().getDomainNames()) { System.out.println(" " + domainName); } System.out.println(); // Put data into a domain System.out.println("Putting data into " + myDomain + " domain.\n"); sdb.batchPutAttributes(new BatchPutAttributesRequest(myDomain, createSampleData())); // Select data from a domain // Notice the use of backticks around the domain name in our select expression. String selectExpression = "select * from `" + myDomain + "` where Category = 'Clothes'"; System.out.println("Selecting: " + selectExpression + "\n"); SelectRequest selectRequest = new SelectRequest(selectExpression); for (Item item : sdb.select(selectRequest).getItems()) { System.out.println(" Item"); System.out.println(" Name: " + item.getName()); for (Attribute attribute : item.getAttributes()) { System.out.println(" Attribute"); System.out.println(" Name: " + attribute.getName()); System.out.println(" Value: " + attribute.getValue()); } } System.out.println(); // Delete values from an attribute System.out.println("Deleting Blue attributes in Item_O3.\n"); Attribute deleteValueAttribute = new Attribute("Color", "Blue"); sdb.deleteAttributes( new DeleteAttributesRequest(myDomain, "Item_03").withAttributes(deleteValueAttribute)); // Delete an attribute and all of its values System.out.println("Deleting attribute Year in Item_O3.\n"); sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03") .withAttributes(new Attribute().withName("Year"))); // Replace an attribute System.out.println("Replacing Size of Item_03 with Medium.\n"); List<ReplaceableAttribute> replaceableAttributes = new ArrayList<ReplaceableAttribute>(); replaceableAttributes.add(new ReplaceableAttribute("Size", "Medium", true)); sdb.putAttributes(new PutAttributesRequest(myDomain, "Item_03", replaceableAttributes)); // Delete an item and all of its attributes System.out.println("Deleting Item_03.\n"); sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03")); // Delete a domain System.out.println("Deleting " + myDomain + " domain.\n"); sdb.deleteDomain(new DeleteDomainRequest(myDomain)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SimpleDB, 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 SimpleDB, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:SimpleDBWrite.java
License:Open Source License
public static void run(String searchItem) throws Exception { /*/*w w w . ja v a 2 s.c o m*/ * This credentials provider implementation loads your AWS credentials * from a properties file at the root of your classpath. * * Important: Be sure to fill in your AWS access credentials in the * AwsCredentials.properties file before you try to run this * sample. * http://aws.amazon.com/security-credentials */ AmazonSimpleDB sdb = new AmazonSimpleDBClient(new ClasspathPropertiesFileCredentialsProvider()); Region usWest2 = Region.getRegion(Regions.US_WEST_2); sdb.setRegion(usWest2); try { // Create a domain String myDomain = "WanningStore"; sdb.createDomain(new CreateDomainRequest(myDomain)); // List domains // System.out.println("Listing all domains in your account:\n"); // for (String domainName : sdb.listDomains().getDomainNames()) { // System.out.println(" " + domainName); // } // System.out.println(); // Put data into a domain System.out.println("Putting data into " + myDomain + " domain.\n"); sdb.batchPutAttributes(new BatchPutAttributesRequest(myDomain, createData(searchItem))); // // Delete values from an attribute // System.out.println("Deleting Blue attributes in Item_O3.\n"); // Attribute deleteValueAttribute = new Attribute("Color", "Blue"); // sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03") // .withAttributes(deleteValueAttribute)); // Delete an attribute and all of its values // System.out.println("Deleting attribute Year in Item_O3.\n"); // sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03") // .withAttributes(new Attribute().withName("Year"))); // // // Replace an attribute // System.out.println("Replacing Size of Item_03 with Medium.\n"); // List<ReplaceableAttribute> replaceableAttributes = new ArrayList<ReplaceableAttribute>(); // replaceableAttributes.add(new ReplaceableAttribute("Size", "Medium", true)); // sdb.putAttributes(new PutAttributesRequest(myDomain, "Item_03", replaceableAttributes)); // // // Delete an item and all of its attributes // System.out.println("Deleting Item_03.\n"); // sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03")); // // // Delete a domain // System.out.println("Deleting " + myDomain + " domain.\n"); // sdb.deleteDomain(new DeleteDomainRequest(myDomain)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SimpleDB, 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 SimpleDB, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:SimpleQueueService.java
License:Open Source License
public static AmazonSQS push(HashMap<String, Integer> data, String Queuename) throws Exception { /*/*from ww w.java 2s .c o m*/ * This credentials provider implementation loads your AWS credentials * from a properties file at the root of your classpath. * * Important: Be sure to fill in your AWS access credentials in the * AwsCredentials.properties file before you try to run this * sample. * http://aws.amazon.com/security-credentials */ AmazonSQS sqs = new AmazonSQSClient(new ClasspathPropertiesFileCredentialsProvider()); /*Region usWest2 = Region.getRegion(Regions.US_WEST_2); sqs.setRegion(usWest2); */ System.out.println("==========================================="); System.out.println("Getting Started with Amazon SQS"); System.out.println("===========================================\n"); try { // Create a queue String myQueueUrl = null; System.out.println("Creating/ a new SQS queue called " + Queuename); CreateQueueRequest createQueueRequest = new CreateQueueRequest(Queuename); /** * the AWS API, the call to createQueue, shown in Listing 2, * doesn't necessarily create a new queue every time. If the queue already exists, its handle is returned. In SQS, queues are just URLs; consequently, a queue handle is also just a URL. Note that in the AWS SDK API, * the Queue URL is a String type and not the Java URL type * */ myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); QueuePath = myQueueUrl; System.out.println(); // Send a message System.out.println("Sending a message to MyQueue.\n"); sqs.sendMessage(new SendMessageRequest(myQueueUrl, data.toString())); return sqs; } 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()); } return sqs; }
From source file:SimpleQueueService.java
License:Open Source License
public static String show() { // it will view the task Queue messages AmazonSQS sqs = new AmazonSQSClient(new ClasspathPropertiesFileCredentialsProvider()); CreateQueueRequest createQueueRequest = new CreateQueueRequest("taskQueue"); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); String taskQueue = null;//from w w w. j ava 2 s . c om boolean flag = true; while (flag) { List<Message> msgs = sqs .receiveMessage(new ReceiveMessageRequest(myQueueUrl).withMaxNumberOfMessages(1)).getMessages(); System.out.println(msgs.size()); if (msgs.size() > 0) { Message message = msgs.get(0); System.out.println("The message is " + message.getBody()); taskQueue = message.getBody(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, message.getReceiptHandle())); } else { flag = false; // System.out.println("nothing found, trying again in 30 seconds"); } System.out.println(); } System.out.println(taskQueue); return taskQueue; }
From source file:SimpleQueueService.java
License:Open Source License
public static String executeRemoteWorkers(int nOfTaskToExecute) { // gets the task Queue from SQS and read each message and returns the messgae bode AmazonSQS sqs = new AmazonSQSClient(new ClasspathPropertiesFileCredentialsProvider()); CreateQueueRequest createQueueRequest = new CreateQueueRequest("taskQueue"); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); String taskQueue = null;/*from ww w . j av a2 s. c o m*/ Boolean flag = true; //while(flag){ List<Message> msgs = sqs.receiveMessage(new ReceiveMessageRequest(myQueueUrl).withMaxNumberOfMessages(1)) .getMessages(); System.out.println(msgs.size()); if (msgs.size() > 0) { flag = false; Message message = msgs.get(0); System.out.println("The message is " + message.getBody()); taskQueue = message.getBody(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, message.getReceiptHandle())); //RemoteWorkers.ProcessTask(taskQueue); } else { taskQueue = ""; } System.out.println(); //} return taskQueue; }
From source file:SimpleQueueService.java
License:Open Source License
public static int ResultQueue() { // gets the result Queue from SQS and get the messages size and returns the size AmazonSQS sqs = null;/*from ww w . j a va 2s . co m*/ sqs = new AmazonSQSClient(new ClasspathPropertiesFileCredentialsProvider()); CreateQueueRequest createQueueRequest = new CreateQueueRequest("resultQueue"); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); String taskQueue = null; boolean flag = true; while (flag) { List<Message> msgs = sqs.receiveMessage(new ReceiveMessageRequest(myQueueUrl)).getMessages(); System.out.println("Result Queue Size " + msgs.size()); int size = msgs.size(); if (size > 0) { flag = false; return msgs.size(); } else { System.out.println("trying after 10 min"); try { Thread.currentThread().sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return 0; }
From source file:SimpleQueueService.java
License:Open Source License
public static int getNumberOFTasksRunning() { // returns the number of amazon tasks running AmazonSQSClient sqs = new AmazonSQSClient(new ClasspathPropertiesFileCredentialsProvider()); CreateQueueRequest createQueueRequest = new CreateQueueRequest("taskQueue"); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); GetQueueAttributesRequest request = new GetQueueAttributesRequest(); request = request.withAttributeNames("ApproximateNumberOfMessages"); request = request.withQueueUrl(myQueueUrl); Map<String, String> attrs = sqs.getQueueAttributes(request).getAttributes(); // get the approximate number of messages in the queue int sizeOfMessages = Integer.parseInt(attrs.get("ApproximateNumberOfMessages")); System.out.println("sizeOfMessages " + sizeOfMessages); return sizeOfMessages; }
From source file:AmazonKinesisAuditVerify.java
License:Open Source License
private static void configure(String propertiesFile) throws IOException { if (propertiesFile != null) { loadProperties(propertiesFile);//from w w w . j av a2s.co m } // 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 classpath. //AWSCredentialsProvider credentialsProvider = null; try { credentialsProvider = new ProfileCredentialsProvider(); // 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 ClasspathPropertiesFileCredentialsProvider(); // 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:TableCreator.java
License:Open Source License
private static void init() throws Exception { dynamoDB = new AmazonDynamoDBClient(new ClasspathPropertiesFileCredentialsProvider()); Region usEast1 = Region.getRegion(Regions.US_EAST_1); dynamoDB.setRegion(usEast1);/*from w w w .j ava2 s . c o m*/ }
From source file:InlineGettingStartedCodeApp.java
License:Open Source License
/** * @param args//from w ww. jav a2s . c om */ 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 usEast1 = Region.getRegion(Regions.US_EAST_1); ec2.setRegion(usEast1); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); //*************************** Required Parameters Settings ************************// // 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); //*************************** Bid Type Settings ************************// // Set the type of the bid to persistent. requestRequest.setType("persistent"); //*************************** Valid From/To Settings ************************// // Set the valid start time to be two minutes from now. Calendar from = Calendar.getInstance(); from.add(Calendar.MINUTE, 2); requestRequest.setValidFrom(from.getTime()); // Set the valid end time to be two minutes and two hours from now. Calendar until = (Calendar) from.clone(); until.add(Calendar.HOUR, 2); requestRequest.setValidUntil(until.getTime()); //*************************** Launch Group Settings ************************// // Set the launch group. requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP"); //*************************** Availability Zone Group Settings ************************// // Set the availability zone group. requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP"); //*************************** Add the block device mapping ************************// // Goal: Setup block device mappings to ensure that we will not delete // the root partition on termination. // Create the block device mapping to describe the root partition. BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); // Set the delete on termination flag to false. EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setDeleteOnTermination(Boolean.FALSE); blockDeviceMapping.setEbs(ebs); // Add the block device mapping to the block list. ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); // Set the block device mapping configuration in the launch specifications. launchSpecification.setBlockDeviceMappings(blockList); //*************************** Add the availability zone ************************// // Setup the availability zone to use. Note we could retrieve the availability // zones using the ec2.describeAvailabilityZones() API. For this demo we will just use // us-east-1b. SpotPlacement placement = new SpotPlacement("us-east-1b"); launchSpecification.setPlacement(placement); //*************************** Add the placement group ************************// // Setup the placement group to use with whatever name you desire. // For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP". // Note: We have commented this out, because we are not leveraging cc1.4xlarge or // cg1.4xlarge in this example. /* SpotPlacement pg = new SpotPlacement(); pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP"); launchSpecification.setPlacement(pg); */ //*************************** Add the launch specification ************************// // Add the launch specification. 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()); } //============================================================================================// //=========================== 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); //============================================================================================// //====================================== 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()); } }