Java Code Examples for com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#load()

The following examples show how to use com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#load() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ObjectPersistenceCRUDExample.java    From aws-dynamodb-examples with Apache License 2.0 7 votes vote down vote up
private static void testCRUDOperations() {

        CatalogItem item = new CatalogItem();
        item.setId(601);
        item.setTitle("Book 601");
        item.setISBN("611-1111111111");
        item.setBookAuthors(new HashSet<String>(Arrays.asList("Author1", "Author2")));
        
        // Save the item (book).
        DynamoDBMapper mapper = new DynamoDBMapper(client);
        mapper.save(item);
        
        // Retrieve the item.
        CatalogItem itemRetrieved = mapper.load(CatalogItem.class, 601);
        System.out.println("Item retrieved:");
        System.out.println(itemRetrieved);

        // Update the item.
        itemRetrieved.setISBN("622-2222222222");
        itemRetrieved.setBookAuthors(new HashSet<String>(Arrays.asList("Author1", "Author3")));
        mapper.save(itemRetrieved);
        System.out.println("Item updated:");
        System.out.println(itemRetrieved);
        
        // Retrieve the updated item.
        DynamoDBMapperConfig config = new DynamoDBMapperConfig(DynamoDBMapperConfig.ConsistentReads.CONSISTENT);
        CatalogItem updatedItem = mapper.load(CatalogItem.class, 601, config);
        System.out.println("Retrieved the previously updated item:");
        System.out.println(updatedItem);
        
        // Delete the item.
        mapper.delete(updatedItem);
        
        // Try to retrieve deleted item.
        CatalogItem deletedItem = mapper.load(CatalogItem.class, updatedItem.getId(), config);
        if (deletedItem == null) {
            System.out.println("Done - Sample item is deleted.");
        }
    }
 
Example 2
Source File: AutoGeneratedKeysITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testHashKeyRangeKeyBothAutogenerated() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    HashKeyRangeKeyBothAutoGenerated obj = new HashKeyRangeKeyBothAutoGenerated();
    obj.setOtherAttribute("blah");

    assertNull(obj.getKey());
    assertNull(obj.getRangeKey());
    mapper.save(obj);
    assertNotNull(obj.getKey());
    assertNotNull(obj.getRangeKey());

    HashKeyRangeKeyBothAutoGenerated other = mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj.getKey(),
            obj.getRangeKey());
    assertEquals(other, obj);
}
 
Example 3
Source File: NumericSetAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoad() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    for ( Map<String, AttributeValue> attr : attrs ) {
        NumberSetAttributeTestClass x = util.load(NumberSetAttributeTestClass.class, attr.get(KEY_NAME).getS());
        assertEquals(x.getKey(), attr.get(KEY_NAME).getS());
        
        // Convert all numbers to the most inclusive type for easy comparison
        assertNumericSetsEquals(x.getBigDecimalAttribute(), attr.get(BIG_DECIMAL_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getBigIntegerAttribute(), attr.get(BIG_INTEGER_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getFloatObjectAttribute(), attr.get(FLOAT_OBJECT_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getDoubleObjectAttribute(), attr.get(DOUBLE_OBJECT_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getIntegerAttribute(), attr.get(INTEGER_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getLongObjectAttribute(), attr.get(LONG_OBJECT_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getByteObjectAttribute(), attr.get(BYTE_OBJECT_ATTRIBUTE).getNS());
        assertSetsEqual(toSet("0", "1"), attr.get(BOOLEAN_ATTRIBUTE).getNS());
    }
}
 
Example 4
Source File: ComplexTypeITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests using a complex type for a (string) key
 */
@Test
public void testComplexKey() throws Exception {
    ComplexKey obj = new ComplexKey();
    ComplexNestedType key = new ComplexNestedType();
    key.setIntValue(start++);
    key.setStringValue("" + start++);
    obj.setKey(key);
    obj.setOtherAttribute("" + start++);
    
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    mapper.save(obj);
    ComplexKey loaded = mapper.load(ComplexKey.class, obj.getKey());
    assertEquals(obj, loaded);       
}
 
Example 5
Source File: BinaryAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoad() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    for ( Map<String, AttributeValue> attr : attrs ) {
    	// test BinaryAttributeClass
        BinaryAttributeByteBufferTestClass x = util.load(BinaryAttributeByteBufferTestClass.class, attr.get(KEY_NAME).getS());
        assertEquals(x.getKey(), attr.get(KEY_NAME).getS());
        assertEquals(x.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength)));
        assertTrue(x.getBinarySetAttribute().contains(ByteBuffer.wrap(generateByteArray(contentLength))));
        assertTrue(x.getBinarySetAttribute().contains(ByteBuffer.wrap(generateByteArray(contentLength + 1))));

        // test BinaryAttributeByteArrayTestClass
        BinaryAttributeByteArrayTestClass y = util.load(BinaryAttributeByteArrayTestClass.class, attr.get(KEY_NAME).getS());
        assertEquals(y.getKey(), attr.get(KEY_NAME).getS());
        assertTrue(Arrays.equals(y.getBinaryAttribute(), (generateByteArray(contentLength))));
        assertTrue(2 == y.getBinarySetAttribute().size());
        assertTrue(setContainsBytes(y.getBinarySetAttribute(), generateByteArray(contentLength)));
        assertTrue(setContainsBytes(y.getBinarySetAttribute(), generateByteArray(contentLength+1)));
    }

}
 
Example 6
Source File: AutoGeneratedKeysITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testNothingAutogeneratedKeyOnly() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    NothingAutoGeneratedKeyOnly obj = new NothingAutoGeneratedKeyOnly();
    obj.setKey("" + System.currentTimeMillis());
    obj.setRangeKey("" + System.currentTimeMillis());

    assertNotNull(obj.getKey());
    assertNotNull(obj.getRangeKey());
    mapper.save(obj);
    assertNotNull(obj.getKey());
    assertNotNull(obj.getRangeKey());

    NothingAutoGeneratedKeyOnly other = mapper.load(NothingAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey());
    assertEquals(other, obj);
}
 
Example 7
Source File: ExceptionHandlingITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = DynamoDBMappingException.class)
public void testWrongDataType2() {
    Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>();
    attr.put("integerProperty", new AttributeValue().withNS("1", "2", "3"));
    attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++));
    dynamo.putItem(new PutItemRequest().withTableName(TABLE_NAME).withItem(attr));
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.load(NumericFields.class, attr.get(KEY_NAME).getS());
}
 
Example 8
Source File: SimpleNumericAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoad() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    for ( Map<String, AttributeValue> attr : attrs ) {
        NumberAttributeTestClass x = util.load(getKeyObject(attr.get(KEY_NAME).getS()));
        assertEquals(x.getKey(), attr.get(KEY_NAME).getS());
        
        // Convert all numbers to the most inclusive type for easy comparison
        assertEquals(x.getBigDecimalAttribute(), new BigDecimal(attr.get(BIG_DECIMAL_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getBigIntegerAttribute()), new BigDecimal(attr.get(BIG_INTEGER_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getFloatAttribute()), new BigDecimal(attr.get(FLOAT_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getFloatObjectAttribute()), new BigDecimal(attr.get(FLOAT_OBJECT_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getDoubleAttribute()), new BigDecimal(attr.get(DOUBLE_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getDoubleObjectAttribute()), new BigDecimal(attr.get(DOUBLE_OBJECT_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getIntAttribute()), new BigDecimal(attr.get(INT_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getIntegerAttribute()), new BigDecimal(attr.get(INTEGER_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getLongAttribute()), new BigDecimal(attr.get(LONG_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getLongObjectAttribute()), new BigDecimal(attr.get(LONG_OBJECT_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getByteAttribute()), new BigDecimal(attr.get(BYTE_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getByteObjectAttribute()), new BigDecimal(attr.get(BYTE_OBJECT_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getShortAttribute()), new BigDecimal(attr.get(SHORT_ATTRIBUTE).getN()));
        assertEquals(new BigDecimal(x.getShortObjectAttribute()), new BigDecimal(attr.get(SHORT_OBJECT_ATTRIBUTE).getN()));
        assertEquals(x.isBooleanAttribute(), attr.get(BOOLEAN_ATTRIBUTE).getN().equals("1"));
        assertEquals((Object) x.getBooleanObjectAttribute(), (Object) attr.get(BOOLEAN_OBJECT_ATTRIBUTE).getN().equals("1"));
    }
    
    // Test loading an object that doesn't exist
    assertNull(util.load(getKeyObject("does not exist")));
}
 
Example 9
Source File: ObjectPersistenceBatchWriteExample.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
private static void testBatchDelete(DynamoDBMapper mapper) {
    
    Book book1 = mapper.load(Book.class, 901);
    Book book2 = mapper.load(Book.class, 902);
    System.out.println("Deleting two books from the ProductCatalog table.");
    mapper.batchDelete(Arrays.asList(book1, book2));
}
 
Example 10
Source File: AutoGeneratedKeysITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testHashKeyRangeKeyBothAutogeneratedKeyOnly() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    HashKeyRangeKeyBothAutoGeneratedKeyOnly obj = new HashKeyRangeKeyBothAutoGeneratedKeyOnly();

    assertNull(obj.getKey());
    assertNull(obj.getRangeKey());
    mapper.save(obj);
    assertNotNull(obj.getKey());
    assertNotNull(obj.getRangeKey());

    HashKeyRangeKeyBothAutoGeneratedKeyOnly other = mapper.load(HashKeyRangeKeyBothAutoGeneratedKeyOnly.class, obj.getKey(),
            obj.getRangeKey());
    assertEquals(other, obj);
}
 
Example 11
Source File: AutoGeneratedKeysITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testHashKeyAutogeneratedKeyOnly() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    HashKeyAutoGeneratedKeyOnly obj = new HashKeyAutoGeneratedKeyOnly();
    obj.setRangeKey("" + System.currentTimeMillis());

    assertNull(obj.getKey());
    assertNotNull(obj.getRangeKey());
    mapper.save(obj);
    assertNotNull(obj.getKey());
    assertNotNull(obj.getRangeKey());

    HashKeyAutoGeneratedKeyOnly other = mapper.load(HashKeyAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey());
    assertEquals(other, obj);
}
 
Example 12
Source File: SimpleNumericAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDelete() throws Exception {
    NumberAttributeTestClass obj = getUniqueObject();
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.save(obj);

    NumberAttributeTestClass loaded = util.load(NumberAttributeTestClass.class, obj.getKey());
    loaded.setIgnored(obj.getIgnored());
    assertEquals(obj, loaded);

    util.delete(obj);
    assertNull(util.load(NumberAttributeTestClass.class, obj.getKey()));
}
 
Example 13
Source File: AwsKmsEncryptedObject.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
public static void encryptRecord(final String cmkArn, final String region) {
  // Sample object to be encrypted
  DataPoJo record = new DataPoJo();
  record.setPartitionAttribute("is this");
  record.setSortAttribute(55);
  record.setExample("data");
  record.setSomeNumbers(99);
  record.setSomeBinary(new byte[]{0x00, 0x01, 0x02});
  record.setLeaveMe("alone");

  // Set up our configuration and clients
  final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build();
  final AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(region).build();
  final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kms, cmkArn);
  // Encryptor creation
  final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp);
  // Mapper Creation
  // Please note the use of SaveBehavior.PUT (SaveBehavior.CLOBBER works as well).
  // Omitting this can result in data-corruption.
  DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder().withSaveBehavior(SaveBehavior.PUT).build();
  DynamoDBMapper mapper = new DynamoDBMapper(ddb, mapperConfig, new AttributeEncryptor(encryptor));

  System.out.println("Plaintext Record: " + record);
  // Save the item to the DynamoDB table
  mapper.save(record);

  // Retrieve the encrypted item (directly without decrypting) from Dynamo so we can see it in our example
  final Map<String, AttributeValue> itemKey = new HashMap<>();
  itemKey.put("partition_attribute", new AttributeValue().withS("is this"));
  itemKey.put("sort_attribute", new AttributeValue().withN("55"));
  System.out.println("Encrypted Record: " + ddb.getItem("ExampleTable", itemKey).getItem());
  
  // Retrieve (and decrypt) it from DynamoDB
  DataPoJo decrypted_record = mapper.load(DataPoJo.class, "is this", 55);
  System.out.println("Decrypted Record: " + decrypted_record);
}
 
Example 14
Source File: SimpleStringAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveOnlyKeyClobber() {
    KeyOnly obj = new KeyOnly();
    obj.setKey("" + startKey++);
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    mapper.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER));
    
    KeyOnly loaded = mapper.load(KeyOnly.class, obj.getKey(), new DynamoDBMapperConfig(ConsistentReads.CONSISTENT));
    assertEquals(obj, loaded);
    
    // saving again shouldn't be an error
    mapper.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER));
}
 
Example 15
Source File: ObjectPersistenceBatchWriteExample.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
private static void testBatchWrite(DynamoDBMapper mapper) {
    
    // Create Forum item to save
    Forum forumItem = new Forum();
    forumItem.name = "Test BatchWrite Forum";
    forumItem.threads = 0;
    forumItem.category = "Amazon Web Services";
    
    // Create Thread item to save
    Thread threadItem = new Thread();
    threadItem.forumName = "AmazonDynamoDB";
    threadItem.subject = "My sample question";
    threadItem.message = "BatchWrite message";
    List<String> tags = new ArrayList<String>();
    tags.add("batch operations");
    tags.add("write");
    threadItem.tags = new HashSet<String>(tags);
    
    // Load ProductCatalog item to delete
    Book book3 = mapper.load(Book.class, 903);
    
    List<Object> objectsToWrite = Arrays.asList(forumItem, threadItem);
    List<Book> objectsToDelete = Arrays.asList(book3);
    
    DynamoDBMapperConfig config = new DynamoDBMapperConfig(DynamoDBMapperConfig.SaveBehavior.CLOBBER);
    mapper.batchWrite(objectsToWrite, objectsToDelete, config);
}
 
Example 16
Source File: SimpleStringAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoad() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    for ( Map<String, AttributeValue> attr : attrs ) {
        StringAttributeTestClass x = util.load(StringAttributeTestClass.class, attr.get(KEY_NAME).getS());
        assertEquals(x.getKey(), attr.get(KEY_NAME).getS());
        assertEquals(x.getStringAttribute(), attr.get(STRING_ATTRIBUTE).getS());
        assertEquals(x.getRenamedAttribute(), attr.get(ORIGINAL_NAME_ATTRIBUTE).getS());
    }

}
 
Example 17
Source File: ExceptionHandlingITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = DynamoDBMappingException.class)
public void testPrivateKeyGetterLoad() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.load(PrivateKeyGetter.class, "abc");
}
 
Example 18
Source File: DynamoDBMapperQueryScanExample.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
private static void GetBook(DynamoDBMapper mapper, int id) throws Exception {
    System.out.println("GetBook: Get book Id='101' ");
    System.out.println("Book table has no sort key. You can do GetItem, but not Query.");
    Book book = mapper.load(Book.class, id);
    System.out.format("Id = %s Title = %s, ISBN = %s %n", book.getId(), book.getTitle(), book.getISBN());
}
 
Example 19
Source File: UseDynamoMapping.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

        final String USAGE = "\n" +
                "To run this example, supply the following values: \n" +
                "artist name \n" +
                "song title \n" +
                "album title \n" +
                "number of awards \n";

        if (args.length < 4) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String artist = args[0];
        String songTitle = args[1];
        String albumTitle = args[2];
        String awards = args[3];


        // snippet-start:[dynamodb.java.dynamoDB_mapping.main]
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        MusicItems items = new MusicItems();

        try{
            // Add new content to the Music table
            items.setArtist(artist);
            items.setSongTitle(songTitle);
            items.setAlbumTitle(albumTitle);
            items.setAwards(Integer.parseInt(awards)); //convert to an int

            // Save the item
            DynamoDBMapper mapper = new DynamoDBMapper(client);
            mapper.save(items);

            // Load an item based on the Partition Key and Sort Key
            // Both values need to be passed to the mapper.load method
            String artistName = artist;
            String songQueryTitle = songTitle;

            // Retrieve the item
            MusicItems itemRetrieved = mapper.load(MusicItems.class, artistName, songQueryTitle);
            System.out.println("Item retrieved:");
            System.out.println(itemRetrieved);

            // Modify the Award value
            itemRetrieved.setAwards(2);
            mapper.save(itemRetrieved);
            System.out.println("Item updated:");
            System.out.println(itemRetrieved);

            System.out.print("Done");
        } catch (AmazonDynamoDBException e) {
            e.getStackTrace();
        }
    }
 
Example 20
Source File: DBUtil.java    From alexa-skill-java with Apache License 2.0 4 votes vote down vote up
public static Person getPerson(String id) {
    DynamoDBMapper mapper = new DynamoDBMapper(getClient());
    return mapper.load(Person.class, id);
}