List of usage examples for com.amazonaws AmazonServiceException getMessage
@Override
public String getMessage()
From source file:com.yahoo.ycsb.db.MailAppDynamoDBClient.java
License:Open Source License
public int query(String table, String hashKey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { logger.debug("query key: " + hashKey + " from table: " + table); Key lastKeyEvaluated = null;/*from ww w .j a v a2 s . c o m*/ do { QueryRequest queryRequest = new QueryRequest().withTableName(table) .withHashKeyValue(new AttributeValue(hashKey)).withExclusiveStartKey(lastKeyEvaluated); if (fields != null) { for (String attrib : fields) { queryRequest.withAttributesToGet(attrib); } } QueryResult res; try { res = dynamoDB.query(queryRequest); } catch (AmazonServiceException ex) { logger.error(ex.getMessage()); return SERVER_ERROR; } catch (AmazonClientException ex) { logger.error(ex.getMessage()); return CLIENT_ERROR; } if (res.getCount() > 0) { for (Map<String, AttributeValue> items : res.getItems()) { result.add(extractResult(items)); } logger.debug("Result: " + res.toString()); } lastKeyEvaluated = res.getLastEvaluatedKey(); } while (lastKeyEvaluated != null); return OK; }
From source file:com.yahoo.ycsb.db.MailAppDynamoDBClient.java
License:Open Source License
@Override public int update(String table, String key, HashMap<String, ByteIterator> values) { if (key.contains(hashAndRangeKeyDelimiter)) { String[] keys = key.split(hashAndRangeKeyDelimiter); String hashKey = keys[0]; String rangeKey = keys[1]; return updateWithHashAndRangeKey(table, hashKey, rangeKey, values); } else {/*from w w w . ja v a 2s .co m*/ logger.debug("updatekey: " + key + " from table: " + table); Map<String, AttributeValueUpdate> attributes = new HashMap<String, AttributeValueUpdate>(values.size()); for (Entry<String, ByteIterator> val : values.entrySet()) { AttributeValue v = new AttributeValue(val.getValue().toString()); //Counter support String stringValue = v.getS(); if (stringValue.startsWith(incrementTag)) { Long incrementValue = Long.valueOf(stringValue.replace(incrementTag, "")); attributes.put(val.getKey(), new AttributeValueUpdate().withAction(AttributeAction.ADD) .withValue(new AttributeValue().withN("+" + incrementValue))); } else if (stringValue.startsWith(decrementTag)) { Long decrementValue = Long.valueOf(stringValue.replace(decrementTag, "")); attributes.put(val.getKey(), new AttributeValueUpdate().withAction(AttributeAction.ADD) .withValue(new AttributeValue().withN("-" + decrementValue))); } else { attributes.put(val.getKey(), new AttributeValueUpdate().withValue(v).withAction("PUT")); } } UpdateItemRequest req = new UpdateItemRequest(table, createPrimaryKey(key), attributes); try { dynamoDB.updateItem(req); } catch (AmazonServiceException ex) { if (debug) ex.printStackTrace(); logger.error(ex.getMessage()); return SERVER_ERROR; } catch (AmazonClientException ex) { if (debug) ex.printStackTrace(); logger.error(ex.getMessage()); return CLIENT_ERROR; } return OK; } }
From source file:com.yahoo.ycsb.db.MailAppDynamoDBClient.java
License:Open Source License
public int updateWithHashAndRangeKey(String table, String hashKey, String rangeKey, HashMap<String, ByteIterator> values) { logger.debug("updatekey: " + hashKey + " rangeKey: " + rangeKey + " from table: " + table); Map<String, AttributeValueUpdate> attributes = new HashMap<String, AttributeValueUpdate>(values.size()); for (Entry<String, ByteIterator> val : values.entrySet()) { AttributeValue v = new AttributeValue(val.getValue().toString()); //Counter support String stringValue = v.getS(); if (stringValue.startsWith(incrementTag)) { Long incrementValue = Long.valueOf(stringValue.replace(incrementTag, "")); attributes.put(val.getKey(), new AttributeValueUpdate().withAction(AttributeAction.ADD) .withValue(new AttributeValue().withN("+" + incrementValue))); } else if (stringValue.startsWith(decrementTag)) { Long decrementValue = Long.valueOf(stringValue.replace(decrementTag, "")); attributes.put(val.getKey(), new AttributeValueUpdate().withAction(AttributeAction.ADD) .withValue(new AttributeValue().withN("-" + decrementValue))); } else {//from w w w . j a v a2 s .c o m attributes.put(val.getKey(), new AttributeValueUpdate().withValue(v).withAction("PUT")); } } Key key = new Key().withHashKeyElement(new AttributeValue(hashKey)) .withRangeKeyElement(new AttributeValue(rangeKey)); UpdateItemRequest req = new UpdateItemRequest().withKey(key).withTableName(table) .withAttributeUpdates(attributes); //System.out.println("updating table "+table+" h+r key: "+key+ "values "+attributes); try { dynamoDB.updateItem(req); } catch (AmazonServiceException ex) { ex.printStackTrace(); logger.error(ex.getMessage()); return SERVER_ERROR; } catch (AmazonClientException ex) { ex.printStackTrace(); logger.error(ex.getMessage()); return CLIENT_ERROR; } return OK; }
From source file:com.yahoo.ycsb.db.MailAppDynamoDBClient.java
License:Open Source License
@Override public int insert(String table, String key, HashMap<String, ByteIterator> values) { if (key.contains(hashAndRangeKeyDelimiter)) { String[] keys = key.split(hashAndRangeKeyDelimiter); String hashKey = keys[0]; String rangeKey = keys[1]; return insertWithHashAndRangeKey(table, hashKey, rangeKey, values); } else {// w w w . ja v a2 s . com logger.debug("insertkey: " + primaryKeyName + "-" + key + " from table: " + table); Map<String, AttributeValue> attributes = createAttributes(values); // adding primary key attributes.put(primaryKeyName, new AttributeValue(key)); PutItemRequest putItemRequest = new PutItemRequest(table, attributes); PutItemResult res = null; try { res = dynamoDB.putItem(putItemRequest); } catch (AmazonServiceException ex) { logger.error(ex.getMessage()); return SERVER_ERROR; } catch (AmazonClientException ex) { logger.error(ex.getMessage()); return CLIENT_ERROR; } return res.getConsumedCapacityUnits().intValue() * -1; } }
From source file:com.yahoo.ycsb.db.MailAppDynamoDBClient.java
License:Open Source License
public int insertWithHashAndRangeKey(String table, String hashKey, String rangeKey, HashMap<String, ByteIterator> values) { logger.debug("insertkey: " + primaryKeyName + "-" + hashKey + " from table: " + table); Map<String, AttributeValue> attributes = createAttributesForHashAndRange(values); // adding primary key attributes.put(primaryKeyName, new AttributeValue().withS(hashKey)); attributes.put(rangeKeyName, new AttributeValue().withS(rangeKey)); // System.out.println("attributes: "+attributes); PutItemRequest putItemRequest = new PutItemRequest().withTableName(table).withItem(attributes); PutItemResult res = null;//from w w w . j ava2 s . c o m try { res = dynamoDB.putItem(putItemRequest); } catch (AmazonServiceException ex) { logger.error(ex.getMessage()); return SERVER_ERROR; } catch (AmazonClientException ex) { logger.error(ex.getMessage()); return CLIENT_ERROR; } return res.getConsumedCapacityUnits().intValue() * -1; }
From source file:com.yahoo.ycsb.db.MailAppDynamoDBClient.java
License:Open Source License
@Override public int delete(String table, String key) { if (key.contains(hashAndRangeKeyDelimiter)) { String[] keys = key.split(hashAndRangeKeyDelimiter); String hashKey = keys[0]; String rangeKey = keys[1]; return deleteWithHashAndRangeKey(table, hashKey, rangeKey); } else {//from ww w . java2 s . c o m logger.debug("deletekey: " + key + " from table: " + table); DeleteItemRequest req = new DeleteItemRequest(table, createPrimaryKey(key)); DeleteItemResult res = null; try { res = dynamoDB.deleteItem(req); } catch (AmazonServiceException ex) { logger.error(ex.getMessage()); return SERVER_ERROR; } catch (AmazonClientException ex) { logger.error(ex.getMessage()); return CLIENT_ERROR; } return res.getConsumedCapacityUnits().intValue() * -1; } }
From source file:com.yahoo.ycsb.db.MailAppDynamoDBClient.java
License:Open Source License
public int deleteWithHashAndRangeKey(String table, String hashKey, String rangeKey) { logger.debug("deletekey: " + hashKey + " rangeKey " + rangeKey + " from table: " + table); ReturnValue returnValues = ReturnValue.ALL_OLD; Key key = new Key().withHashKeyElement(new AttributeValue(hashKey)) .withRangeKeyElement(new AttributeValue(rangeKey)); DeleteItemRequest req = new DeleteItemRequest().withTableName(table).withKey(key) .withReturnValues(returnValues); DeleteItemResult res = null;// w ww .ja va 2 s . co m try { res = dynamoDB.deleteItem(req); } catch (AmazonServiceException ex) { logger.error(ex.getMessage()); return SERVER_ERROR; } catch (AmazonClientException ex) { logger.error(ex.getMessage()); return CLIENT_ERROR; } return res.getConsumedCapacityUnits().intValue() * -1; }
From source file:com.zhang.aws.dynamodb.AmazonDynamoDBSample.java
License:Open Source License
public static void main(String[] args) throws Exception { init();/*from w w w . j a v a2 s . c o m*/ try { String tableName = "my-favorite-movies-table"; // 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("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 System.out.println("Waiting for " + tableName + " to become ACTIVE..."); Tables.waitForTableToBecomeActive(dynamoDB, 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:com.zhang.aws.s3.S3Sample.java
License:Open Source License
public static void main(String[] args) throws IOException { /*/*from www . j a va 2s .c o m*/ * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (~/.aws/credentials). */ ResourceBundle bundle = ResourceBundle.getBundle("credentials"); AWSCredentials credentials = null; try { // credentials = new ProfileCredentialsProvider().getCredentials(); credentials = new BasicAWSCredentials(bundle.getString("aws_access_key_id"), bundle.getString("aws_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 (~/.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 = "elasticbeanstalk-us-west-2-948206320069"; String key = "MyObjectKey2"; 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())); s3.putObject(new PutObjectRequest(bucketName, key, getFileFromDisk())); /*** * * ?url * */ GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key); URL generatePresignedUrl = s3.generatePresignedUrl(urlRequest); System.out.println("public url:" + generatePresignedUrl.toString()); /* * 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")); for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { System.out.println( " - " + objectSummary.getKey() + " " + "(size = " + objectSummary.getSize() + ")"); } 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); System.out.println("------------------------------------------"); } 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:com.zhang.aws.sqs.SimpleQueueServiceSample.java
License:Open Source License
public static void main(String[] args) throws Exception { AWSCredentials credentials = null;//from ww w . j a v a 2 s . c om try { credentials = CredentialsUtil.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); Region usWest2 = Region.getRegion(Regions.AP_SOUTHEAST_1); sqs.setRegion(usWest2); 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()); } }