List of usage examples for com.amazonaws.regions Region getRegion
public static Region getRegion(Regions region)
From source file:ScalingClient.java
License:Open Source License
private void loadParams() throws Exception { if (System.getProperty(STREAM_PARAM) == null) { throw new Exception("You must provide a Stream Name"); } else {//from w ww .j a va 2s . c o m this.streamName = System.getProperty(STREAM_PARAM); } this.shardId = System.getProperty(SHARD_ID_PARAM); if (System.getProperty(ACTION_PARAM) == null) { throw new Exception("You must provide a Scaling Action"); } else { this.scalingAction = ScalingAction.valueOf(System.getProperty(ACTION_PARAM)); // ensure the action is one of the supported types for shards if (this.shardId != null && !(this.scalingAction.equals(StreamScaler.ScalingAction.split) || this.scalingAction.equals(StreamScaler.ScalingAction.merge))) { throw new Exception("Can only Split or Merge Shards"); } } if (System.getProperty(REGION_PARAM) != null) { this.region = Region.getRegion(Regions.fromName(System.getProperty(REGION_PARAM))); } if (this.scalingAction != ScalingAction.report) { if (System.getProperty(SCALE_COUNT_PARAM) == null && System.getProperty(SCALE_PCT_PARAM) == null) throw new Exception("You must provide either a scaling Count or Percentage"); if (System.getProperty(SCALE_COUNT_PARAM) != null && System.getProperty(SCALE_PCT_PARAM) != null) throw new Exception("You must provide either a scaling Count or Percentage but not both"); if (this.shardId != null && System.getProperty(SCALE_COUNT_PARAM) == null) { throw new Exception("Shards must be scaled by an absolute number only"); } if (System.getProperty(SCALE_COUNT_PARAM) != null) { this.scaleCount = Integer.parseInt(System.getProperty(SCALE_COUNT_PARAM)); this.scaleBy = StreamScaler.ScaleBy.count; } if (System.getProperty(SCALE_PCT_PARAM) != null) { this.scalePct = Double.parseDouble(System.getProperty(SCALE_PCT_PARAM)); this.scaleBy = StreamScaler.ScaleBy.pct; } if (System.getProperty(MIN_SHARDS_PARAM) != null) { this.minShards = Integer.parseInt(System.getProperty(MIN_SHARDS_PARAM)); } if (System.getProperty(MAX_SHARDS_PARAM) != null) { this.maxShards = Integer.parseInt(System.getProperty(MAX_SHARDS_PARAM)); } } scaler = new StreamScaler(this.region); }
From source file:VideoServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String url = request.getParameter("action"); System.out.println("url" + url); Connection conn = null;/* ww w. j ava 2 s .co m*/ Statement setupStatement; Statement readStatement = null; ResultSet resultSet = null; String results = ""; int numresults = 0; String statement = null; List<Video> result = new ArrayList<>(); try { // Create connection to RDS instance conn = DriverManager.getConnection(jdbcUrl); setupStatement = conn.createStatement(); String retrieveVideoName = "select id from metadata where url like '" + url + "%';"; ResultSet rs = setupStatement.executeQuery(retrieveVideoName); rs.next(); String ids = rs.getString(1); String retrieveUrl = "select url from metadata where id =" + ids + ";"; ResultSet ru = setupStatement.executeQuery(retrieveUrl); ru.next(); String urls = ru.getString(1); System.out.println("este es el id:" + ids); System.out.println("esta es la url:" + urls); String[] urlIdeal = urls.split(".mp4"); String finalUrl = urlIdeal[0] + ".mp4"; System.out.println(finalUrl); AWSCredentials credentials = new PropertiesCredentials( new File("/Users/diana/Desktop/AwsCredentials.properties")); dynamoDBClient = new AmazonDynamoDBClient(new STSSessionCredentialsProvider(credentials)); dynamoDBClient.setRegion(Region.getRegion(Regions.US_WEST_2)); String s = getItem(String.valueOf(ids)); System.out.println(s); String[] textArray = s.split("\\{"); String textFinal = textArray[3]; String[] newTextArray = textFinal.split(",}"); String textFinalFinal = newTextArray[0]; String[] last = textFinalFinal.split("S:"); System.out.println(last[1].trim()); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Mp4Servlet</title>"); out.println(" <script src=\"jquery-1.11.3.min.js\"></script>\n" + " <script type=\"text/javascript\" src=\"../libs/base64.js\"></script>\n" + " <script type=\"text/javascript\" src=\"../libs/sprintf.js\"></script>\n" + " <script type=\"text/javascript\" src=\"../jspdf.js\"></script>"); out.println(" <style type=\"text/css\">\n" + " body {\n" + " padding-top: 20px;\n" + " padding-bottom: 40px;\n" + " }\n" + "\n" + " table{\n" + " display: table;\n" + " border:black 5px solid;\n" + " border-collapse: separate;\n" + " border-spacing: 7px;\n" + " border-color: gray;\n" + " padding:2px;\n" + "\n" + " }\n" + " \n" + " #logo{\n" + " height: 130px;\n" + " width: 728px;\n" + " }\n" + " hr{\n" + " /*border-color:#357EC7;*/\n" + " border-color:#B6B6B4;\n" + " }\n" + "\n" + " /* Custom container */\n" + " .container-narrow {\n" + " margin: 0 auto;\n" + " max-width: 700px;\n" + " }\n" + " .container-narrow > hr {\n" + " margin: 30px 0;\n" + " }\n" + "\n" + " /* Main marketing messages */\n" + " .jumbotron {\n" + " margin: 60px 0;\n" + " text-align: center;\n" + " color: grey;\n" + " }\n" + " .jumbotron h1 {\n" + " font-size: 72px;\n" + " line-height: 1;\n" + "\n" + " }\n" + " .jumbotron .btn {\n" + " font-size: 21px;\n" + " padding: 14px 24px;\n" + " }\n" + "\n" + " /* Supporting marketing content */\n" + " .marketing {\n" + " margin: 60px 0;\n" + " }\n" + " .marketing p + h4 {\n" + " margin-top: 28px;\n" + " }\n" + " \n" + " \n" + " </style>\n" + " \n" + "\n" + "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n" + ""); out.println("</head>"); out.println("<body>"); out.println("<div class=\"container-narrow\">\n" + " <img id = \"logo\" src=\"http://opennebula.org/wp-content/uploads/2015/05/IIT_Logo_stack_186_blk.png\">\n" + " </div>"); out.println("<div class='jumbotron'></div>"); out.println( "<div class='container-narrow'> <video id='idtry' controls preload='auto' width='500' height='200'></div>\n" + "\n" + " \n" + " </video>"); out.println( "<div class='container-narrow'><br><button id ='button' type='button' class='btn btn-primary btn-lg' onclick='getText()'>EDIT</button></div>\n" + " <div>\n" + " <div class='container-narrow'><form id='usrform'><textarea id='text' class = 'container-narrow' name='comment' style='width: 400px; height: 200px;' form='usrform'></textarea>\n" + " <br><button id ='button2' type='button' onclick='submitToDynamo()'>Submit changes</button>\n" + " </form></div>\n" + " </div>"); out.println("<script> \n" + " var textA = " + "\"" + last[1].trim() + "\"" + ";\n" + "\n" + " document.getElementById('usrform').style.visibility = 'hidden';\n" + " \n" + " function getText() {\n" + "\n" + " var t = document.createTextNode(textA);\n" + " document.getElementById('text').appendChild(t);\n" + " document.getElementById('button').style.visibility = 'hidden';\n" + " document.getElementById('usrform').style.visibility = 'visible';\n" + "\n" + " }"); out.println(" var x;\n" + " function submitToDynamo() {\n" + " \n" + " document.getElementById('usrform').style.visibility = 'hidden';\n" + " document.getElementById('button').style.visibility = 'visible';\n" + " x = document.getElementById('text').value;\n" + " download(f,x);\n" + " }\n" + " "); out.println(" function download(filename, text) {\n" + " var pom = document.createElement('a');\n" + " pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));\n" + " pom.setAttribute('download', filename);\n" + "\n" + " if (document.createEvent) {\n" + " var event = document.createEvent('MouseEvents');\n" + " event.initEvent('click', true, true);\n" + " pom.dispatchEvent(event);\n" + " }\n" + " else {\n" + " pom.click();\n" + " }\n" + "}\n" + " \n" + " \n" + "var f = '/Users/diana/Desktop/texto.txt';"); out.println("var code = '<source src=\"" + finalUrl + "\" type=\"video/mp4\" />';\n" + " document.getElementById(\"idtry\").innerHTML=code;"); out.println("</script>"); out.println("<div>"); out.println("</div><br>"); out.println("<a href='http://localhost:8080/studentUI/Uiservlet'>BACK TO LIST </a>"); out.println("</body>"); out.println("</html>"); } } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } finally { System.out.println("Closing the connection."); if (conn != null) try { conn.close(); } catch (SQLException ignore) { } } }
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 *//*from ww w .j a v a 2s . c om*/ 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 ww . j a va 2s. c om*/ * 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 ww w . j a va 2s . c om*/ * 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. * /*ww w . j a 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:InlineGettingStartedCodeApp.java
License:Open Source License
/** * @param args//w w w . j a v a 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 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()); } }
From source file:AWS.java
/** * Creates new form main// w w w . j av a 2 s . co m */ public AWS() { AWSCredentials credentials = new ProfileCredentialsProvider().getCredentials(); String endPoint; Region region; endPoint = "https://ec2.eu-west-1.amazonaws.com"; region = Region.getRegion(Regions.EU_WEST_1); ec2client = new AmazonEC2Client(credentials); ec2client.setEndpoint(endPoint); ec2client.setRegion(region); initComponents(); }
From source file:InlineTaggingCodeApp.java
License:Open Source License
/** * @param args//from w ww.java2 s . 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 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: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 www . j a v a 2 s. c o m 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()); } }