Guest User

Untitled

a guest
Dec 9th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. package samples.dynamodb;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.nio.ByteBuffer;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8.  
  9. import samples.dynamodb.model.Employee;
  10.  
  11. import com.amazonaws.services.dynamodb.AmazonDynamoDB;
  12. import com.amazonaws.services.dynamodb.datamodeling.DynamoDBMapper;
  13. import com.amazonaws.services.dynamodb.model.AttributeValue;
  14. import com.amazonaws.services.dynamodb.model.PutItemRequest;
  15. import com.amazonaws.services.dynamodb.model.PutItemResult;
  16.  
  17. public class BinaryDataPutSample extends AbstractDynamoDBSample {
  18.  
  19. public static void main(String[] args) {
  20. new BinaryDataPutSample().execute(args);
  21. }
  22.  
  23. @Override
  24. public void execute(String... args) {
  25. AmazonDynamoDB client = createClient();
  26. executeBinaryDataLowLevel(client, args);
  27. executeBinaryDataHighLevel(client, args);
  28. }
  29.  
  30. private void executeBinaryDataLowLevel(AmazonDynamoDB client,
  31. String... args) {
  32. Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
  33. {
  34. item.put("id", new AttributeValue().withN("7"));
  35. item.put("time", new AttributeValue().withN("1331650800000"));
  36. ByteBuffer b = createBody();
  37. item.put("picture", new AttributeValue().withB(b));
  38. }
  39. PutItemRequest putItemRequest = new PutItemRequest().withTableName(
  40. "employee").withItem(item);
  41. PutItemResult result = client.putItem(putItemRequest);
  42. Double consumedCapacityUnits = result.getConsumedCapacityUnits();
  43. System.out.println("put item:" + item + ", consumed units:"
  44. + consumedCapacityUnits);
  45. }
  46.  
  47. private void executeBinaryDataHighLevel(AmazonDynamoDB client,
  48. String... args) {
  49. DynamoDBMapper mapper = new DynamoDBMapper(client);
  50. Employee e = mapper.load(Employee.class, 1007L, 1331821910141L);
  51. e.setPicture(createBodyBytes());
  52. mapper.save(e);
  53. System.out.println("high level:" + e.toString());
  54. }
  55.  
  56. private ByteBuffer createBody() {
  57. byte[] body = createBodyBytes();
  58. ByteBuffer buffer = ByteBuffer.allocate(body.length);
  59. buffer.put(body, 0, body.length);
  60. buffer.position(0);
  61. return buffer;
  62. }
  63.  
  64. private byte[] createBodyBytes() {
  65. try {
  66. File f = new File("C:\\picture.jpg");
  67. FileInputStream fis = new FileInputStream(f);
  68. byte[] body = new byte[(int) f.length()];
  69. fis.read(body);
  70. return body;
  71. } catch (Exception e) {
  72. throw new RuntimeException(e);
  73. }
  74. }
  75.  
  76. }
Add Comment
Please, Sign In to add comment