List of usage examples for com.amazonaws AmazonClientException AmazonClientException
public AmazonClientException(String message, Throwable t)
From source file: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 */// w w w .j av a 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 * (/home/madhurima/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").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 (/home/madhurima/.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:CreateSecurityGroupApp.java
License:Open Source License
public static void main(String[] args) { /*//from w w w .ja va 2 s.c o m * The ProfileCredentialsProvider will return your [New Profile] * credential profile by reading from the credentials file located at * (C:\\Users\\Accolite\\.aws\\credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("New Profile").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 (C:\\Users\\Accolite\\.aws\\credentials), and is in valid format.", e); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); ec2.setRegion(usWest2); // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest("Muneer_SG", "My Security Group"); CreateSecurityGroupResult result = ec2.createSecurityGroup(securityGroupRequest); System.out.println(String.format("Security group created: [%s]", result.getGroupId())); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } String ipAddr = "0.0.0.0/0"; // Get the IP of the current host, so that we can limit the Security Group // by default to the ip range associated with your subnet. try { InetAddress addr = InetAddress.getLocalHost(); // Get IP Address ipAddr = addr.getHostAddress() + "/10"; } catch (UnknownHostException e) { } // Create a range that you would like to populate. List<String> ipRanges = Collections.singletonList(ipAddr); // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic). IpPermission ipPermission = new IpPermission().withIpProtocol("tcp").withFromPort(new Integer(22)) .withToPort(new Integer(22)).withIpRanges(ipRanges); List<IpPermission> ipPermissions = Collections.singletonList(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( "GettingStartedGroup", ipPermissions); ec2.authorizeSecurityGroupIngress(ingressRequest); System.out.println(String.format("Ingress port authroized: [%s]", ipPermissions.toString())); } catch (AmazonServiceException ase) { // Ignore because this likely means the zone has already been authorized. System.out.println(ase.getMessage()); } }
From source file:TweetSQS.java
License:Open Source License
public static void main(String[] args) throws Exception { /*//from w ww. ja v a 2 s . co m * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (). */ AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( TweetSQS.class.getResourceAsStream("AwsCredentials.properties")); } 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 (/Users/aohong/.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(); // 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 first message text.")); // Receive messages System.out.println("Receiving messages from MyQueue.\n"); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); 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 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:RandomQuery1OnDynamoDB.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. * /*from w ww. ja v a 2 s . c o m*/ * @see com.amazonaws.auth.BasicAWSCredentials * @see com.amazonaws.auth.ProfilesConfigFile * @see com.amazonaws.ClientConfiguration */ private static void init() throws Exception { /* * The ProfileCredentialsProvider will return your [default] credential * profile by reading from the credentials file located at * (C:\\Users\\Divendar\\.aws\\credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").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 (C:\\Users\\Divendar\\.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:AmazonSESSample.java
License:Open Source License
public static void main(String[] args) throws IOException { // Construct an object to contain the recipient address. Destination destination = new Destination().withToAddresses(new String[] { TO }); // Create the subject and body of the message. Content subject = new Content().withData(SUBJECT); Content textBody = new Content().withData(BODY); Body body = new Body().withText(textBody); // Create a message with the specified subject and body. Message message = new Message().withSubject(subject).withBody(body); // Assemble the email. SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination) .withMessage(message);//from w w w . j a v a2s.com try { System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java..."); /* * The ProfileCredentialsProvider will return your [haow2] * credential profile by reading from the credentials file located at * (/Users/Dawn/.aws/credentials). * * TransferManager manages a pool of threads, so we create a * single instance and share it throughout our application. */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("haow2").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 (/Users/Dawn/.aws/credentials), and is in valid format.", e); } // Instantiate an Amazon SES client, which will make the service call with the supplied AWS credentials. AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials); // Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your production // access status, sending limits, and Amazon SES identity-related settings are specific to a given // AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using // the US East (N. Virginia) region. Examples of other regions that Amazon SES supports are US_WEST_2 // and EU_WEST_1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html Region REGION = Region.getRegion(Regions.US_EAST_1); client.setRegion(REGION); // Send the email. client.sendEmail(request); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent."); System.out.println("Error message: " + ex.getMessage()); } }
From source file:InlineTaggingCodeSampleApp.java
License:Open Source License
public static void main(String[] args) { //============================================================================================// //=============================== Submitting a Request =======================================// //============================================================================================// /*/*w w w . j a va2 s . c om*/ * The ProfileCredentialsProvider will return your [haow2] * credential profile by reading from the credentials file located at * (/Users/Dawn/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("haow2").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 (/Users/Dawn/.aws/credentials), and is in valid format.", e); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); 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-8c1fece5"); launchSpecification.setInstanceType("t1.micro"); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); 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:SimpleQueueServiceMultiThread2.java
License:Open Source License
public static void main(String[] args) throws Exception { /*// w w w.j av 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); } //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 SimpleQueueServiceMultiThread2(); 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:EbsAttach.java
License:Open Source License
private static void init() throws Exception { /*// www .j a v a2s .co m * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (/Users/Modoka/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( EbsAttach.class.getResourceAsStream("AwsCredentials.properties")); // credentials = new ProfileCredentialsProvider("default").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 (/Users/Modoka/.aws/credentials), and is in valid format.", e); } ec2 = new AmazonEC2Client(credentials); }
From source file:InstallYarn.java
License:Open Source License
public static void main(String[] args) throws JSchException, IOException, InterruptedException { /*// w w w.ja v a 2 s .c o m * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (C:\\Users\\CH\\.aws\\credentials). */ AWSCredentials credentials = null; try { credentials = new BasicAWSCredentials("Your Access Key ID", "Your Secret Access Key"); } 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 (C:\\Users\\CH\\.aws\\credentials), and is in valid format.", e); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); ec2.setRegion(usWest2); /* // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest( "GettingStartedGroup", "Getting Started Security Group"); CreateSecurityGroupResult result = ec2 .createSecurityGroup(securityGroupRequest); System.out.println(String.format("Security group created: [%s]", result.getGroupId())); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } String ipAddr = "0.0.0.0/0"; // Get the IP of the current host, so that we can limit the Security Group // by default to the ip range associated with your subnet. try { InetAddress addr = InetAddress.getLocalHost(); // Get IP Address ipAddr = addr.getHostAddress()+"/10"; } catch (UnknownHostException e) { } // Create a range that you would like to populate. List<String> ipRanges = Collections.singletonList(ipAddr); // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic). IpPermission ipPermission = new IpPermission() .withIpProtocol("tcp") .withFromPort(new Integer(22)) .withToPort(new Integer(22)) .withIpRanges(ipRanges); List<IpPermission> ipPermissions = Collections.singletonList(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( "GettingStartedGroup", ipPermissions); ec2.authorizeSecurityGroupIngress(ingressRequest); System.out.println(String.format("Ingress port authroized: [%s]", ipPermissions.toString())); } catch (AmazonServiceException ase) { // Ignore because this likely means the zone has already been authorized. System.out.println(ase.getMessage()); } */ //CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest() //.withKeyName("CHENHAO"); //CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest); //KeyPair keyPair = new KeyPair(); //keyPair = createKeyPairResult.getKeyPair(); //String privateKey = keyPair.getKeyMaterial(); int cluster_size = Integer .parseInt(JOptionPane.showInputDialog("Enter number of machines you want to set")); String ami_name = JOptionPane.showInputDialog("Enter your ami name"); String key_name = JOptionPane.showInputDialog("Enter your key name"); String s_group_name = JOptionPane.showInputDialog("Enter your security group name"); RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId(ami_name).withInstanceType("t2.micro").withMinCount(cluster_size) .withMaxCount(cluster_size).withKeyName(key_name).withSecurityGroups(s_group_name); RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest); Thread.sleep(10000); Vector<String> instanceId = new Vector<String>(); for (Instance ins : runInstancesResult.getReservation().getInstances()) instanceId.add(ins.getInstanceId()); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(instanceId); DescribeInstancesResult result = ec2.describeInstances(request); List<Reservation> reservations = result.getReservations(); List<Instance> instances_list = new Vector<Instance>(); for (int i = 0; i < reservations.size(); i++) instances_list.addAll(reservations.get(i).getInstances()); System.out.println("Plan cluster size:" + cluster_size + " Real size:" + instances_list.size()); JSch jsch = new JSch(); JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Choose your privatekey"); chooser.setFileHidingEnabled(false); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose " + chooser.getSelectedFile().getAbsolutePath() + "."); jsch.addIdentity(chooser.getSelectedFile().getAbsolutePath()); } Session session; UserInfo ui = new MyUserInfo(); for (int i = 0; i < instances_list.size(); i++) { if (instances_list.get(i).getPublicIpAddress() == null) System.out.println("Error, public ip is null\n"); System.out.println("Connect to:" + instances_list.get(i).getPublicIpAddress() + "\n"); session = jsch.getSession("ubuntu", instances_list.get(i).getPublicIpAddress(), 22); session.setUserInfo(ui); session.connect(); // //if(i==0) //{ // transfer_file_to("/home/ubuntu","C:/Users/CH/Downloads/ch.pem",session); // exec("chmod 400 /home/ubuntu/ch.pem",session); //} //slaves file for (int j = 0; j < instances_list.size(); j++) { if (j != 0) exec("echo " + instances_list.get(j).getPrivateIpAddress() + "\n >> /usr/local/hadoop/etc/hadoop/slaves", session); } //core-site file String command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress() + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml"; exec(command, session); //hdfs-size file command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress() + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml"; exec(command, session); command = "sed -i 's#replication#" + Integer.toString(cluster_size - 1) + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml"; exec(command, session); //yarn-size file command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress() + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml"; exec(command, session); session.disconnect(); } //username and passphrase will be given via UserInfo interface. //slaves file }
From source file:AmazonKinesisApplicationSample.java
License:Open Source 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"); /*//w w w . j a va 2s . c om * The ProfileCredentialsProvider will return your [haow2] * credential profile by reading from the credentials file located at * (/Users/Dawn/.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 (/Users/Dawn/.aws/credentials), and is in valid format.", e); } }