com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig. 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: Application.java    From spring-data-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
@Bean
public CommandLineRunner multirepo(ConfigurableApplicationContext ctx, CustomerRepository jpaRepository,
		DeviceRepository dynamoDBRepository, AmazonDynamoDB amazonDynamoDB, DynamoDBMapper dynamoDBMapper,
		DynamoDBMapperConfig config) {
	return (args) -> {
		demoJPA(jpaRepository);

		CreateTableRequest ctr = dynamoDBMapper.generateCreateTableRequest(Device.class)
				.withProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
		TableUtils.createTableIfNotExists(amazonDynamoDB, ctr);
		TableUtils.waitUntilActive(amazonDynamoDB, ctr.getTableName());


		demoDynamoDB(dynamoDBRepository);

		ctx.close();
	};
}
 
Example #3
Source File: TransactionManager.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
public TransactionManager(AmazonDynamoDB client, String transactionTableName, String itemImageTableName, DynamoDBMapperConfig config, AttributeTransformer transformer) {
    if(client == null) {
        throw new IllegalArgumentException("client must not be null");
    }
    if(transactionTableName == null) {
        throw new IllegalArgumentException("transactionTableName must not be null");
    }
    if(itemImageTableName == null) {
        throw new IllegalArgumentException("itemImageTableName must not be null");
    }
    this.client = client;
    this.transactionTableName = transactionTableName;
    this.itemImageTableName = itemImageTableName;
    this.facadeProxy = new ThreadLocalDynamoDBFacade();
    this.clientMapper = new DynamoDBMapper(facadeProxy, config, transformer);
    this.readUncommittedIsolationHandler = new ReadUncommittedIsolationHandlerImpl();
    this.readCommittedIsolationHandler = new ReadCommittedIsolationHandlerImpl(this);
}
 
Example #4
Source File: DynamoDBRepositoryExtension.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Bean}.
 * 
 * @param <T>
 *            The type of the repository.
 * @param repositoryType
 *            The class representing the repository.
 * @param beanManager
 *            The BeanManager instance.
 * @return The bean.
 */
private <T> Bean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers, BeanManager beanManager) {

	// Determine the amazondbclient bean which matches the qualifiers of the
	// repository.
	Bean<AmazonDynamoDB> amazonDynamoDBBean = amazonDynamoDBs.get(qualifiers);

	// Determine the dynamo db mapper configbean which matches the
	// qualifiers of the repository.
	Bean<DynamoDBMapperConfig> dynamoDBMapperConfigBean = dbMapperConfigs.get(qualifiers);
	
	if (amazonDynamoDBBean == null) {
		throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
				AmazonDynamoDBClient.class.getName(), qualifiers));
	}
	
	Bean<DynamoDBOperations> dynamoDBOperationsBean = dynamoDBOperationss.get(qualifiers);

	
	// Construct and return the repository bean.
	return new DynamoDBRepositoryBean<T>(beanManager, amazonDynamoDBBean, dynamoDBMapperConfigBean,dynamoDBOperationsBean,qualifiers,
			repositoryType);
}
 
Example #5
Source File: DynamoDBRepositoryBean.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
@Override
public T create(CreationalContext<T> creationalContext, Class<T> repositoryType) {

	// Get an instance from the associated AmazonDynamoDB bean.
	AmazonDynamoDB amazonDynamoDB = getDependencyInstance(amazonDynamoDBBean, AmazonDynamoDB.class);

	// Get an instance from the associated optional AmazonDynamoDB bean.
	DynamoDBMapperConfig dynamoDBMapperConfig = dynamoDBMapperConfigBean == null ? null : getDependencyInstance(
			dynamoDBMapperConfigBean, DynamoDBMapperConfig.class);
	
	DynamoDBOperations dynamoDBOperations = dynamoDBOperationsBean == null ? null
			:  getDependencyInstance(
					dynamoDBOperationsBean, DynamoDBOperations.class);

	if (dynamoDBOperations == null)
	{
		dynamoDBOperations = new DynamoDBTemplate(amazonDynamoDB,dynamoDBMapperConfig);
	}
	
	DynamoDBRepositoryFactory factory = new DynamoDBRepositoryFactory(dynamoDBOperations);
	return factory.getRepository(repositoryType);
}
 
Example #6
Source File: DynamoDBRepositoryBean.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a {@link DynamoDBRepositoryBean}.
 * 
 * @param beanManager
 *            must not be {@literal null}.
 * @param dynamoDBMapperBean
 *            must not be {@literal null}.
 * @param qualifiers
 *            must not be {@literal null}.
 * @param repositoryType
 *            must not be {@literal null}.
 */
DynamoDBRepositoryBean(BeanManager beanManager, Bean<AmazonDynamoDB> amazonDynamoDBBean,
		Bean<DynamoDBMapperConfig> dynamoDBMapperConfigBean,Bean<DynamoDBOperations> dynamoDBOperationsBean, Set<Annotation> qualifiers, Class<T> repositoryType) {

	super(qualifiers, repositoryType, beanManager);
	if (dynamoDBOperationsBean == null)
	{
		Assert.notNull(amazonDynamoDBBean);
	}
	else
	{
		Assert.isNull(amazonDynamoDBBean,"Cannot specify both amazonDynamoDB bean and dynamoDBOperationsBean in repository configuration");
		Assert.isNull(dynamoDBMapperConfigBean,"Cannot specify both dynamoDBMapperConfigBean bean and dynamoDBOperationsBean in repository configuration");

	}
	this.amazonDynamoDBBean = amazonDynamoDBBean;
	this.dynamoDBMapperConfigBean = dynamoDBMapperConfigBean;
	this.dynamoDBOperationsBean = dynamoDBOperationsBean;
}
 
Example #7
Source File: MapperQueryExpressionCryptoTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
private static <T> QueryRequest testCreateQueryRequestFromExpression(
        Class<T> clazz, DynamoDBQueryExpression<T> queryExpression,
        String expectedErrorMessage) {
    try {
        QueryRequest request = (QueryRequest) testedMethod.invoke(mapper, clazz, queryExpression, DynamoDBMapperConfig.DEFAULT);
        if (expectedErrorMessage != null) {
            fail("Exception containing messsage ("
                    + expectedErrorMessage + ") is expected.");
        }
        return request;
    } catch (InvocationTargetException ite) {
        if (expectedErrorMessage != null) {
            assertTrue("Exception message [" + ite.getCause().getMessage() + "] does not contain " +
                            "the expected message [" + expectedErrorMessage + "].",
                    ite.getCause().getMessage().contains(expectedErrorMessage));
        } else {
            ite.getCause().printStackTrace();
            fail("Internal error when calling createQueryRequestFromExpressio method");
        }
    } catch (Exception e) {
        fail(e.getMessage());
    }
    return null;
}
 
Example #8
Source File: MapperLoadingStrategyConfigITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
private static PaginatedList<RangeKeyTestClass> getTestPaginatedParallelScanList(PaginationLoadingStrategy paginationLoadingStrategy) {
    DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT);
    DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig);
    
    // Construct the scan expression with the exact same conditions
    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
    scanExpression.addFilterCondition("key", 
            new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(
                    new AttributeValue().withN(Long.toString(hashKey))));
    scanExpression.addFilterCondition("rangeKey", 
            new Condition().withComparisonOperator(ComparisonOperator.GT).withAttributeValueList(
                    new AttributeValue().withN("1.0")));
    scanExpression.setLimit(PAGE_SIZE);
    
    return mapper.parallelScan(RangeKeyTestClass.class, scanExpression, PARALLEL_SEGMENT, new DynamoDBMapperConfig(paginationLoadingStrategy));
}
 
Example #9
Source File: MapperLoadingStrategyConfigITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
private static PaginatedList<RangeKeyTestClass> getTestPaginatedScanList(PaginationLoadingStrategy paginationLoadingStrategy) {
    DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT);
    DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig);
    
    // Construct the scan expression with the exact same conditions
    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
    scanExpression.addFilterCondition("key", 
            new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(
                    new AttributeValue().withN(Long.toString(hashKey))));
    scanExpression.addFilterCondition("rangeKey", 
            new Condition().withComparisonOperator(ComparisonOperator.GT).withAttributeValueList(
                    new AttributeValue().withN("1.0")));
    scanExpression.setLimit(PAGE_SIZE);
    
    return mapper.scan(RangeKeyTestClass.class, scanExpression, new DynamoDBMapperConfig(paginationLoadingStrategy));
}
 
Example #10
Source File: AbstractDAO.java    From nfscan with MIT License 6 votes vote down vote up
/**
 * Find all rows in table given the entity object
 *
 * @return a list of entities found
 * @throws DataAccessException
 */
public List<T> findAll() throws DataAccessException {
    DynamoDBScanExpression dynamoDBScanExpression = new DynamoDBScanExpression();
    DynamoDBMapperConfig config = new DynamoDBMapperConfig(DynamoDBMapperConfig.PaginationLoadingStrategy.EAGER_LOADING);
    PaginatedScanList<T> paginatedScanList = dynamoDBMapper.scan(getType(), dynamoDBScanExpression, config);
    paginatedScanList.loadAllResults();

    List<T> list = new ArrayList<T>(paginatedScanList.size());

    Iterator<T> iterator = paginatedScanList.iterator();
    while (iterator.hasNext()) {
        T element = iterator.next();
        list.add(element);
    }

    return list;
}
 
Example #11
Source File: Application.java    From spring-data-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
@Bean
public CommandLineRunner rest(ConfigurableApplicationContext ctx, UserRepository dynamoDBRepository,
		AmazonDynamoDB amazonDynamoDB, DynamoDBMapper dynamoDBMapper, DynamoDBMapperConfig config) {
	return (args) -> {

		CreateTableRequest ctr = dynamoDBMapper.generateCreateTableRequest(User.class)
				.withProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
		TableUtils.createTableIfNotExists(amazonDynamoDB, ctr);
		TableUtils.waitUntilActive(amazonDynamoDB, ctr.getTableName());

		createEntities(dynamoDBRepository);

		log.info("");
		log.info("Run curl -v http://localhost:8080/users and follow the HATEOS links");
		log.info("");
		log.info("Press <enter> to shutdown");
		System.in.read();
		ctx.close();
	};
}
 
Example #12
Source File: DynamoDBMapperWithCustomTableName.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
public DynamoDBMapperWithCustomTableName(AmazonDynamoDBClient amazonDynamoDBClient, DynamoDBMapperConfig.TableNameResolver tableNameResolver) {
    super(amazonDynamoDBClient,
            DynamoDBMapperConfig
                    .builder()
                    .withTableNameResolver(tableNameResolver)
                    .build());
}
 
Example #13
Source File: Application.java    From spring-data-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner custom(ConfigurableApplicationContext ctx, UserRepository userRepository,
		AmazonDynamoDB amazonDynamoDB, DynamoDBMapper dynamoDBMapper, DynamoDBMapperConfig config) {
	return (args) -> {
		CreateTableRequest ctr = dynamoDBMapper.generateCreateTableRequest(User.class)
				.withProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
		TableUtils.createTableIfNotExists(amazonDynamoDB, ctr);
		TableUtils.waitUntilActive(amazonDynamoDB, ctr.getTableName());

		demoCustomInterface(userRepository);

		ctx.close();
	};
}
 
Example #14
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 #15
Source File: DynamoDBPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private DynamoDBMapper getDBMapper(String tableName) {
    try {
        DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig.Builder()
                .withTableNameOverride(new DynamoDBMapperConfig.TableNameOverride(tableName))
                .withPaginationLoadingStrategy(PaginationLoadingStrategy.LAZY_LOADING).build();
        return new DynamoDBMapper(db.getDynamoClient(), mapperConfig);
    } catch (AmazonClientException e) {
        logger.error("Error getting db mapper: {}", e.getMessage());
        throw e;
    }
}
 
Example #16
Source File: DynamoDBTemplate.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
public void setDynamoDBMapperConfig(DynamoDBMapperConfig dynamoDBMapperConfig)
{
	this.dynamoDBMapperConfig = dynamoDBMapperConfig;
	dynamoDBMapper = dynamoDBMapperConfig == null ? new DynamoDBMapper(amazonDynamoDB) : new DynamoDBMapper(
			amazonDynamoDB, dynamoDBMapperConfig);
	if (dynamoDBMapperConfig == null)
	{
		this.dynamoDBMapperConfig = DynamoDBMapperConfig.DEFAULT;
	}
}
 
Example #17
Source File: FakeParameters.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private FakeParameters(Class<T> clazz, Map<String, AttributeValue> attribs,
                       DynamoDBMapperConfig config, String tableName, String hashKeyName, String rangeKeyName,
                       boolean isPartialUpdate) {
    super();
    this.clazz = clazz;
    this.attrs = Collections.unmodifiableMap(attribs);
    this.config = config;
    this.tableName = tableName;
    this.hashKeyName = hashKeyName;
    this.rangeKeyName = rangeKeyName;
    this.isPartialUpdate = isPartialUpdate;
}
 
Example #18
Source File: FakeParameters.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
public static <T> AttributeTransformer.Parameters<T> getInstance(Class<T> clazz,
                                                                 Map<String, AttributeValue> attribs, DynamoDBMapperConfig config, String tableName,
                                                                 String hashKeyName, String rangeKeyName, boolean isPartialUpdate) {

    // We use this relatively insane proxy setup so that modifications to the Parameters
    // interface doesn't break our tests (unless it actually impacts our code).
    FakeParameters<T> fakeParams = new FakeParameters<T>(clazz, attribs, config, tableName,
            hashKeyName, rangeKeyName, isPartialUpdate);
    @SuppressWarnings("unchecked")
    AttributeTransformer.Parameters<T> proxyObject = (AttributeTransformer.Parameters<T>) Proxy
            .newProxyInstance(AttributeTransformer.class.getClassLoader(),
                    new Class[]{AttributeTransformer.Parameters.class},
                    new ParametersInvocationHandler<T>(fakeParams));
    return proxyObject;
}
 
Example #19
Source File: MapperQueryExpressionCryptoTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws SecurityException, NoSuchMethodException {
    AmazonDynamoDB dynamo = new AmazonDynamoDBClient();
    mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    testedMethod = DynamoDBMapper.class.getDeclaredMethod("createQueryRequestFromExpression", Class.class, DynamoDBQueryExpression.class, DynamoDBMapperConfig.class);
    testedMethod.setAccessible(true);
}
 
Example #20
Source File: DynamoDBMapperWithCustomTableName.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
public DynamoDBMapperWithCustomTableName(AmazonDynamoDBClient amazonDynamoDBClient, DynamoDBMapperConfig.TableNameResolver tableNameResolver) {
    super(amazonDynamoDBClient,
            DynamoDBMapperConfig
                    .builder()
                    .withTableNameResolver(tableNameResolver)
                    .build());
}
 
Example #21
Source File: EnvironmentVariableTableNameResolver.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
@Override
public String getTableName(Class<?> clazz, DynamoDBMapperConfig config) {
    String environmentVariableName = "DynamoDb" + clazz.getSimpleName() + "Table";
    String tableName = System.getenv(environmentVariableName);
    if (tableName == null) {
        throw new DynamoDBMappingException("DynamoDB table name for " + clazz + " cannot be determined. " + environmentVariableName + " environment variable should be set.");
    }
    return tableName;
}
 
Example #22
Source File: MapperLoadingStrategyConfigITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private static PaginatedList<RangeKeyTestClass> getTestPaginatedQueryList(PaginationLoadingStrategy paginationLoadingStrategy) {
    DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT);
    DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig);
    
    // Construct the query expression for the tested hash-key value and any range-key value greater that 1.0
    RangeKeyTestClass keyObject = new RangeKeyTestClass();
    keyObject.setKey(hashKey);
    DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>().withHashKeyValues(keyObject);
    queryExpression.withRangeKeyCondition("rangeKey",
            new Condition().withComparisonOperator(ComparisonOperator.GT.toString()).withAttributeValueList(
                    new AttributeValue().withN("1.0"))).withLimit(PAGE_SIZE);
    
    return mapper.query(RangeKeyTestClass.class, queryExpression, new DynamoDBMapperConfig(paginationLoadingStrategy));
}
 
Example #23
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 #24
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 #25
Source File: ConfigurationITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testClobber() throws Exception {
    DynamoDBMapper util = new DynamoDBMapper(dynamo, new DynamoDBMapperConfig(SaveBehavior.CLOBBER));

    NumberAttributeTestClassExtended obj = getUniqueObject();
    util.save(obj);
    assertEquals(obj, util.load(obj.getClass(), obj.getKey()));

    NumberAttributeTestClass copy = copy(obj);
    util.save(copy);
    assertEquals(copy, util.load(copy.getClass(), obj.getKey()));

    // We should have lost the extra field because of the clobber behavior
    assertNull(util.load(NumberAttributeTestClassExtended.class, obj.getKey()).getExtraField());

    // Now test overriding the clobber behavior on a per-save basis
    obj = getUniqueObject();
    util.save(obj);
    assertEquals(obj, util.load(obj.getClass(), obj.getKey()));

    copy = copy(obj);
    util.save(copy, new DynamoDBMapperConfig(SaveBehavior.UPDATE));
    assertEquals(copy, util.load(copy.getClass(), obj.getKey()));

    // We shouldn't have lost any extra info
    assertNotNull(util.load(NumberAttributeTestClassExtended.class, obj.getKey()).getExtraField());
}
 
Example #26
Source File: EnvironmentVariableTableNameResolver.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
@Override
public String getTableName(Class<?> clazz, DynamoDBMapperConfig config) {
    String environmentVariableName = "DynamoDb" + clazz.getSimpleName() + "Table";
    String tableName = System.getenv(environmentVariableName);
    if (tableName == null) {
        throw new DynamoDBMappingException("DynamoDB table name for " + clazz + " cannot be determined. " + environmentVariableName + " environment variable should be set.");
    }
    return tableName;
}
 
Example #27
Source File: QueryITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    setUpTableWithRangeAttribute();

    DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(
            ConsistentReads.CONSISTENT);
    mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo, mapperConfig);

    putTestData(mapper, TEST_ITEM_NUMBER);

    hashKeyObject = new RangeKeyTestClass();
    hashKeyObject.setKey(HASH_KEY);
}
 
Example #28
Source File: DynamoDBMapperWithCustomTableName.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
public DynamoDBMapperWithCustomTableName(AmazonDynamoDBClient amazonDynamoDBClient, DynamoDBMapperConfig.TableNameResolver tableNameResolver) {
    super(amazonDynamoDBClient,
            DynamoDBMapperConfig
                    .builder()
                    .withTableNameResolver(tableNameResolver)
                    .build());
}
 
Example #29
Source File: EnvironmentVariableTableNameResolver.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
@Override
public String getTableName(Class<?> clazz, DynamoDBMapperConfig config) {
    String environmentVariableName = "DynamoDb" + clazz.getSimpleName() + "Table";
    String tableName = System.getenv(environmentVariableName);
    if (tableName == null) {
        throw new DynamoDBMappingException("DynamoDB table name for " + clazz + " cannot be determined. " + environmentVariableName + " environment variable should be set.");
    }
    return tableName;
}
 
Example #30
Source File: DynamoDBMapperBatchWriteExample.java    From aws-doc-sdk-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 = DynamoDBMapperConfig.builder()
            .withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.CLOBBER)
        .build();

        mapper.batchWrite(objectsToWrite, objectsToDelete, config);
    }