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

The following examples show how to use com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper. 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: ScanITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test(enabled = false)
public void testParallelScanExceptionHandling() {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    int INVALID_LIMIT = 0;
    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(INVALID_LIMIT);
    try {
        PaginatedParallelScanList<SimpleClass> parallelScanList = util.parallelScan(SimpleClass.class, scanExpression, PARALLEL_SCAN_SEGMENTS);
        fail("Should have seen the AmazonServiceException");
    } catch (AmazonServiceException ase) {
        assertNotNull(ase.getErrorCode());
        assertNotNull(ase.getErrorType());
        assertNotNull(ase.getMessage());
    } catch (Exception e) {
        fail("Should have seen the AmazonServiceException");
    }

}
 
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 testRangeKeyAutogenerated() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    RangeKeyAutoGenerated obj = new RangeKeyAutoGenerated();
    obj.setOtherAttribute("blah");
    obj.setKey("" + System.currentTimeMillis());

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

    RangeKeyAutoGenerated other = mapper.load(RangeKeyAutoGenerated.class, obj.getKey(), obj.getRangeKey());
    assertEquals(other, obj);
}
 
Example #3
Source File: ScanITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests scanning the table with AND/OR logic operator.
 */
@Test
public void testScanWithConditionalOperator() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
        .withLimit(SCAN_LIMIT)
        .withScanFilter(ImmutableMapParameter.of(
                "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL),
                "non-existent-field", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL)
                ))
        .withConditionalOperator(ConditionalOperator.AND);

    List<SimpleClass> andConditionResult = mapper.scan(SimpleClass.class, scanExpression);
    assertTrue(andConditionResult.isEmpty());

    List<SimpleClass> orConditionResult = mapper.scan(SimpleClass.class,
            scanExpression.withConditionalOperator(ConditionalOperator.OR));
    assertFalse(orConditionResult.isEmpty());
}
 
Example #4
Source File: AutoGeneratedKeysITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testHashKeyAutogenerated() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    HashKeyAutoGenerated obj = new HashKeyAutoGenerated();
    obj.setOtherAttribute("blah");
    obj.setRangeKey("" + System.currentTimeMillis());

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

    HashKeyAutoGenerated other = mapper.load(HashKeyAutoGenerated.class, obj.getKey(), obj.getRangeKey());
    assertEquals(other, obj);
}
 
Example #5
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 #6
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 #7
Source File: ScanITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test(enabled = false)
public void testParallelScanPerformance() throws Exception{
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(SCAN_LIMIT);
    scanExpression.addFilterCondition("value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString()));
    scanExpression.addFilterCondition("extraData", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString()));

    long startTime = System.currentTimeMillis();
    PaginatedScanList<SimpleClass> scanList = util.scan(SimpleClass.class, scanExpression);
    scanList.loadAllResults();
    long fullTableScanTime = System.currentTimeMillis() - startTime;
    startTime = System.currentTimeMillis();
    PaginatedParallelScanList<SimpleClass> parallelScanList = util.parallelScan(SimpleClass.class, scanExpression, PARALLEL_SCAN_SEGMENTS);
    parallelScanList.loadAllResults();
    long parallelScanTime = System.currentTimeMillis() - startTime;
    assertTrue(scanList.size() == parallelScanList.size());
    assertTrue(fullTableScanTime > parallelScanTime);
    System.out.println("fullTableScanTime : " + fullTableScanTime + "(ms), parallelScanTime : " + parallelScanTime + "(ms).");
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
Source File: ObjectPersistenceBatchWriteExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #13
Source File: DynamoDBPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Retry flushing data after creating table associated with mapper
 *
 * @param mapper mapper associated with the batch
 * @param batch original batch of data. Used for logging and to determine table name
 * @param failedBatch failed batch that should be retried
 */
private void retryFlushAfterCreatingTable(DynamoDBMapper mapper, Deque<DynamoDBItem<?>> batch,
        FailedBatch failedBatch) {
    logger.debug("Table was not found. Trying to create table and try saving again");
    if (createTable(mapper, batch.peek().getClass())) {
        logger.debug("Table creation successful, trying to save again");
        if (!failedBatch.getUnprocessedItems().isEmpty()) {
            ExponentialBackoffRetry retry = new ExponentialBackoffRetry(failedBatch.getUnprocessedItems());
            retry.run();
            if (retry.getUnprocessedItems().isEmpty()) {
                logger.debug("Successfully saved items after table creation");
            }
        }
    } else {
        logger.warn("Table creation failed. Not storing some parts of batch: {}. Unprocessed items: {}", batch,
                failedBatch.getUnprocessedItems());
    }
}
 
Example #14
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 #15
Source File: BinaryAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() throws Exception {
	// test BinaryAttributeClass
	BinaryAttributeByteBufferTestClass byteBufferObj = getUniqueByteBufferObject(contentLength);
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.save(byteBufferObj);

    util.delete(byteBufferObj);
    assertNull(util.load(BinaryAttributeByteBufferTestClass.class, byteBufferObj.getKey()));

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

    util.delete(bytesObj);
    assertNull(util.load(BinaryAttributeByteArrayTestClass.class, bytesObj.getKey()));

}
 
Example #16
Source File: DynamoDBMapperQueryScanExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void FindBooksPricedLessThanSpecifiedValue(DynamoDBMapper mapper, String value) throws Exception {

        System.out.println("FindBooksPricedLessThanSpecifiedValue: Scan ProductCatalog.");

        Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
        eav.put(":val1", new AttributeValue().withN(value));
        eav.put(":val2", new AttributeValue().withS("Book"));

        DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
            .withFilterExpression("Price < :val1 and ProductCategory = :val2").withExpressionAttributeValues(eav);

        List<Book> scanResult = mapper.scan(Book.class, scanExpression);

        for (Book book : scanResult) {
            System.out.println(book);
        }
    }
 
Example #17
Source File: AutoGeneratedKeysITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testHashKeyRangeKeyBothAutogeneratedBatchWrite() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    HashKeyRangeKeyBothAutoGenerated obj = new HashKeyRangeKeyBothAutoGenerated();
    obj.setOtherAttribute("blah");
    HashKeyRangeKeyBothAutoGenerated obj2 = new HashKeyRangeKeyBothAutoGenerated();
    obj2.setOtherAttribute("blah");

    assertNull(obj.getKey());
    assertNull(obj.getRangeKey());
    assertNull(obj2.getKey());
    assertNull(obj2.getRangeKey());
    mapper.batchSave(obj, obj2);
    assertNotNull(obj.getKey());
    assertNotNull(obj.getRangeKey());
    assertNotNull(obj2.getKey());
    assertNotNull(obj2.getRangeKey());

    assertEquals(mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj.getKey(),
            obj.getRangeKey()), obj);
    assertEquals(mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj2.getKey(),
            obj2.getRangeKey()), obj2);
}
 
Example #18
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 #19
Source File: RangeKeyAttributesITCase.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 ) {
        RangeKeyTestClass x = util.load(newRangeKey(Long.parseLong(attr.get(KEY_NAME).getN()),
                Double.parseDouble(attr.get(RANGE_KEY).getN())));

        // Convert all numbers to the most inclusive type for easy
        // comparison
        assertEquals(new BigDecimal(x.getKey()), new BigDecimal(attr.get(KEY_NAME).getN()));
        assertEquals(new BigDecimal(x.getRangeKey()), new BigDecimal(attr.get(RANGE_KEY).getN()));
        assertEquals(new BigDecimal(x.getVersion()), new BigDecimal(attr.get(VERSION_ATTRIBUTE).getN()));
        assertEquals(x.getBigDecimalAttribute(), new BigDecimal(attr.get(BIG_DECIMAL_ATTRIBUTE).getN()));
        assertNumericSetsEquals(x.getIntegerAttribute(), attr.get(INTEGER_ATTRIBUTE).getNS());
        assertEquals(x.getStringAttribute(), attr.get(STRING_ATTRIBUTE).getS());
        assertSetsEqual(x.getStringSetAttribute(), toSet(attr.get(STRING_SET_ATTRIBUTE).getSS()));
    }
}
 
Example #20
Source File: ProductInfoRepositoryIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@BeforeClass
public static void setupClass() {
    Properties testProperties = loadFromFileInClasspath("test.properties")
            .filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
            .filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
            .filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
            .orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));

    String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY);
    String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY);
    String amazonDynamoDBEndpoint = testProperties.getProperty(DYNAMODB_ENDPOINT);

    amazonDynamoDB = new AmazonDynamoDBClient(new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey));
    amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint);
    dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB);
}
 
Example #21
Source File: ObjectPersistenceQueryScanExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #22
Source File: DynamoDBMapperQueryScanExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
private static void FindRepliesPostedWithinTimePeriod(DynamoDBMapper mapper, String forumName, String threadSubject)
    throws Exception {
    String partitionKey = 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);

    Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
    eav.put(":val1", new AttributeValue().withS(partitionKey));
    eav.put(":val2", new AttributeValue().withS(startDate));
    eav.put(":val3", new AttributeValue().withS(endDate));

    DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>()
        .withKeyConditionExpression("Id = :val1 and ReplyDateTime between :val2 and :val3")
        .withExpressionAttributeValues(eav);

    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());
    }

}
 
Example #23
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 #24
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 #25
Source File: ScanITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testParallelScan() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(SCAN_LIMIT);
    scanExpression.addFilterCondition("value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString()));
    scanExpression.addFilterCondition("extraData", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString()));

    PaginatedParallelScanList<SimpleClass> parallelScanList = util.parallelScan(SimpleClass.class, scanExpression, PARALLEL_SCAN_SEGMENTS);
    int count = 0;
    Iterator<SimpleClass> iterator = parallelScanList.iterator();
    HashMap<String, Boolean> allDataAppearance = new HashMap<String, Boolean>();
    for (int i=0;i<500;i++) {
        allDataAppearance.put("" + i, false);
    }
    while (iterator.hasNext()) {
        count++;
        SimpleClass next = iterator.next();
        assertNotNull(next.getExtraData());
        assertNotNull(next.getValue());
        allDataAppearance.put(next.getId(), true);
    }
    assertFalse(allDataAppearance.values().contains(false));

    int totalCount = util.count(SimpleClass.class, scanExpression);

    assertNotNull(parallelScanList.get(totalCount / 2));
    assertTrue(totalCount == count);
    assertTrue(totalCount == parallelScanList.size());

    assertTrue(parallelScanList.contains(parallelScanList.get(parallelScanList.size() / 2)));
    assertTrue(count == parallelScanList.toArray().length);

}
 
Example #26
Source File: StringSetAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests saving only some attributes of an object.
 */
@Test
public void testIncompleteObject() {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);        

    StringSetAttributeTestClass obj = getUniqueObject();
    obj.setStringSetAttribute(null);
    util.save(obj);
    
    assertEquals(obj, util.load(StringSetAttributeTestClass.class, obj.getKey()));
    
    obj.setStringSetAttributeRenamed(null);
    util.save(obj);
    assertEquals(obj, util.load(StringSetAttributeTestClass.class, obj.getKey()));        
}
 
Example #27
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 testUnsupportedHashKeyType() {
    ComplexType complexType = new ComplexType("" + startKey++, new ComplexType("" + startKey++, null));
    ComplexHashKeyType obj = new ComplexHashKeyType();
    obj.setKey(complexType);
    obj.setAttribute("abc");
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    util.save(obj);
}
 
Example #28
Source File: StringSetAttributesITCase.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 ) {
        StringSetAttributeTestClass x = util.load(StringSetAttributeTestClass.class, attr.get(KEY_NAME).getS());
        assertEquals(x.getKey(), attr.get(KEY_NAME).getS());
        assertSetsEqual(x.getStringSetAttribute(), toSet(attr.get(STRING_SET_ATTRIBUTE).getSS()));
        assertSetsEqual(x.getStringSetAttributeRenamed(), toSet(attr.get(ORIGINAL_NAME_ATTRIBUTE).getSS()));
    }        
}
 
Example #29
Source File: BookPost.java    From serverless with Apache License 2.0 5 votes vote down vote up
@Override
public String handleRequest(Book request, Context context) {
	DynamoDBMapper mapper = new DynamoDBMapper(DynamoDBUtil.getClient());
	mapper.save(request);

	return "success";
}
 
Example #30
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());
}