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

The following examples show how to use com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#save() . 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: SimpleStringAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests saving an incomplete object into DynamoDB
 */
@Test
public void testIncompleteObject() {
    StringAttributeTestClass obj = getUniqueObject();
    obj.setStringAttribute(null);
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.save(obj);
    
    assertEquals(obj, util.load(StringAttributeTestClass.class, obj.getKey()));
    
    // test removing an attribute
    assertNotNull(obj.getRenamedAttribute());
    obj.setRenamedAttribute(null);
    util.save(obj);
    assertEquals(obj, util.load(StringAttributeTestClass.class, obj.getKey()));        
}
 
Example 3
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 4
Source File: HashKeyOnlyTableWithGSIITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that we can query using the hash/range GSI on our hash-key only
 * table.
 */
@Test
public void testGSIQuery() throws Exception {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory
            .createDynamoDBMapper(dynamo);
    String status = "foo-status";

    User user = new User();
    user.setId("123");
    user.setStatus(status);
    user.setTs("321");
    mapper.save(user);

    DynamoDBQueryExpression<User> expr = new DynamoDBQueryExpression<User>()
            .withIndexName("statusAndCreation")
            .withLimit(100)
            .withConsistentRead(false)
            .withHashKeyValues(user)
            .withRangeKeyCondition(
                    "ts",
                    new Condition()
                    .withComparisonOperator(ComparisonOperator.GT)
                    .withAttributeValueList(new AttributeValue("100")));

    PaginatedQueryList<User> query = mapper.query(User.class, expr);
    int size = query.size();
    if (DEBUG)
        System.err.println("size=" + size);
    assertTrue(1 == size);
    assertEquals(status, query.get(0).getStatus());
}
 
Example 5
Source File: AutoGeneratedKeysITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testNothingAutogenerated() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    NothingAutoGenerated obj = new NothingAutoGenerated();
    obj.setOtherAttribute("blah");
    obj.setKey("" + System.currentTimeMillis());
    obj.setRangeKey("" + System.currentTimeMillis());

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

    NothingAutoGenerated other = mapper.load(NothingAutoGenerated.class, obj.getKey(), obj.getRangeKey());
    assertEquals(other, obj);
}
 
Example 6
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 testAutoGeneratedIntegerHashKey() {
    AutoGeneratedIntegerKey obj = new AutoGeneratedIntegerKey();
    obj.setValue("fdgfdsgf");
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    mapper.save(obj);
}
 
Example 7
Source File: ExceptionHandlingITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonSetCollection() {
    NonSetCollectionType obj = new NonSetCollectionType();
    obj.setKey("" + startKey++);
    obj.setBadlyMapped(new ArrayList<String>());
    obj.getBadlyMapped().add("abc");
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    mapper.save(obj);
}
 
Example 8
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 9
Source File: SimpleStringAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveOnlyKey() {
    KeyOnly obj = new KeyOnly();
    obj.setKey("" + startKey++);
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    mapper.save(obj);
    
    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);
}
 
Example 10
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 11
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 testPrivateSetterLoad() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    PrivateSetter object = new PrivateSetter();
    object.setStringProperty("value");
    util.save(object);
    util.load(PrivateSetter.class, object.getKey());
}
 
Example 12
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 testFractionalVersionAttribute() {
    FractionalVersionAttribute obj = new FractionalVersionAttribute();
    obj.setKey("" + startKey++);
    obj.setVersion(0d);
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    mapper.save(obj);
}
 
Example 13
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 14
Source File: DynamoDBMapperExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {

        // Set the AWS region you want to access.
        Regions usWest2 = Regions.US_WEST_2;
        client = AmazonDynamoDBClientBuilder.standard().withRegion(usWest2).build();

        DimensionType dimType = new DimensionType();
        dimType.setHeight("8.00");
        dimType.setLength("11.0");
        dimType.setThickness("1.0");

        Book book = new Book();
        book.setId(502);
        book.setTitle("Book 502");
        book.setISBN("555-5555555555");
        book.setBookAuthors(new HashSet<String>(Arrays.asList("Author1", "Author2")));
        book.setDimensions(dimType);

        DynamoDBMapper mapper = new DynamoDBMapper(client);
        mapper.save(book);

        Book bookRetrieved = mapper.load(Book.class, 502);
        System.out.println("Book info: " + "\n" + bookRetrieved);

        bookRetrieved.getDimensions().setHeight("9.0");
        bookRetrieved.getDimensions().setLength("12.0");
        bookRetrieved.getDimensions().setThickness("2.0");

        mapper.save(bookRetrieved);

        bookRetrieved = mapper.load(Book.class, 502);
        System.out.println("Updated book info: " + "\n" + bookRetrieved);
    }
 
Example 15
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 testNoHashKeyGetter() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.save(new NoKeyGetterDefined());
}
 
Example 16
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 testPrivateKeyGetter() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.save(new PrivateKeyGetter());
}
 
Example 17
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 18
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 testNoTableAnnotation() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.save(new NoTableAnnotation());
}
 
Example 19
Source File: EncryptionContextOverridesWithDynamoDBMapper.java    From aws-dynamodb-encryption-java with Apache License 2.0 4 votes vote down vote up
public static void encryptRecord(final String cmkArn,
                                 final String newEncryptionContextTableName,
                                 AmazonDynamoDB ddb,
                                 AWSKMS kms) throws GeneralSecurityException {
    // Sample object to be encrypted
    ExampleItem record = new ExampleItem();
    record.setPartitionAttribute("is this");
    record.setSortAttribute(55);
    record.setExample("my data");

    // Set up our configuration and clients
    final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kms, cmkArn);
    final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp);

    Map<String, String> tableNameEncryptionContextOverrides = new HashMap<>();
    tableNameEncryptionContextOverrides.put("ExampleTableForEncryptionContextOverrides", newEncryptionContextTableName);
    tableNameEncryptionContextOverrides.put("AnotherExampleTableForEncryptionContextOverrides", "this table doesn't exist");

    // Supply an operator to override the table name used in the encryption context
    encryptor.setEncryptionContextOverrideOperator(
            overrideEncryptionContextTableNameUsingMap(tableNameEncryptionContextOverrides)
    );

    // 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(DynamoDBMapperConfig.SaveBehavior.PUT).build();
    DynamoDBMapper mapper = new DynamoDBMapper(ddb, mapperConfig, new AttributeEncryptor(encryptor));

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

    // Retrieve (and decrypt) it from DynamoDB
    ExampleItem decrypted_record = mapper.load(ExampleItem.class, "is this", 55);
    System.out.println("Decrypted Record: " + decrypted_record.toString());

    // Setup new configuration to decrypt without using an overridden EncryptionContext
    final Map<String, AttributeValue> itemKey = new HashMap<>();
    itemKey.put("partition_attribute", new AttributeValue().withS("is this"));
    itemKey.put("sort_attribute", new AttributeValue().withN("55"));

    final EnumSet<EncryptionFlags> signOnly = EnumSet.of(EncryptionFlags.SIGN);
    final EnumSet<EncryptionFlags> encryptAndSign = EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN);
    final Map<String, AttributeValue> encryptedItem = ddb.getItem("ExampleTableForEncryptionContextOverrides", itemKey)
            .getItem();
    System.out.println("Encrypted Record: " + encryptedItem);

    Map<String, Set<EncryptionFlags>> encryptionFlags = new HashMap<>();
    encryptionFlags.put("partition_attribute", signOnly);
    encryptionFlags.put("sort_attribute", signOnly);
    encryptionFlags.put("example", encryptAndSign);

    final DynamoDBEncryptor encryptorWithoutOverrides = DynamoDBEncryptor.getInstance(cmp);

    // Decrypt the record without using an overridden EncryptionContext
    encryptorWithoutOverrides.decryptRecord(encryptedItem,
            encryptionFlags,
            new EncryptionContext.Builder().withHashKeyName("partition_attribute")
                    .withRangeKeyName("sort_attribute")
                    .withTableName(newEncryptionContextTableName)
                    .build());
    System.out.printf("The example item was encrypted using the table name '%s' in the EncryptionContext%n", newEncryptionContextTableName);
}
 
Example 20
Source File: BinaryAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 4 votes vote down vote up
/**
 * Tests saving an incomplete object into DynamoDB
 */
@Test
public void testIncompleteObject() {
	// test BinaryAttributeClass
	BinaryAttributeByteBufferTestClass byteBufferObj = getUniqueByteBufferObject(contentLength);
    byteBufferObj.setBinarySetAttribute(null);
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.save(byteBufferObj);

    BinaryAttributeByteBufferTestClass loadedX = util.load(BinaryAttributeByteBufferTestClass.class, byteBufferObj.getKey());
    assertEquals(loadedX.getKey(), byteBufferObj.getKey());
	assertEquals(loadedX.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength)));
	assertEquals(loadedX.getBinarySetAttribute(), null);


    // test removing an attribute
    assertNotNull(byteBufferObj.getBinaryAttribute());
    byteBufferObj.setBinaryAttribute(null);
    util.save(byteBufferObj);

    loadedX = util.load(BinaryAttributeByteBufferTestClass.class, byteBufferObj.getKey());
    assertEquals(loadedX.getKey(), byteBufferObj.getKey());
	assertEquals(loadedX.getBinaryAttribute(), null);
	assertEquals(loadedX.getBinarySetAttribute(), null);

	// test BinaryAttributeByteArrayTestClass
	BinaryAttributeByteArrayTestClass bytesObj = getUniqueBytesObject(contentLength);
    bytesObj.setBinarySetAttribute(null);
    util.save(bytesObj);

    BinaryAttributeByteArrayTestClass loadedY = util.load(BinaryAttributeByteArrayTestClass.class, bytesObj.getKey());
    assertEquals(loadedY.getKey(), bytesObj.getKey());
	assertTrue(Arrays.equals(loadedY.getBinaryAttribute(), generateByteArray(contentLength)));
	assertEquals(loadedY.getBinarySetAttribute(), null);


    // test removing an attribute
    assertNotNull(bytesObj.getBinaryAttribute());
    bytesObj.setBinaryAttribute(null);
    util.save(bytesObj);

    loadedY = util.load(BinaryAttributeByteArrayTestClass.class, bytesObj.getKey());
    assertEquals(loadedY.getKey(), bytesObj.getKey());
	assertEquals(loadedY.getBinaryAttribute(), null);
	assertEquals(loadedY.getBinarySetAttribute(), null);
}