private Platform getDevicePlatform(DynamoDBMapper mapper,String token) { Dispositivo d = mapper.load(Dispositivo.class, token); if(null==d) return null; if(d.getOs()==1) return Platform.APNS_SANDBOX; if(d.getOs()==2) return Platform.GCM; //Just for testing return Platform.APNS_SANDBOX; //return null; }
@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; } }
/** * Puts an object identified by a key * * @param key * @param obj */ @Override public void put(K key, T obj) { try { Object hashKey = getHashKey(key, obj); Object rangeKey = getRangeKey(key, obj); if (hashKey != null) { DynamoDBMapper mapper = new DynamoDBMapper( dynamoDBStoreHandler.getDynamoDbClient()); if (rangeKey != null) { mapper.load(persistentClass, hashKey, rangeKey); } else { mapper.load(persistentClass, hashKey); } mapper.save(obj); } else throw new GoraException("No HashKey found in Key nor in Object."); } catch (NullPointerException npe) { LOG.error("Error while putting an item. " + npe.toString()); throw new NullArgumentException(npe.getMessage()); } catch (Exception e) { LOG.error("Error while putting an item. " + obj.toString()); throw new RuntimeException(e); } }
private static void FindBooksPricedLessThanSpecifiedValue( DynamoDBMapper mapper, String value) throws Exception { System.out.println("FindBooksPricedLessThanSpecifiedValue: Scan ProductCatalog."); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); scanExpression.addFilterCondition("Price", new Condition() .withComparisonOperator(ComparisonOperator.LT) .withAttributeValueList(new AttributeValue().withN(value))); scanExpression.addFilterCondition("ProductCategory", new Condition() .withComparisonOperator(ComparisonOperator.EQ) .withAttributeValueList(new AttributeValue().withS("Book"))); List<Book> scanResult = mapper.scan(Book.class, scanExpression); for (Book book : scanResult) { System.out.println(book); } }
private static void FindBicyclesOfSpecificTypeWithMultipleThreads( DynamoDBMapper mapper, int numberOfThreads, String bicycleType) throws Exception { System.out.println("FindBicyclesOfSpecificTypeWithMultipleThreads: Scan ProductCatalog With Multiple Threads."); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); scanExpression.addFilterCondition("ProductCategory", new Condition() .withComparisonOperator(ComparisonOperator.EQ) .withAttributeValueList(new AttributeValue().withS("Bicycle"))); scanExpression.addFilterCondition("BicycleType", new Condition() .withComparisonOperator(ComparisonOperator.EQ) .withAttributeValueList(new AttributeValue().withS(bicycleType))); List<Bicycle> scanResult = mapper.parallelScan(Bicycle.class, scanExpression, numberOfThreads); for (Bicycle bicycle : scanResult) { System.out.println(bicycle); } }
public static void main(String[] args) throws Exception { try { DynamoDBMapper mapper = new DynamoDBMapper(client); testBatchSave(mapper); testBatchDelete(mapper); testBatchWrite(mapper); System.out.println("Example complete!"); } catch (Throwable t) { System.err.println("Error running the ObjectPersistenceBatchWriteExample: " + t); t.printStackTrace(); } }
@Before public void setup() throws NoSuchFieldException, IllegalAccessException { underTest = spy(new DynamoDbConfig(environment, awsKms)); when(underTest.encryptionTransformer(any(String.class))).thenReturn(transformer); when(underTest.tableNameOverrideConfig(any(String.class))).thenReturn(mapConfigNamed); when(underTest.getDynamoDbMapperConfig()).thenReturn(mapConfig); mockStatic(DynamoDBMapper.class); mockStatic(DynamoDbConfigFactory.class); MockitoAnnotations.initMocks(DynamoDbConfigTest.class); }
@Test public void dbMapperNoAudit() { when(environment.getProperty(eq(Constants.NO_AUDIT_ENV_VARIABLE))).thenReturn("true"); when(environment.getProperty(eq(Constants.DYNAMO_TABLE_NAME_ENV_VARIABLE))).thenReturn(null); when(environment.getProperty(eq(Constants.KMS_KEY_ENV_VARIABLE))).thenReturn(null); DynamoDBMapper dynamoDBMapper = underTest.dynamoDbMapper(amazonDynamoDB); assertThat(dynamoDBMapper).isNull(); }
@Before @Override public void setup() { super.setup(); final DynamoDBMapper mapper = new DynamoDBMapper(dynamodbClient); resourceTripleDao = new DynamoDBResourceTripleDao(mapper); addResourceData(); }
public static User addUser(DynamoDBMapper dbMapper, String firstName, String lastName, String address, String facebookId) { User user = new User(); user.setUserId(UUID.randomUUID().toString()); user.setFirstName(firstName); user.setLastName(lastName); if(address != null) user.setAddress(address); if(facebookId != null) user.setFacebookId(facebookId); dbMapper.save(user); return user; }
/** * generate dynamo db mapper etc. to connect to database */ private DBConnector() { AWSPropertiesProvider awsPropertiesProvider = new AWSPropertiesProvider("dynamoDb.properties"); AmazonDynamoDBClient dbClient = new AmazonDynamoDBClient(awsPropertiesProvider.getCredentials()); dbClient.setRegion(awsPropertiesProvider.getRegion()); dynamoDB = new DynamoDB(dbClient); dynamoDBMapper = new DynamoDBMapper(dbClient); }
public GenericDynamoDbDao(DynamoDbClientFactory clientFactory, Class<T> clazz) { DynamoDBTableMapper<T, K, ?> tableMapper = new DynamoDBMapper(clientFactory.client()).newTableMapper(clazz); log.info("Building table for " + clazz.getName()); boolean tableIfNotExists = tableMapper.createTableIfNotExists(new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)); log.info("table created?: "+tableIfNotExists); this.tableMapper = tableMapper; }
public GenericDynamoDbRangeDao(DynamoDbClientFactory clientFactory, Class<T> clazz) { DynamoDBTableMapper<T, K, R> tableMapper = new DynamoDBMapper(clientFactory.client()).newTableMapper(clazz); log.info("Building table for " + clazz.getName()); tableMapper.deleteTableIfExists(); tableMapper.createTableIfNotExists(new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)); this.tableMapper = tableMapper; }
@BeforeClass public static void beforeClass() { sDynamoDB = DynamoDBEmbedded.create().amazonDynamoDB(); sDynamoDBMapper = new DynamoDBMapper(sDynamoDB); sDynamoDBRepository = new DynamoDBRepository(); sDynamoDBRepository.setDynamoDBMapper(sDynamoDBMapper); sDynamoDBRepository.setLockDurationMs(LOCK_DURATION_MS); }
@Override public String handleRequest(Book request, Context context) { DynamoDBMapper mapper = new DynamoDBMapper(DynamoDBUtil.getClient()); mapper.save(request); return "success"; }
@Override public GatewayResponse handleRequest(GatewayRequest request, Context context) { DynamoDBMapper mapper = new DynamoDBMapper(DynamoDBUtil.getClient()); mapper.save(request.getBody()); return new GatewayResponse(200, request.getBody(), GatewayResponse.HEADERS_JSON); }
@PostConstruct public void connect(){ BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey, secretKey); AmazonDynamoDB client = AmazonDynamoDBAsyncClientBuilder .standard() .withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials)) .build(); dynamoDB = new DynamoDB(client); mapper = new DynamoDBMapper(client); }
@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()); }
@Override protected void configure() { bindFactory(AmazonCloudSearchFactory.class).to(AmazonCloudSearch.class).in(Singleton.class); bindFactory(AmazonDynamoDBFactory.class).to(AmazonDynamoDB.class).in(Singleton.class); bindFactory(AmazonS3ClientFactory.class).to(AmazonS3Client.class).in(Singleton.class); bindFactory(AWSCredentialsProviderFactory.class).to(AWSCredentialsProvider.class).in(Singleton.class); bindFactory(CurrentUserFactory.class).to(User.class).in(RequestScoped.class); bindFactory(DynamoDBConfigurationFactory.class).to(ClientConfiguration.class).in(Singleton.class); bindFactory(DynamoDBFactory.class).to(DynamoDB.class).in(Singleton.class); bindFactory(DynamoDBMapperFactory.class).to(DynamoDBMapper.class).in(Singleton.class); bindFactory(EnvFactory.class).to(Env.class).in(Singleton.class); bindFactory(ExecutorServiceFactory.class).to(ExecutorService.class).in(Singleton.class); bindFactory(ObjectMapperFactory.class).to(ObjectMapper.class).in(Singleton.class); bindFactory(WebRequestorFactory.class).to(WebRequestor.class).in(Singleton.class); }
@Test public void testProvide() { AmazonDynamoDB amazonDynamoDB = mock(AmazonDynamoDB.class); Env env = mock(Env.class); when(env.get("DYNAMODB_TABLE_PREFIX")).thenReturn(Optional.of("table")); DynamoDBMapperFactory factory = new DynamoDBMapperFactory(amazonDynamoDB, env); DynamoDBMapper mapper = factory.provide(); assertNotNull(mapper); factory.dispose(mapper); verify(env).get("DYNAMODB_TABLE_PREFIX"); }
protected AmazonDynamoDBDAO() { dynamoDB = new AmazonDynamoDBClient(new ClasspathPropertiesFileCredentialsProvider()); Region usWest2 = Region.getRegion(Regions.US_WEST_2); String local_db = EnvironmentUtils.getInstance().getLocal_db(); if (local_db != null && local_db.trim().length() > 0) { // LOCAL dynamoDB.setEndpoint(local_db,"local","us-west-2"); } else { // PROD dynamoDB.setRegion(usWest2); } mapper = new DynamoDBMapper(dynamoDB); }
private void init() { InstanceProfileCredentialsProvider credentialsProvider = new InstanceProfileCredentialsProvider(); AmazonDynamoDB amazonDynamoDB = new AmazonDynamoDBClient(credentialsProvider); amazonDynamoDB.setRegion(Regions.getCurrentRegion()); dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB, dynamoDBMapperConfig()); amazonS3 = new AmazonS3Client(credentialsProvider); Region current = Regions.getCurrentRegion(); if (!current.equals(Region.getRegion(Regions.US_EAST_1))) { amazonS3.setRegion(current); } systemUpgrade = new UpgradeSystemTo003(); }
public DynamoDBQuery(AmazonDynamoDB client, EntityPath<Q> entityPath) { this.queryMixin = new QueryMixin<DynamoDBQuery<Q>>(this, new DefaultQueryMetadata().noValidate()); this.client = client; this.mapper = new DynamoDBMapper(this.client); this.serializer = DynamodbSerializer.DEFAULT; this.entityPath = entityPath; }
@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); }
/** * Executes a query after building a DynamoDB specific query based on the * received one */ @Override public Result<K, T> execute(Query<K, T> query) { DynamoDBQuery<K, T> dynamoDBQuery = buildDynamoDBQuery(query); DynamoDBMapper mapper = new DynamoDBMapper( dynamoDBStoreHandler.getDynamoDbClient()); List<T> objList = null; if (DynamoDBQuery.getType().equals(DynamoDBQuery.RANGE_QUERY)) objList = mapper.scan(persistentClass, (DynamoDBScanExpression) dynamoDBQuery.getQueryExpression()); if (DynamoDBQuery.getType().equals(DynamoDBQuery.SCAN_QUERY)) objList = mapper.scan(persistentClass, (DynamoDBScanExpression) dynamoDBQuery.getQueryExpression()); return new DynamoDBResult<K, T>(this, query, objList); }
public FandomDAO() { client = new AmazonDynamoDBClient( new ClasspathPropertiesFileCredentialsProvider()); mapper = new DynamoDBMapper(client); Fandom test = mapper.load(Fandom.class, "fandoms"); if (test == null) { test = new Fandom(); test.setId("fandoms"); mapper.save(test); } }
public CraftDAO(){ client = new AmazonDynamoDBClient(new ClasspathPropertiesFileCredentialsProvider()); mapper = new DynamoDBMapper(client); Craft test = mapper.load(Craft.class, "crafts"); if(test == null){ test = new Craft(); test.setId("crafts"); mapper.save(test); } }
public static void main(String[] args) throws Exception { try { DynamoDBMapper mapper = new DynamoDBMapper(client); // Get a book - Id=101 GetBook(mapper, 101); // Sample forum and thread to test queries. String forumName = "Amazon DynamoDB"; String threadSubject = "DynamoDB Thread 1"; // Sample queries. FindRepliesInLast15Days(mapper, forumName, threadSubject); FindRepliesPostedWithinTimePeriod(mapper, forumName, threadSubject); // Scan a table and find book items priced less than specified value. FindBooksPricedLessThanSpecifiedValue(mapper, "20"); // Scan a table with multiple threads and find bicycle items with a specified bicycle type int numberOfThreads = 16; FindBicyclesOfSpecificTypeWithMultipleThreads(mapper, numberOfThreads, "Road"); System.out.println("Example complete!"); } catch (Throwable t) { System.err.println("Error running the ObjectPersistenceQueryScanExample: " + t); t.printStackTrace(); } }
private static void FindRepliesInLast15Days(DynamoDBMapper mapper, String forumName, String threadSubject) throws Exception { System.out.println("FindRepliesInLast15Days: Replies within last 15 days."); String hashKey = forumName + "#" + threadSubject; long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L); Date twoWeeksAgo = new Date(); twoWeeksAgo.setTime(twoWeeksAgoMilli); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); String twoWeeksAgoStr = dateFormatter.format(twoWeeksAgo); Condition rangeKeyCondition = new Condition() .withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr.toString())); Reply replyKey = new Reply(); replyKey.setId(hashKey); DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>() .withHashKeyValues(replyKey) .withRangeKeyCondition("ReplyDateTime", rangeKeyCondition); List<Reply> latestReplies = mapper.query(Reply.class, queryExpression); for (Reply reply : latestReplies) { System.out.format("Id=%s, Message=%s, PostedBy=%s %n, ReplyDateTime=%s %n", reply.getId(), reply.getMessage(), reply.getPostedBy(), reply.getReplyDateTime() ); } }
private static void FindRepliesPostedWithinTimePeriod( DynamoDBMapper mapper, String forumName, String threadSubject) throws Exception { String hashKey = forumName + "#" + threadSubject; System.out.println("FindRepliesPostedWithinTimePeriod: Find replies for thread Message = 'DynamoDB Thread 2' posted within a period."); long startDateMilli = (new Date()).getTime() - (14L*24L*60L*60L*1000L); // Two weeks ago. long endDateMilli = (new Date()).getTime() - (7L*24L*60L*60L*1000L); // One week ago. SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); String startDate = dateFormatter.format(startDateMilli); String endDate = dateFormatter.format(endDateMilli); Condition rangeKeyCondition = new Condition() .withComparisonOperator(ComparisonOperator.BETWEEN.toString()) .withAttributeValueList(new AttributeValue().withS(startDate), new AttributeValue().withS(endDate)); Reply replyKey = new Reply(); replyKey.setId(hashKey); DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>() .withHashKeyValues(replyKey) .withRangeKeyCondition("ReplyDateTime", rangeKeyCondition); List<Reply> betweenReplies = mapper.query(Reply.class, queryExpression); for (Reply reply : betweenReplies) { System.out.format("Id=%s, Message=%s, PostedBy=%s %n, PostedDateTime=%s %n", reply.getId(), reply.getMessage(), reply.getPostedBy(), reply.getReplyDateTime() ); } }
private static void testBatchSave(DynamoDBMapper mapper) { Book book1 = new Book(); book1.id = 901; book1.inPublication = true; book1.ISBN = "902-11-11-1111"; book1.pageCount = 100; book1.price = 10; book1.productCategory = "Book"; book1.title = "My book created in batch write"; Book book2 = new Book(); book2.id = 902; book2.inPublication = true; book2.ISBN = "902-11-12-1111"; book2.pageCount = 200; book2.price = 20; book2.productCategory = "Book"; book2.title = "My second book created in batch write"; Book book3 = new Book(); book3.id = 903; book3.inPublication = false; book3.ISBN = "902-11-13-1111"; book3.pageCount = 300; book3.price = 25; book3.productCategory = "Book"; book3.title = "My third book created in batch write"; System.out.println("Adding three books to ProductCatalog table."); mapper.batchSave(Arrays.asList(book1, book2, book3)); }
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)); }
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; } }