@PostConstruct protected void init() { configureAWSLogAgent(); credentialsProvider = new InstanceProfileCredentialsProvider(); region = Regions.getCurrentRegion(); amazonDynamoDB.setRegion(region); dbPrefix = AmazonConfigProvider.getDynamoDbPrefix(); DynamoDBMapperConfig config = new DynamoDBMapperConfig.Builder().withTableNameOverride(DynamoDBMapperConfig.TableNameOverride. withTableNamePrefix(dbPrefix)).build(); mapper = new DynamoDBMapper(amazonDynamoDB, config); tablesWithPrefix = Arrays.stream(tables).map(s -> dbPrefix.concat(s)).collect(Collectors.toList()); if (customBucketName != null) { customBucketName = customBucketName.toLowerCase(); } if ((customBucketName.isEmpty() || CUSTOM_BUCKET_NAME_DEFAULT_VALUE.equals(customBucketName)) && !validateBucketName(customBucketName).isValid()) { customBucketName = null; } }
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; }
/** * 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; }
@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); }
/** * 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); }
@Inject public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) { mapper = new DynamoDBMapper(client, new DynamoDBMapperConfig.Builder() .withTableNameOverride(TableNameOverride .withTableNamePrefix(env.get("DYNAMODB_TABLE_PREFIX").orElse("localhost") + ".")) .build()); }
@Bean public DynamoDBMapperConfig dynamoDBMapperConfig() { DynamoDBMapperConfig.Builder builder = new DynamoDBMapperConfig.Builder(); builder.withTableNameOverride(DynamoDBMapperConfig.TableNameOverride. withTableNamePrefix(getDynamoDbPrefix())); return builder.build(); }
/** * 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; }
@BeforeClass public static void setUp() throws Exception { client = ClientFactory.getInstance(); mapper = new DynamoDBMapper(client, new DynamoDBMapperConfig( DynamoDBMapperConfig.SaveBehavior.CLOBBER, DynamoDBMapperConfig.ConsistentReads.CONSISTENT, null)); fillTable(); }
@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); }
public static <T> AttributeTransformer.Parameters<T> getInstance(Class<T> clazz, Map<String, AttributeValue> attribs, DynamoDBMapperConfig config, String tableName, String hashKeyName, String rangeKeyName) { // 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); @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; }
private FakeParameters(Class<T> clazz, Map<String, AttributeValue> attribs, DynamoDBMapperConfig config, String tableName, String hashKeyName, String rangeKeyName) { super(); this.clazz = clazz; this.attrs = Collections.unmodifiableMap(attribs); this.config = config; this.tableName = tableName; this.hashKeyName = hashKeyName; this.rangeKeyName = rangeKeyName; }
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); }
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."); } }
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; } }
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; } }
public DynamoDBRecipeDraftsStore() { this.logger = LogManager.getLogger(getClass()); AWSCredentials credentials = new BasicAWSCredentials(Configuration.getInstance().getDynamoDbAccessKey(), Configuration.getInstance().getDynamoDbAccessSecret()); AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(credentials); dynamoDBClient.setRegion(Region.getRegion(Regions.EU_WEST_1)); this.mapper = new DynamoDBMapper(dynamoDBClient, new DynamoDBMapperConfig( DynamoDBMapperConfig.SaveBehavior.UPDATE_SKIP_NULL_ATTRIBUTES)); }
/** * {@inheritDoc} */ @Override public void addResourceTriple(final ResourceTriple triple) { mapper.save(triple, DynamoDBMapperConfig.SaveBehavior.CLOBBER.config()); }
public DynamoDBExecutor(final AmazonDynamoDBClient dynamoDB, final DynamoDBMapperConfig config) { this(dynamoDB, config, new AsyncExecutor(64, 300, TimeUnit.SECONDS)); }
public DynamoDBExecutor(final AmazonDynamoDBClient dynamoDB, final DynamoDBMapperConfig config, final AsyncExecutor asyncExecutor) { this.dynamoDB = dynamoDB; this.asyncDBExecutor = new AsyncDynamoDBExecutor(this, asyncExecutor); this.mapper = config == null ? new DynamoDBMapper(dynamoDB) : new DynamoDBMapper(dynamoDB, config); }
public DynamoDBMapper mapper(final DynamoDBMapperConfig config) { return new DynamoDBMapper(dynamoDB, config); }
@PostConstruct protected void init() { DynamoDBMapperConfig config = new DynamoDBMapperConfig.Builder().withTableNameOverride(DynamoDBMapperConfig.TableNameOverride. withTableNamePrefix(AmazonConfigProviderDEV.getDynamoDbPrefix(SystemUtils.getSystemId()))).build(); mapper = new DynamoDBMapper(amazonDynamoDB, config); }
public DynamoDBMapperConfig dynamoDBMapperConfig() { DynamoDBMapperConfig.Builder builder = new DynamoDBMapperConfig.Builder(); builder.withTableNameOverride(DynamoDBMapperConfig.TableNameOverride. withTableNamePrefix(AmazonConfigProvider.getDynamoDbPrefix())); return builder.build(); }
@DynamoDBIgnore public HashSet<HNItemItem> getHNItemsByd(int minutes_ago, DynamoDBMapper mapper, DynamoDBMapperConfig dynamo_config) { // set up an expression to query screename#id DynamoDBQueryExpression<HNItemItem> queryExpression = new DynamoDBQueryExpression<HNItemItem>() .withIndexName("by-time-index") .withScanIndexForward(true) .withConsistentRead(false); // set the user_id part HNItemItem key = new HNItemItem(); key.setBy(getId()); queryExpression.setHashKeyValues(key); // set the msfe range part if(minutes_ago > 0) { //System.out.println("Getting comment children with a valid cutoff time."); Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, (minutes_ago * -1)); long time_cutoff = cal.getTimeInMillis() / 1000; // set the msfe range part Map<String, Condition> keyConditions = new HashMap<String, Condition>(); keyConditions.put("time",new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue().withN(new Long(time_cutoff).toString()))); queryExpression.setRangeKeyConditions(keyConditions); } // execute List<HNItemItem> notificationitems = mapper.query(HNItemItem.class, queryExpression, dynamo_config); if(notificationitems != null && notificationitems.size() > 0) { HashSet<HNItemItem> returnset = new HashSet<HNItemItem>(); for (HNItemItem notificationitem : notificationitems) { returnset.add(notificationitem); } return returnset; } else { return null; } }
public static DynamoDBMapper createDynamoDBMapper(AmazonDynamoDB dynamo) { return new DynamoDBMapper(dynamo, DynamoDBMapperConfig.DEFAULT, new AttributeEncryptor(new TestEncryptionMaterialsProvider())); }
public static DynamoDBMapper createDynamoDBMapper(AmazonDynamoDB dynamo, DynamoDBMapperConfig config) { return new DynamoDBMapper(dynamo, config, new AttributeEncryptor(new TestEncryptionMaterialsProvider())); }
public DynamoDBMapperConfig getMapperConfig() { return config; }
/** * Create a new DynamoDBMapper with table name override */ public static DynamoDBMapper createDynamoMapper(AmazonDynamoDBClient dynamoDbClient, String tableName) { return new DynamoDBMapper(dynamoDbClient, new DynamoDBMapperConfig(new TableNameOverride(tableName))); }
public void setDynamoDBMapperConfig(DynamoDBMapperConfig dynamoDBMapperConfig) { this.dynamoDBMapperConfig = dynamoDBMapperConfig; }
public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB,DynamoDBMapperConfig dynamoDBMapperConfig) { this.amazonDynamoDB = amazonDynamoDB; setDynamoDBMapperConfig(dynamoDBMapperConfig); }
/** * Creates a {@link DynamoDBMapper} with a customized configuration and customized attribute transformer. * * @param dynamoDb The DynamoDB client. * @param config The configuration to use. * @param transformer The attribute transformer to use. * @return A DynamoDB mapper. */ public static DynamoDBMapper createDynamoDbMapper( final AmazonDynamoDB dynamoDb, final DynamoDBMapperConfig config, final AttributeTransformer transformer) { return new DynamoDBMapper(dynamoDb, config, transformer); }
/** * Counts all rows in this specific table. * Use it carefully since it loads all results from DynamoDB. To be honest there are only * a few situations where this could be considered a wise solution. * * @return a amount of rows found * @throws DataAccessException */ public int count() throws DataAccessException { DynamoDBScanExpression dynamoDBScanExpression = new DynamoDBScanExpression(); DynamoDBMapperConfig config = new DynamoDBMapperConfig(DynamoDBMapperConfig.PaginationLoadingStrategy.EAGER_LOADING); PaginatedScanList<T> paginatedScanList = dynamoDBMapper.scan(getType(), dynamoDBScanExpression, config); paginatedScanList.loadAllResults(); return paginatedScanList.size(); }
/** * Update document processor * <p/> * {@sample.xml ../../../doc/DynamoDB-connector.xml.sample dynamodb:update-document} * * @param tableName * the table to update * @param document * the object to save to the table as a document. If not explicitly provided, it defaults to PAYLOAD. * * @return Object the place that was stored */ @Processor public Object updateDocument(final String tableName, @Optional @Default(PAYLOAD) final Object document) { DynamoDBMapperConfig config = new DynamoDBMapperConfig(DynamoDBMapperConfig.SaveBehavior.UPDATE); DynamoDBMapper mapper = getDbObjectMapper(tableName); mapper.save(document, config); // save does not return the modified document. Just return the original. return document; }
/** * Creates a DynamoDB configuration that forces the table name to the parameter. * * @param tableName The name of the table. * @return A DynamoDB configuration that forces the table name. */ DynamoDBMapperConfig tableNameOverrideConfig(String tableName) { return DynamoDBMapperConfig.builder().withTableNameOverride(new DynamoDBMapperConfig.TableNameOverride(tableName)) .build(); }
/** * Nameless db mapper config builder * * @return dynamo db mapper */ DynamoDBMapperConfig getDynamoDbMapperConfig() { return DynamoDBMapperConfig.builder().build(); }
/*** * Create a DynamoMapper repository. This defaults the SaveBehavior to {@link SaveBehavior#UPDATE} * * @param dynamoClient * @return mapperRepository - {@link DynamoMapperRepository} */ public static DynamoMapperRepository create(final AmazonDynamoDBClient dynamoClient) { return DynamoMapperRepository.create(dynamoClient, new DynamoDBMapperConfig(SaveBehavior.UPDATE)); }
/*** * Create a DynamoMapper repository * * @param dynamoClient - {@link AmazonDynamoDBClient} * @param config - {@link DynamoDBMapperConfig} * @return mapperRepository - {@link DynamoMapperRepository} */ public static DynamoMapperRepository create(final AmazonDynamoDBClient dynamoClient, final DynamoDBMapperConfig config) { final DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(dynamoClient); final DynamoMapperRepository mapperRepository = new DynamoMapperRepository(dynamoDBMapper); return mapperRepository; }
/** * Builds a database object mapper for a dynamodb table * * @param tableName * the name of the table * * @return DynamoDBMapper a new DynamoDB mapper for the targeted table */ private DynamoDBMapper getDbObjectMapper(String tableName) { DynamoDBMapperConfig.TableNameOverride override = new DynamoDBMapperConfig.TableNameOverride(tableName); DynamoDBMapperConfig config = new DynamoDBMapperConfig(override); return new com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper(getDynamoDBClient(), config); }