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

The following examples show how to use com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression. 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: StateModel.java    From eb-java-scorekeep with Apache License 2.0 7 votes vote down vote up
public List<State> loadStates(String sessionId, String gameId) throws SessionNotFoundException, GameNotFoundException {
  if ( sessionModel.loadSession(sessionId) == null ) {
    throw new SessionNotFoundException(sessionId);
  }
  if ( gameModel.loadGame(gameId) == null ) {
    throw new GameNotFoundException(gameId);
  }
  Map<String, AttributeValue> attributeValues = new HashMap<String, AttributeValue>();
  attributeValues.put(":val1", new AttributeValue().withS(gameId));

  Map<String, String> attributeNames = new HashMap<String, String>();
  attributeNames.put("#key1", "game");

  DynamoDBQueryExpression<State> queryExpression = new DynamoDBQueryExpression<State>()
      .withIndexName("game-index")
      .withExpressionAttributeValues(attributeValues)
      .withExpressionAttributeNames(attributeNames)
      .withKeyConditionExpression("#key1 = :val1")
      .withConsistentRead(false);

  List<State> gameStates = mapper.query(State.class, queryExpression);
  return gameStates;
}
 
Example #2
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 #3
Source File: IndexRangeKeyAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/** 
 * Tests the exception when user specifies an invalid index name in the query.
 */
@Test
public void testInvalidIndexNameException() {
	IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass();
	hashKeyItem.setKey(0);
	try {
		mapper.query(IndexRangeKeyTestClass.class,
				new DynamoDBQueryExpression<IndexRangeKeyTestClass>()
					.withHashKeyValues(hashKeyItem)
					.withRangeKeyCondition(INDEX_BAR_RANGE_KEY, 
							new Condition()
								.withAttributeValueList(new AttributeValue().withN("0"))
								.withComparisonOperator(ComparisonOperator.GE.toString()))
					.withIndexName("some_index"));
		fail("some_index is not a valid index name.");
	} catch (IllegalArgumentException iae) {
		System.out.println(iae.getMessage());
	} catch (Exception e) {
		fail("Should trigger an IllegalArgumentException.");
	}
}
 
Example #4
Source File: DynamoDBQueryUtils.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private static void maybeAddStateFilter(FilterCriteria filter,
        final DynamoDBQueryExpression<DynamoDBItem<?>> queryExpression) {
    if (filter.getOperator() != null && filter.getState() != null) {
        // Convert filter's state to DynamoDBItem in order get suitable string representation for the state
        final DynamoDBItem<?> filterState = AbstractDynamoDBItem.fromState(filter.getItemName(), filter.getState(),
                new Date());
        queryExpression.setFilterExpression(String.format("%s %s :opstate", DynamoDBItem.ATTRIBUTE_NAME_ITEMSTATE,
                operatorAsString(filter.getOperator())));

        filterState.accept(new DynamoDBItemVisitor() {

            @Override
            public void visit(DynamoDBStringItem dynamoStringItem) {
                queryExpression.setExpressionAttributeValues(
                        ImmutableMap.of(":opstate", new AttributeValue().withS(dynamoStringItem.getState())));
            }

            @Override
            public void visit(DynamoDBBigDecimalItem dynamoBigDecimalItem) {
                queryExpression.setExpressionAttributeValues(ImmutableMap.of(":opstate",
                        new AttributeValue().withN(dynamoBigDecimalItem.getState().toPlainString())));
            }
        });

    }
}
 
Example #5
Source File: AbstractDynamoDBQueryCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
protected void applySortIfSpecified(DynamoDBQueryExpression<T> queryExpression, List<String> permittedPropertyNames) {
	if (permittedPropertyNames.size() > 1) {
		throw new UnsupportedOperationException("Can only sort by at most a single range or index range key");

	}
	if (sort != null) {
		boolean sortAlreadySet = false;
		for (Order order : sort) {
			if (permittedPropertyNames.contains(order.getProperty())) {
				if (sortAlreadySet) {
					throw new UnsupportedOperationException("Sorting by multiple attributes not possible");

				}
				queryExpression.setScanIndexForward(order.getDirection().equals(Direction.ASC));
				sortAlreadySet = true;
			} else {
				throw new UnsupportedOperationException("Sorting only possible by " + permittedPropertyNames
						+ " for the criteria specified");
			}
		}
	}
}
 
Example #6
Source File: GameModel.java    From eb-java-scorekeep with Apache License 2.0 6 votes vote down vote up
public List<Game> loadGames(String sessionId) throws SessionNotFoundException {
  if ( sessionModel.loadSession(sessionId) == null ) {
    throw new SessionNotFoundException(sessionId);
  }
  Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
  eav.put(":val1", new AttributeValue().withS(sessionId));

  Map<String, String> ean = new HashMap<String, String>();
  ean.put("#key1", "session");

  DynamoDBQueryExpression<Game> queryExpression = new DynamoDBQueryExpression<Game>()
      .withIndexName("session-index")
      .withExpressionAttributeValues(eav)
      .withExpressionAttributeNames(ean)
      .withKeyConditionExpression("#key1 = :val1")
      .withConsistentRead(false);

  List<Game> sessionGames = mapper.query(Game.class, queryExpression);
  return sessionGames;
}
 
Example #7
Source File: MoveModel.java    From eb-java-scorekeep with Apache License 2.0 6 votes vote down vote up
public List<Move> loadMoves(String sessionId, String gameId) throws SessionNotFoundException, GameNotFoundException {
  if ( sessionModel.loadSession(sessionId) == null ) {
    throw new SessionNotFoundException(sessionId);
  }
  if ( gameModel.loadGame(gameId) == null ) {
    throw new GameNotFoundException(gameId);
  }
  Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
  eav.put(":val1", new AttributeValue().withS(gameId));

  Map<String, String> ean = new HashMap<String, String>();
  ean.put("#key1", "game");

  DynamoDBQueryExpression<Move> queryExpression = new DynamoDBQueryExpression<Move>()
  .withIndexName("game-index")
  .withExpressionAttributeValues(eav)
  .withExpressionAttributeNames(ean)
  .withKeyConditionExpression("#key1 = :val1")
  .withConsistentRead(false);

  List<Move> gameMoves = mapper.query(Move.class, queryExpression);
  return gameMoves;
}
 
Example #8
Source File: DynamoDBEventDao.java    From lambda-java8-dynamodb with Apache License 2.0 6 votes vote down vote up
@Override
public List<Event> findEventsByCity(String city) {

    Map<String, AttributeValue> eav = new HashMap<>();
    eav.put(":v1", new AttributeValue().withS(city));

    DynamoDBQueryExpression<Event> query = new DynamoDBQueryExpression<Event>()
                                                .withIndexName(Event.CITY_INDEX)
                                                .withConsistentRead(false)
                                                .withKeyConditionExpression("city = :v1")
                                                .withExpressionAttributeValues(eav);

    return mapper.query(Event.class, query);


    // NOTE:  without an index, this query would require a full table scan with a filter:
    /*
     DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
                                                .withFilterExpression("city = :val1")
                                                .withExpressionAttributeValues(eav);

     return mapper.scan(Event.class, scanExpression);
    */

}
 
Example #9
Source File: DynamoDBEntityWithHashAndRangeKeyCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
protected Query<T> buildFinderQuery(DynamoDBOperations dynamoDBOperations) {
	if (isApplicableForQuery()) {
		if (isApplicableForGlobalSecondaryIndex()) {
			String tableName = dynamoDBOperations.getOverriddenTableName(entityInformation.getDynamoDBTableName());
			QueryRequest queryRequest = buildQueryRequest(tableName, getGlobalSecondaryIndexName(),
					getHashKeyAttributeName(), getRangeKeyAttributeName(), this.getRangeKeyPropertyName(),
					getHashKeyConditions(), getRangeKeyConditions());
			return new MultipleEntityQueryRequestQuery<T>(dynamoDBOperations,entityInformation.getJavaType(), queryRequest);
		} else {
			DynamoDBQueryExpression<T> queryExpression = buildQueryExpression();
			return new MultipleEntityQueryExpressionQuery<T>(dynamoDBOperations, entityInformation.getJavaType(), queryExpression);
		}
	} else {
		return new MultipleEntityScanExpressionQuery<T>(dynamoDBOperations, clazz, buildScanExpression());
	}
}
 
Example #10
Source File: DynamoDBEntityWithHashAndRangeKeyCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
protected Query<Long> buildFinderCountQuery(DynamoDBOperations dynamoDBOperations,boolean pageQuery) {
	if (isApplicableForQuery()) {
		if (isApplicableForGlobalSecondaryIndex()) {
			String tableName = dynamoDBOperations.getOverriddenTableName(entityInformation.getDynamoDBTableName());
			QueryRequest queryRequest = buildQueryRequest(tableName, getGlobalSecondaryIndexName(),
					getHashKeyAttributeName(), getRangeKeyAttributeName(), this.getRangeKeyPropertyName(),
					getHashKeyConditions(), getRangeKeyConditions());
			return new QueryRequestCountQuery<T>(dynamoDBOperations,entityInformation.getJavaType(), queryRequest);
	
		} else {
			DynamoDBQueryExpression<T> queryExpression = buildQueryExpression();
			return new QueryExpressionCountQuery<T>(dynamoDBOperations, entityInformation.getJavaType(), queryExpression);
	
		}
	} else {
		return new ScanExpressionCountQuery<T>(dynamoDBOperations, clazz, buildScanExpression(),pageQuery);
	}
}
 
Example #11
Source File: DynamoDBTemplate.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
@Override
public <T> PaginatedQueryList<T> query(Class<T> domainClass,
		DynamoDBQueryExpression<T> queryExpression) {
	PaginatedQueryList<T> results = dynamoDBMapper.query(domainClass, queryExpression);
	maybeEmitEvent(new AfterQueryEvent<T>(results));
	return results;
}
 
Example #12
Source File: HashKeyOnlyTableWithGSIITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that we can query using the hash/range GSI on our hash-key only
 * table.
 */
@Test
public void testGSIQuery() throws Exception {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory
            .createDynamoDBMapper(dynamo);
    String status = "foo-status";

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

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

    PaginatedQueryList<User> query = mapper.query(User.class, expr);
    int size = query.size();
    if (DEBUG)
        System.err.println("size=" + size);
    assertTrue(1 == size);
    assertEquals(status, query.get(0).getStatus());
}
 
Example #13
Source File: PartTreeDynamoDBQueryUnitTest.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
// Sorting by range key when querying by indexrangekey not supported
@Test(expected=UnsupportedOperationException.class)
public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByHashKeyAndIndexRangeKey_OrderByRangeKey() {


	setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod,
			Playlist.class, "findByUserNameAndDisplayNameOrderByPlaylistNameDesc", 2, "userName", "playlistName");
	Set<String> indexRangeKeyPropertyNames = new HashSet<String>();
	indexRangeKeyPropertyNames.add("displayName");
	Mockito.when(mockPlaylistEntityMetadata.getIndexRangeKeyPropertyNames()).thenReturn(indexRangeKeyPropertyNames);
	Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true);
	Playlist prototypeHashKey = new Playlist();
	prototypeHashKey.setUserName("someUserName");
	Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn(
			prototypeHashKey);


	// Mock out specific DynamoDBOperations behavior expected by this method
	ArgumentCaptor<DynamoDBQueryExpression> queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class);
	ArgumentCaptor<Class> classCaptor = ArgumentCaptor.forClass(Class.class);
	Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist);
	Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1);
	Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn(
			mockPlaylistQueryResults);

	// Execute the query
	Object[] parameters = new Object[] { "someUserName","someDisplayName" };
	partTreeDynamoDBQuery.execute(parameters);


}
 
Example #14
Source File: MapperQueryExpressionCryptoTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testHashOnlyQueryOnHashRangeTable() {
    // Primary hash only query on a Hash+Range table
    QueryRequest queryRequest = testCreateQueryRequestFromExpression(
            LSIRangeKeyTestClass.class,
            new DynamoDBQueryExpression<LSIRangeKeyTestClass>()
                    .withHashKeyValues(new LSIRangeKeyTestClass("foo", null)));
    assertTrue(queryRequest.getKeyConditions().size() == 1);
    assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey"));
    assertNull(queryRequest.getIndexName());

    // Hash+Range query on a LSI
    queryRequest = testCreateQueryRequestFromExpression(
            LSIRangeKeyTestClass.class,
            new DynamoDBQueryExpression<LSIRangeKeyTestClass>()
                    .withHashKeyValues(new LSIRangeKeyTestClass("foo", null))
                    .withRangeKeyCondition("lsiRangeKey", RANGE_KEY_CONDITION)
                    .withIndexName("LSI"));
    assertTrue(queryRequest.getKeyConditions().size() == 2);
    assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey"));
    assertTrue(queryRequest.getKeyConditions().containsKey("lsiRangeKey"));
    assertEquals("LSI", queryRequest.getIndexName());

    // Hash-only query on a LSI
    queryRequest = testCreateQueryRequestFromExpression(
            LSIRangeKeyTestClass.class,
            new DynamoDBQueryExpression<LSIRangeKeyTestClass>()
                    .withHashKeyValues(new LSIRangeKeyTestClass("foo", null))
                    .withIndexName("LSI"));
    assertTrue(queryRequest.getKeyConditions().size() == 1);
    assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey"));
    assertEquals("LSI", queryRequest.getIndexName());
}
 
Example #15
Source File: PartTreeDynamoDBQueryUnitTest.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
// Can't sort by indexrangekey when querying by hash key only
@Test(expected=UnsupportedOperationException.class)
public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeIdWithHashKeyOnly_WhenSortingByIndexRangeKey() {
	PlaylistId playlistId = new PlaylistId();
	playlistId.setUserName("someUserName");

	setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod,
			Playlist.class, "findByPlaylistIdOrderByDisplayNameDesc", 1, "userName", "playlistName");
	Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true);
	Playlist prototypeHashKey = new Playlist();
	prototypeHashKey.setUserName("someUserName");
	Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn(
			prototypeHashKey);
	Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName");
	Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn(null);
	Set<String> indexRangeKeyPropertyNames = new HashSet<String>();
	indexRangeKeyPropertyNames.add("displayName");
	Mockito.when(mockPlaylistEntityMetadata.getIndexRangeKeyPropertyNames()).thenReturn(indexRangeKeyPropertyNames);

	// Mock out specific DynamoDBOperations behavior expected by this method
	ArgumentCaptor<DynamoDBQueryExpression> queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class);
	ArgumentCaptor<Class> classCaptor = ArgumentCaptor.forClass(Class.class);
	Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist);
	Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1);
	Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn(
			mockPlaylistQueryResults);

	// Execute the query
	Object[] parameters = new Object[] { playlistId };
	partTreeDynamoDBQuery.execute(parameters);


}
 
Example #16
Source File: PartTreeDynamoDBQueryUnitTest.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test(expected=UnsupportedOperationException.class)

public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByHashKeyAndIndexRangeKey_WithInvalidOrderSpecified() {


	setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod,
			Playlist.class, "findByUserNameAndDisplayNameOrderByPlaylistNameDesc", 2, "userName", "playlistName");
	Set<String> indexRangeKeyPropertyNames = new HashSet<String>();
	indexRangeKeyPropertyNames.add("displayName");
	Mockito.when(mockPlaylistEntityMetadata.getIndexRangeKeyPropertyNames()).thenReturn(indexRangeKeyPropertyNames);
	Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true);
	Playlist prototypeHashKey = new Playlist();
	prototypeHashKey.setUserName("someUserName");
	Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn(
			prototypeHashKey);


	// Mock out specific DynamoDBOperations behavior expected by this method
	ArgumentCaptor<DynamoDBQueryExpression> queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class);
	ArgumentCaptor<Class> classCaptor = ArgumentCaptor.forClass(Class.class);
	Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist);
	Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1);
	Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn(
			mockPlaylistQueryResults);

	// Execute the query
	Object[] parameters = new Object[] { "someUserName","someDisplayName" };
	partTreeDynamoDBQuery.execute(parameters);


}
 
Example #17
Source File: UserRepositoryDynamoDB.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
public Optional<User> getUserByCriteria(String indexName, User hashKeyValues) {

        DynamoDBQueryExpression<User> expression = new DynamoDBQueryExpression<User>()
                .withIndexName(indexName)
                .withConsistentRead(false)
                .withHashKeyValues(hashKeyValues);

        QueryResultPage<User> result = dynamoDBMapper.queryPage(User.class, expression);

        if (result.getCount() > 0) {
            return Optional.of(result.getResults().get(0));
        }

        return Optional.empty();
    }
 
Example #18
Source File: DynamoDBQueryUtils.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Construct dynamodb query from filter
 *
 * @param filter
 * @return DynamoDBQueryExpression corresponding to the given FilterCriteria
 */
public static DynamoDBQueryExpression<DynamoDBItem<?>> createQueryExpression(
        Class<? extends DynamoDBItem<?>> dtoClass, FilterCriteria filter) {
    DynamoDBItem<?> item = getDynamoDBHashKey(dtoClass, filter.getItemName());
    final DynamoDBQueryExpression<DynamoDBItem<?>> queryExpression = new DynamoDBQueryExpression<DynamoDBItem<?>>()
            .withHashKeyValues(item).withScanIndexForward(filter.getOrdering() == Ordering.ASCENDING)
            .withLimit(filter.getPageSize());
    maybeAddTimeFilter(queryExpression, filter);
    maybeAddStateFilter(filter, queryExpression);
    return queryExpression;
}
 
Example #19
Source File: DynamoDBQueryUtils.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static Condition maybeAddTimeFilter(final DynamoDBQueryExpression<DynamoDBItem<?>> queryExpression,
        final FilterCriteria filter) {
    final Condition timeCondition = constructTimeCondition(filter);
    if (timeCondition != null) {
        queryExpression.setRangeKeyConditions(
                Collections.singletonMap(DynamoDBItem.ATTRIBUTE_NAME_TIMEUTC, timeCondition));
    }
    return timeCondition;
}
 
Example #20
Source File: ObjectPersistenceQueryScanExample.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
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() );
 }
}
 
Example #21
Source File: ObjectPersistenceQueryScanExample.java    From aws-dynamodb-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 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() );
    }

}
 
Example #22
Source File: UserRepositoryDynamoDB.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
public Optional<User> getUserByCriteria(String indexName, User hashKeyValues) {

        DynamoDBQueryExpression<User> expression = new DynamoDBQueryExpression<User>()
                .withIndexName(indexName)
                .withConsistentRead(false)
                .withHashKeyValues(hashKeyValues);

        QueryResultPage<User> result = dynamoDBMapper.queryPage(User.class, expression);

        if (result.getCount() > 0) {
            return Optional.of(result.getResults().get(0));
        }

        return Optional.empty();
    }
 
Example #23
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 #24
Source File: DynamoDBMapperQueryScanExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
private static void FindRepliesInLast15Days(DynamoDBMapper mapper, String forumName, String threadSubject)
    throws Exception {
    System.out.println("FindRepliesInLast15Days: Replies within last 15 days.");

    String partitionKey = 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);

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

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

    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());
    }
}
 
Example #25
Source File: DynamoDBEventDao.java    From lambda-java8-dynamodb with Apache License 2.0 5 votes vote down vote up
@Override
public List<Event> findEventsByTeam(String team) {

    DynamoDBQueryExpression<Event> homeQuery = new DynamoDBQueryExpression<>();
    Event eventKey = new Event();
    eventKey.setHomeTeam(team);
    homeQuery.setHashKeyValues(eventKey);
    List<Event> homeEvents = mapper.query(Event.class, homeQuery);

    Map<String, AttributeValue> eav = new HashMap<>();
    eav.put(":v1", new AttributeValue().withS(team));
    DynamoDBQueryExpression<Event> awayQuery = new DynamoDBQueryExpression<Event>()
                                                    .withIndexName(Event.AWAY_TEAM_INDEX)
                                                    .withConsistentRead(false)
                                                    .withKeyConditionExpression("awayTeam = :v1")
                                                    .withExpressionAttributeValues(eav);

    List<Event> awayEvents = mapper.query(Event.class, awayQuery);

    // need to create a new list because PaginatedList from query is immutable
    List<Event> allEvents = new LinkedList<>();
    allEvents.addAll(homeEvents);
    allEvents.addAll(awayEvents);
    allEvents.sort( (e1, e2) -> e1.getEventDate() <= e2.getEventDate() ? -1 : 1 );

    return allEvents;
}
 
Example #26
Source File: EnhancedClientQueryV1MapperComparisonBenchmark.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
TestItem(TableSchema<?> schema,
         QueryResponse v2Response,

         Class<?> v1BeanClass,
         DynamoDBQueryExpression v1QueryExpression,
         QueryResult v1Response) {
    this.schema = schema;
    this.v2Response = v2Response;

    this.v1BeanClass = v1BeanClass;
    this.v1QueryExpression = v1QueryExpression;
    this.v1Response = v1Response;
}
 
Example #27
Source File: QueryITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that exception should be raised when user provides an index name
 * when making query with the primary range key.
 */
@Test
public void testUnnecessaryIndexNameException() {
    try {
        DynamoDBMapper mapper = TestDynamoDBMapperFactory
                .createDynamoDBMapper(dynamo);
        long hashKey = System.currentTimeMillis();
        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(11).withIndexName("some_index");
        mapper.query(RangeKeyTestClass.class, queryExpression);
        fail("User should not provide index name when making query with the primary range key");
    } catch (IllegalArgumentException expected) {
        System.out.println(expected.getMessage());
    } catch (Exception e) {
        fail("Should trigger AmazonClientException.");
    }

}
 
Example #28
Source File: UserRepositoryDynamoDB.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
public Optional<User> getUserByCriteria(String indexName, User hashKeyValues) {

        DynamoDBQueryExpression<User> expression = new DynamoDBQueryExpression<User>()
                .withIndexName(indexName)
                .withConsistentRead(false)
                .withHashKeyValues(hashKeyValues);

        QueryResultPage<User> result = dynamoDBMapper.queryPage(User.class, expression);

        if (result.getCount() > 0) {
            return Optional.of(result.getResults().get(0));
        }

        return Optional.empty();
    }
 
Example #29
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 #30
Source File: UserRepositoryDynamoDB.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
public Optional<User> getUserByCriteria(String indexName, User hashKeyValues) {

        DynamoDBQueryExpression<User> expression = new DynamoDBQueryExpression<User>()
                .withIndexName(indexName)
                .withConsistentRead(false)
                .withHashKeyValues(hashKeyValues);

        QueryResultPage<User> result = dynamoDBMapper.queryPage(User.class, expression);

        if (result.getCount() > 0) {
            return Optional.of(result.getResults().get(0));
        }

        return Optional.empty();
    }