List of usage examples for com.amazonaws AmazonServiceException getStatusCode
public int getStatusCode()
From source file:pa3.RemoteClientSQS.java
License:Open Source License
public static void main(String[] args) throws Exception { initSQSandDynamoDB();/* w ww. j a v a2s . com*/ double startTime, endTime, totalTime; // String fileName = // "C:/Cloud/Assignment/LocalQueueAsst3/src/cloud/asst3/queue/10KSleepTasks.txt"; // int noOfThreads = 16 ; // String localOrRemote = "REMOTE"; // String clientOrWorker = "CLIENT"; String fileName = args[4]; String requestQueueName = "MyRequestQueue" + args[2]; String responseQueueName = "MyResponseQueue" + args[2]; String clientOrWorker = args[0]; System.out.println("==========================================="); System.out.println("Lets get started with Amazon SQS"); System.out.println("===========================================\n"); try { // Create a queue System.out.println("Creating a new SQS queue called MyRequestQueue.\n"); CreateQueueRequest createRequestQueue = new CreateQueueRequest(requestQueueName); String myRequestQueueUrl = sqs.createQueue(createRequestQueue).getQueueUrl(); System.out.println("Creating a new SQS queue called MyResponseQueue.\n"); CreateQueueRequest createResponseQueue = new CreateQueueRequest(responseQueueName); String myResponseQueueUrl = sqs.createQueue(createResponseQueue).getQueueUrl(); // List queues System.out.println("Listing all queues in your account.\n"); for (String queueUrl : sqs.listQueues().getQueueUrls()) { System.out.println(" QueueUrl: " + queueUrl); } // Send a message System.out.println("Sending a message to " + requestQueueName); int taskID = 1; FileReader fileReader; BufferedReader bufferedReader = null; startTime = System.nanoTime(); try { fileReader = new FileReader(fileName); bufferedReader = new BufferedReader(fileReader); String eachTaskLine = null; mySubmittedTasks = new ConcurrentHashMap<Integer, String>(); while ((eachTaskLine = bufferedReader.readLine()) != null) { sqs.sendMessage(new SendMessageRequest(myRequestQueueUrl, taskID + " " + eachTaskLine)); mySubmittedTasks.put(taskID, eachTaskLine); taskID++; } bufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Sent all the messages to " + requestQueueName); try { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myResponseQueueUrl); receiveMessageRequest.setVisibilityTimeout(900); receiveMessageRequest.setWaitTimeSeconds(20); while (!mySubmittedTasks.isEmpty()) { List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { if (mySubmittedTasks.containsKey(Integer.parseInt(message.getBody().toString()))) { mySubmittedTasks.remove(Integer.parseInt(message.getBody().toString())); String messageReceiptHandle = message.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myResponseQueueUrl, messageReceiptHandle)); } } } } catch (Exception ex) { ex.printStackTrace(); } if (!mySubmittedTasks.isEmpty()) { System.out.println("Some tasks have failed"); } endTime = System.nanoTime(); totalTime = (endTime - startTime) / 1000000000.0; System.out.println("This is " + clientOrWorker.toUpperCase() + " running with workers."); System.out.println("Total time taken: " + totalTime); System.out.println("Received all the messages from MyResponseQueue.\n"); } 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:pa3.RemoteWorkerSQS.java
License:Open Source License
public static void main(String[] args) throws Exception { initSQSandDynamoDB();/*from w w w .j a v a2 s .c o m*/ try { String tableName = "PA3" + args[2]; // Create table if it does not exist yet if (Tables.doesTableExist(dynamoDB, tableName)) { System.out.println("Table " + tableName + " is already ACTIVE"); } else { // Create a table with a primary hash key named 'name', which // holds a string CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) .withKeySchema(new KeySchemaElement().withAttributeName("taskID").withKeyType(KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition().withAttributeName("taskID") .withAttributeType(ScalarAttributeType.S)) .withProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)); TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest) .getTableDescription(); System.out.println("Created Table: " + createdTableDescription); // Wait for it to become active System.out.println("Waiting for " + tableName + " to become ACTIVE..."); Tables.awaitTableToBecomeActive(dynamoDB, tableName); } String noOfWorkers = args[4]; String requestQueueName = "TaskQueue" + args[2]; String responseQueueName = "TaskResponseQueue" + args[2]; String clientOrWorker = args[0]; // Create a queue //System.out.println("Accessing SQS queue: "+requestQueueName); String myRequestQueueUrl = sqs.createQueue(requestQueueName).getQueueUrl(); //System.out.println("Creating a new SQS queue called MyResponseQueue.\n"); String myResponseQueueUrl = sqs.createQueue(responseQueueName).getQueueUrl(); // Receive the messages try { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myRequestQueueUrl); receiveMessageRequest.setVisibilityTimeout(900); receiveMessageRequest.setWaitTimeSeconds(20); while (true) { List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); // Throw exception when queue gets empty if (messages.isEmpty()) { break; } for (Message message : messages) { try { String[] splitTask = message.getBody().split(" "); //DynamoDB Map<String, AttributeValue> item = newItem(splitTask[0]); PutItemRequest putItemRequest = new PutItemRequest(tableName, item) .withConditionExpression("attribute_not_exists(taskID)"); dynamoDB.putItem(putItemRequest); //System.out.println(splitTask[0]+" : "+splitTask[2]); // Execute Task Thread.sleep(Long.parseLong(splitTask[2])); sqs.sendMessage(new SendMessageRequest(myResponseQueueUrl, splitTask[0])); // Delete the message String messageReceiptHandle = message.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myRequestQueueUrl, messageReceiptHandle)); } catch (ConditionalCheckFailedException e) { //e.printStackTrace(); } } } } catch (Exception ex) { //ex.printStackTrace(); } } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with AWS, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:pagerank.S3Wrapper.java
License:Open Source License
public static void main(String[] args) throws IOException { /*// ww w .j a v a2 s.c o m * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (/home/yupenglu/.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/yupenglu/.aws/credentials), and is in valid format.", e); } AmazonS3 s3 = new AmazonS3Client(credentials); // Region usWest2 = Region.getRegion(Regions.US_WEST_2); // s3.setRegion(usWest2); // String bucketName = "my-first-s3-bucket-" + UUID.randomUUID(); String bucketName = "pages4.27"; String key = "NewKey"; System.out.println("==========================================="); System.out.println("Getting Started with Amazon S3"); System.out.println("===========================================\n"); try { /* * Create a new S3 bucket - Amazon S3 bucket names are globally unique, * so once a bucket name has been taken by any user, you can't create * another bucket with that same name. * * You can optionally specify a location for your bucket if you want to * keep your data closer to your applications or users. */ // System.out.println("Creating bucket " + bucketName + "\n"); // s3.createBucket(bucketName); /* * List the buckets in your account */ System.out.println("Listing buckets"); for (Bucket bucket : s3.listBuckets()) { System.out.println(" - " + bucket.getName()); } System.out.println(); /* * Upload an object to your bucket - You can easily upload a file to * S3, or upload directly an InputStream if you know the length of * the data in the stream. You can also specify your own metadata * when uploading to S3, which allows you set a variety of options * like content-type and content-encoding, plus additional metadata * specific to your applications. */ // System.out.println("Uploading a new object to S3 from a file\n"); // s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile())); /* * Download an object - When you download an object, you get all of * the object's metadata and a stream from which to read the contents. * It's important to read the contents of the stream as quickly as * possibly since the data is streamed directly from Amazon S3 and your * network connection will remain open until you read all the data or * close the input stream. * * GetObjectRequest also supports several other options, including * conditional downloading of objects based on modification times, * ETags, and selectively downloading a range of an object. */ // System.out.println("Downloading an object"); // S3Object object = s3.getObject(new GetObjectRequest(bucketName, key)); // System.out.println("Content-Type: " + object.getObjectMetadata().getContentType()); // displayTextInputStream(object.getObjectContent()); /* * List objects in your bucket by prefix - There are many options for * listing the objects in your bucket. Keep in mind that buckets with * many objects might truncate their results when listing their objects, * so be sure to check if the returned object listing is truncated, and * use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve * additional results. */ System.out.println("Listing objects"); // ObjectListing objectListing = s3.listObjects(new ListObjectsRequest() // .withBucketName(bucketName) // .withPrefix("My")); ObjectListing objectListing = s3.listObjects(new ListObjectsRequest().withBucketName(bucketName)); for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { System.out.println(" - " + URLDecoder.decode(objectSummary.getKey(), "UTF-8") + " " + "(size = " + objectSummary.getSize() + ")"); } S3Object testObj = s3.getObject(bucketName, URLEncoder.encode("http://finance.yahoo.com/investing-news/", "UTF-8")); S3ObjectInputStream inputStream = testObj.getObjectContent(); // System.out.println(streamToString(inputStream)); System.out.println(); /* * Delete an object - Unless versioning has been turned on for your bucket, * there is no way to undelete an object, so use caution when deleting objects. */ // System.out.println("Deleting an object\n"); // s3.deleteObject(bucketName, key); /* * Delete a bucket - A bucket must be completely empty before it can be * deleted, so remember to delete any objects from your buckets before * you try to delete them. */ // System.out.println("Deleting bucket " + bucketName + "\n"); // s3.deleteBucket(bucketName); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon S3, 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 S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:Reference.SimpleQueueServiceSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*/* w w w .j ava 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 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/daniel/.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 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:S3Controller.DownloadingImages.java
public static void main(String[] args) throws IOException { AWSCredentials credentials = null;//from ww w. j a v a 2 s . co m String aws_access_key_id = "PUT_YOUR_aws_access_key_id_HERE"; String aws_secret_access_key = "PUT_YOUR_aws_secret_access_key_HERE"; try { credentials = new BasicAWSCredentials(aws_access_key_id, aws_secret_access_key);//.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); } AmazonS3 s3 = new AmazonS3Client(credentials); Region AP_SOUTHEAST_1 = Region.getRegion(Regions.AP_SOUTHEAST_1); s3.setRegion(AP_SOUTHEAST_1); String bucketName = "PUT_YOUR_S3-BUCKET-NAME_HERE"; String key = "PUT_YOUR_S3-BUCKET-KEY_HERE"; try { ArrayList arr = new ArrayList(); ArrayList EmailArray = new ArrayList(); Bucket bucket = new Bucket(bucketName); ObjectListing objects = s3.listObjects(bucket.getName()); do { for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) { // System.out.println(objectSummary.getKey() + "\t" + // objectSummary.getSize() + "\t" + // StringUtils.fromDate(objectSummary.getLastModified())); arr.add(objectSummary.getKey()); } objects = s3.listNextBatchOfObjects(objects); } while (objects.isTruncated()); KrakenIOExampleMain kraken = new KrakenIOExampleMain(); for (int i = 0; i < arr.size(); i++) { System.out.println("Compressing: " + arr.get(i)); String s = (String) arr.get(i); GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket.getName(), s); System.out.println(s3.generatePresignedUrl(request)); URL Glink = s3.generatePresignedUrl(request); String Dlink = Glink.toString(); System.out.println("Download Link:" + Dlink); kraken.Compression(Dlink, bucketName); System.out.println("Compression completed: " + arr.get(i)); EmailArray.add("Processed Image:" + arr.get(i)); } System.out.println("Start Emailing list"); EmailSender esender = new EmailSender(); esender.EmailVerification(GetNotificationEmail, EmailArray); System.out.println("Kraken compression completed"); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon S3, 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 S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } catch (ExecutionException ex) { Logger.getLogger(DownloadingImages.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(DownloadingImages.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:S3Controller.UploadImages.java
public void UploadToS3(String bucketname, String filename, String filepath) { // public static void main(String[] args) { AWSCredentials credentials = null;/* w w w . j a va 2 s .co m*/ String aws_access_key_id = "PUT_YOUR_aws_access_key_id_HERE"; String aws_secret_access_key = "PUT_YOUR_aws_secret_access_key_HERE"; String bucketName = bucketname; //"zillionbucket"; String fileName = filename; //"javaee_duke_image.jpg"; String localpath = filepath; //"C:\\Users\\Hariom\\Documents\\NetBeansProjects\\JavaApplication9\\src\\ProcessedImages\\javaee_duke_image.jpg"; try { credentials = new BasicAWSCredentials(aws_access_key_id, aws_secret_access_key);//.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); } AmazonS3 s3 = new AmazonS3Client(credentials); Region AP_SOUTHEAST_1 = Region.getRegion(Regions.AP_SOUTHEAST_1); s3.setRegion(AP_SOUTHEAST_1); try { s3.putObject(new PutObjectRequest(bucketName, fileName, new File(localpath)) .withCannedAcl(CannedAccessControlList.PublicRead)); System.out.println("File Uploaded to S3: " + fileName); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon S3, 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 S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:sample.AmazonDynamoDBSample.java
License:Open Source License
public static void main(String[] args) throws Exception { init();/* w w w. j a va 2 s . c om*/ try { String tableName = "my-favorite-movies-table"; // Create a table with a primary hash key named 'name', which holds a string CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name") .withAttributeType(ScalarAttributeType.S)) .withProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)); TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest) .getTableDescription(); System.out.println("Created Table: " + createdTableDescription); // Wait for it to become active waitForTableToBecomeAvailable(tableName); // Describe our new table DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName); TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable(); System.out.println("Table Description: " + tableDescription); // Add an item Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James", "Sara"); PutItemRequest putItemRequest = new PutItemRequest(tableName, item); PutItemResult putItemResult = dynamoDB.putItem(putItemRequest); System.out.println("Result: " + putItemResult); // Add another item item = newItem("Airplane", 1980, "*****", "James", "Billy Bob"); putItemRequest = new PutItemRequest(tableName, item); putItemResult = dynamoDB.putItem(putItemRequest); System.out.println("Result: " + putItemResult); // Scan items for movies with a year attribute greater than 1985 HashMap<String, Condition> scanFilter = new HashMap<String, Condition>(); Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withN("1985")); scanFilter.put("year", condition); ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter); ScanResult scanResult = dynamoDB.scan(scanRequest); System.out.println("Result: " + scanResult); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with AWS, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:scheduler.SpotRequests.java
License:Open Source License
/** * The areOpen method will determine if any of the requests that were started are still * in the open state. If all of them have transitioned to either active, cancelled, or * closed, then this will return false./*from w w w .j a v a 2 s. com*/ * @return */ public boolean areAnyOpen() { //==========================================================================// //============== Describe Spot Instance Requests to determine =============// //==========================================================================// // Create the describeRequest with tall of the request id to monitor (e.g. that we started). DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest(); describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds); System.out.println("Checking to determine if Spot Bids have reached the active state..."); // Initialize variables. instanceIds = new ArrayList<String>(); 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) { //System.out.println(" " +describeResponse.getSpotInstanceRequestId() + // " is in the "+describeResponse.getState() + " state."); // 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. // System.out.println(describeResponse.getState()); if (describeResponse.getState().equals("open")) { // return true; } else { return false; } // Add the instance id to the list we will eventually terminate. instanceIds.add(describeResponse.getInstanceId()); } } catch (AmazonServiceException e) { // Print out the error. System.out.println("Error when calling describeSpotInstances"); 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()); // 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. // return true; return false; } // return false; return true; }
From source file:scheduler.SQSService.java
License:Apache License
public void batchSend(List<SendMessageBatchRequestEntry> entries) { try {/*from w ww . j a va 2 s . co m*/ // Send batch messages //System.out.println("\nSending a message to jobQueue.\n"); SendMessageBatchRequest batchRequest = new SendMessageBatchRequest().withQueueUrl(queueUrl); batchRequest.setEntries(entries); SendMessageBatchResult batchResult = sqs.sendMessageBatch(batchRequest); // sendMessageBatch can return successfully, and yet individual batch // items fail. So, make sure to retry the failed ones. if (!batchResult.getFailed().isEmpty()) { //System.out.println("Retry sending failed messages..."); List<SendMessageBatchRequestEntry> failedEntries = new ArrayList<SendMessageBatchRequestEntry>(); Iterator<SendMessageBatchRequestEntry> iter = entries.iterator(); while (iter.hasNext()) { if (batchResult.getFailed().contains(iter.next())) { failedEntries.add((SendMessageBatchRequestEntry) iter.next()); } } batchRequest.setEntries(failedEntries); sqs.sendMessageBatch(batchRequest); } } 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:se252.jan15.calvinandhobbes.project0.IIScCampusMapGETProxyService.java
License:Open Source License
private static String getCategoryData(String category) { AmazonSQS queueClient = Queues.getQueue(); String resp = null;/*from ww w. j a v a2 s.c o m*/ try { // Send a message queueClient.sendMessage(new SendMessageRequest(Queues.req, category)); // Receive messages Boolean flag = true; while (flag) { ReceiveMessageRequest receiveReq = new ReceiveMessageRequest(Queues.resp); receiveReq.setWaitTimeSeconds(10); List<Message> messages = queueClient.receiveMessage(receiveReq).getMessages(); for (Message message : messages) { String[] strs = message.getBody().split("\\$"); if (strs[0].equals(category)) { flag = false; resp = strs[1]; queueClient .deleteMessage(new DeleteMessageRequest(Queues.resp, message.getReceiptHandle())); break; } } } } 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 resp; }