software.amazon.awssdk.services.dynamodb.model.QueryResponse Java Examples

The following examples show how to use software.amazon.awssdk.services.dynamodb.model.QueryResponse. 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: AWSDynamoUtils.java    From para with Apache License 2.0 6 votes vote down vote up
private static QueryResponse queryGSI(String appid, Pager p) {
	Pager pager = (p != null) ? p : new Pager();
	GlobalSecondaryIndexDescription index = getSharedGlobalIndex();

	QueryRequest.Builder query = QueryRequest.builder().
			limit(pager.getLimit()).
			keyConditionExpression(Config._APPID + " = :aid").
			expressionAttributeValues(Collections.singletonMap(":aid", AttributeValue.builder().s(appid).build()));

	if (!StringUtils.isBlank(pager.getLastKey())) {
		// See https://stackoverflow.com/questions/40988397/42735813#42735813
		Map<String, AttributeValue> startKey = new HashMap<>(3);
		// HASH/PARTITION KEY
		startKey.put(Config._APPID, AttributeValue.builder().s(appid).build());
		// RANGE/SORT KEY
		startKey.put(Config._ID, AttributeValue.builder().s(pager.getLastKey()).build());
		// TABLE PRIMARY KEY
		startKey.put(Config._KEY, AttributeValue.builder().s(getKeyForAppid(pager.getLastKey(), appid)).build());
		query.exclusiveStartKey(startKey);
	}

	return index != null ? getClient().query(query.indexName(index.indexName()).
			tableName(getTableNameForAppid(SHARED_TABLE)).build()) : null;
}
 
Example #2
Source File: AWSDynamoUtils.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a page from a "shared" DynamoDB table. Shared tables are tables that have global secondary indexes
 * and can contain the objects of multiple apps.
 * @param <P> type of object
 * @param appid the app identifier (name)
 * @param pager a {@link Pager}
 * @return the id of the last object on the page, or null.
 */
public static <P extends ParaObject> List<P> readPageFromSharedTable(String appid, Pager pager) {
	LinkedList<P> results = new LinkedList<>();
	if (StringUtils.isBlank(appid)) {
		return results;
	}
	QueryResponse pages = queryGSI(appid, pager);
	if (pages != null) {
		for (Map<String, AttributeValue> item : pages.items()) {
			P obj = fromRow(item);
			if (obj != null) {
				results.add(obj);
			}
		}
	}
	if (!results.isEmpty() && pager != null) {
		pager.setLastKey(results.peekLast().getId());
	}
	return results;
}
 
Example #3
Source File: DynamoDBTest.java    From dynein with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetOverdueJobs_failure() {
  String partition = "test-partition";
  QueryRequest queryRequest = getQueryRequest(partition, JobStatus.SCHEDULED, Instant.now(clock));
  Exception exception = new Exception();

  CompletableFuture<QueryResponse> fut = new CompletableFuture<>();
  fut.completeExceptionally(exception);

  when(ddbClient.query(queryRequest)).thenReturn(fut);

  CompletableFuture<SchedulesQueryResponse> response = scheduleManager.getOverdueJobs(partition);
  assertSame(getException(response), exception);

  verify(ddbClient, times(1)).query(queryRequest);
  verifyNoMoreInteractions(ddbClient);
}
 
Example #4
Source File: DynamoDBPositionsStorage.java    From liiklus with MIT License 6 votes vote down vote up
@Override
public CompletionStage<Map<Integer, Map<Integer, Long>>> findAllVersionsByGroup(String topic, String groupName) {
    var request = QueryRequest.builder()
            .tableName(tableName)
            .keyConditions(ImmutableMap.of(
                    HASH_KEY_FIELD, condition(EQ, attribute(topic)),
                    RANGE_KEY_FIELD, condition(BEGINS_WITH, attribute(groupName))
            ))
            .build();

    return Flux
            .from(dynamoDB.queryPaginator(request))
            .flatMapIterable(QueryResponse::items)
            .map(item -> new AbstractMap.SimpleEntry<>(
                    GroupId.ofString(item.get("groupId").s()),
                    toPositions(item)
            ))
            .filter(it -> groupName.equals(it.getKey().getName()))
            .collectMap(
                    it -> it.getKey().getVersion().orElse(0),
                    Map.Entry::getValue
            )
            .toFuture();
}
 
Example #5
Source File: SecondaryIndexesIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void assertQueryResponseCount(Integer expected, QueryRequest request)
        throws InterruptedException {

    int retries = 0;
    QueryResponse result = null;
    do {
        result = dynamo.query(request);

        if (expected == result.count()) {
            return;
        }
        // Handling eventual consistency.
        Thread.sleep(SLEEP_TIME);
        retries++;
    } while (retries <= MAX_RETRIES);

    Assert.fail("Failed to assert query count. Expected : " + expected
                + " actual : " + result.count());
}
 
Example #6
Source File: QueryOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void transformResults_multipleItems_setsLastEvaluatedKey() {
    List<FakeItem> queryResultItems = generateFakeItemList();
    FakeItem lastEvaluatedKey = createUniqueFakeItem();
    List<Map<String, AttributeValue>> queryResultMaps =
        queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList());

    QueryResponse queryResponse = generateFakeQueryResults(queryResultMaps,
                                                           getAttributeValueMap(lastEvaluatedKey));

    Page<FakeItem> queryResultPage = queryOperation.transformResponse(queryResponse,
                                                                      FakeItem.getTableSchema(),
                                                                      PRIMARY_CONTEXT,
                                                                      null);

    assertThat(queryResultPage.lastEvaluatedKey(), is(getAttributeValueMap(lastEvaluatedKey)));
}
 
Example #7
Source File: QueryOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void getAsyncServiceCall_makesTheRightCallAndReturnsResponse() {
    QueryRequest queryRequest = QueryRequest.builder().build();
    QueryPublisher mockQueryPublisher = mock(QueryPublisher.class);
    when(mockDynamoDbAsyncClient.queryPaginator(any(QueryRequest.class))).thenReturn(mockQueryPublisher);

    SdkPublisher<QueryResponse> response =
        queryOperation.asyncServiceCall(mockDynamoDbAsyncClient).apply(queryRequest);

    assertThat(response, is(mockQueryPublisher));
    verify(mockDynamoDbAsyncClient).queryPaginator(queryRequest);
}
 
Example #8
Source File: AWSDynamoUtils.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes all objects in a shared table, which belong to a given appid, by scanning the GSI.
 * @param appid app id
 */
public static void deleteAllFromSharedTable(String appid) {
	if (StringUtils.isBlank(appid) || !isSharedAppid(appid)) {
		return;
	}
	Pager pager = new Pager(25);
	QueryResponse pages;
	Map<String, AttributeValue> lastKey = null;
	do {
		// read all phase
		pages = queryGSI(appid, pager);
		if (pages == null) {
			break;
		}
		List<WriteRequest> deletePage = new LinkedList<>();
		for (Map<String, AttributeValue> item : pages.items()) {
			String key = item.get(Config._KEY).s();
			// only delete rows which belong to the given appid
			if (StringUtils.startsWith(key, keyPrefix(appid))) {
				logger.debug("Preparing to delete '{}' from shared table, appid: '{}'.", key, appid);
				pager.setLastKey(item.get(Config._ID).s());
				deletePage.add(WriteRequest.builder().deleteRequest(b -> b.
						key(Collections.singletonMap(Config._KEY, AttributeValue.builder().s(key).
								build()))).build());
			}
		}
		lastKey = pages.lastEvaluatedKey();
		// delete all phase
		logger.info("Deleting {} items belonging to app '{}', from shared table...", deletePage.size(), appid);
		if (!deletePage.isEmpty()) {
			batchWrite(Collections.singletonMap(getTableNameForAppid(appid), deletePage), 1);
		}
	} while (lastKey != null && !lastKey.isEmpty());
}
 
Example #9
Source File: Query.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static int queryTable(DynamoDbClient ddb,
                             String tableName,
                             String partitionKeyName,
                             String partitionKeyVal,
                             String partitionAlias) {

    // Set up an alias for the partition key name in case it's a reserved word
    HashMap<String,String> attrNameAlias = new HashMap<String,String>();

    attrNameAlias.put(partitionAlias, partitionKeyName);

    // Set up mapping of the partition name with the value
    HashMap<String, AttributeValue> attrValues =
            new HashMap<String,AttributeValue>();
    attrValues.put(":"+partitionKeyName, AttributeValue.builder().s(partitionKeyVal).build());

    // Cretae a QueryRequest object
    QueryRequest queryReq = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(partitionAlias + " = :" + partitionKeyName)
            .expressionAttributeNames(attrNameAlias)
            .expressionAttributeValues(attrValues)
            .build();

    try {
        QueryResponse response = ddb.query(queryReq);
        return response.count();
    } catch (DynamoDbException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
   return -1;
}
 
Example #10
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 #11
Source File: QueryOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void queryItem_withExtension_correctlyTransformsItem() {
    List<FakeItem> queryResultItems = generateFakeItemList();
    List<FakeItem> modifiedResultItems = generateFakeItemList();

    List<Map<String, AttributeValue>> queryResultMap =
        queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList());

    ReadModification[] readModifications =
        modifiedResultItems.stream()
                          .map(QueryOperationTest::getAttributeValueMap)
                          .map(attributeMap -> ReadModification.builder().transformedItem(attributeMap).build())
                          .collect(Collectors.toList())
                          .toArray(new ReadModification[]{});

    when(mockDynamoDbEnhancedClientExtension.afterRead(any(DynamoDbExtensionContext.AfterRead.class)))
        .thenReturn(readModifications[0], Arrays.copyOfRange(readModifications, 1, readModifications.length));

    QueryResponse queryResponse = generateFakeQueryResults(queryResultMap);

    Page<FakeItem> queryResultPage = queryOperation.transformResponse(queryResponse,
                                                                      FakeItem.getTableSchema(),
                                                                      PRIMARY_CONTEXT,
                                                                      mockDynamoDbEnhancedClientExtension);

    assertThat(queryResultPage.items(), is(modifiedResultItems));
    InOrder inOrder = Mockito.inOrder(mockDynamoDbEnhancedClientExtension);
    queryResultMap.forEach(
        attributeMap -> inOrder.verify(mockDynamoDbEnhancedClientExtension)
                               .afterRead(
        DefaultDynamoDbExtensionContext.builder()
                                       .tableMetadata(FakeItem.getTableMetadata())
                                       .operationContext(PRIMARY_CONTEXT)
                                       .items(attributeMap).build()));
}
 
Example #12
Source File: QueryOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void transformResults_multipleItems_returnsCorrectItems() {
    List<FakeItem> queryResultItems = generateFakeItemList();
    List<Map<String, AttributeValue>> queryResultMaps =
        queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList());

    QueryResponse queryResponse = generateFakeQueryResults(queryResultMaps);

    Page<FakeItem> queryResultPage = queryOperation.transformResponse(queryResponse,
                                                                      FakeItem.getTableSchema(),
                                                                      PRIMARY_CONTEXT,
                                                                      null);

    assertThat(queryResultPage.items(), is(queryResultItems));
}
 
Example #13
Source File: ApplicationsService.java    From realworld-serverless-application with Apache License 2.0 5 votes vote down vote up
@Override
public ApplicationList listApplications(final String nextToken, final Integer maxItems) {
  log.info("Listing applications with nextToken {} and maxItems {}", nextToken, maxItems);
  Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
  expressionAttributeValues.put(":u", AttributeValue.builder()
        .s(securityContext.getUserPrincipal().getName())
        .build());

  QueryRequest.Builder requestBuilder = QueryRequest.builder()
        .consistentRead(true)
        .tableName(tableName)
        .keyConditionExpression(String.format("%s = :u",
              ApplicationRecord.USER_ID_ATTRIBUTE_NAME))
        .expressionAttributeValues(expressionAttributeValues)
        .limit(maxItems == null ? DEFAULT_LIST_APPLICATIONS_LIMIT : maxItems);
  if (nextToken != null) {
    try {
      requestBuilder.exclusiveStartKey(paginationTokenSerializer.deserialize(nextToken));
    } catch (InvalidTokenException e) {
      throw new BadRequestApiException(new BadRequestException()
            .errorCode("InvalidRequest")
            .message(String.format("NextToken %s is invalid.", nextToken)));
    }
  }
  QueryResponse queryResponse = dynamodb.query(requestBuilder.build());

  List<ApplicationSummary> applicationSummaries = queryResponse.items()
        .stream()
        .map(ApplicationRecord::new)
        .map(record -> modelMapper.map(record, ApplicationSummary.class))
        .collect(Collectors.toList());

  ApplicationList result = new ApplicationList()
        .applications(applicationSummaries);
  Map<String, AttributeValue> lastEvaluatedKey = queryResponse.lastEvaluatedKey();
  if (lastEvaluatedKey != null && !lastEvaluatedKey.isEmpty()) {
    result.nextToken(paginationTokenSerializer.serialize(lastEvaluatedKey));
  }
  return result;
}
 
Example #14
Source File: QueryOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void getServiceCall_makesTheRightCallAndReturnsResponse() {
    QueryRequest queryRequest = QueryRequest.builder().build();
    QueryIterable mockQueryIterable = mock(QueryIterable.class);
    when(mockDynamoDbClient.queryPaginator(any(QueryRequest.class))).thenReturn(mockQueryIterable);

    SdkIterable<QueryResponse> response = queryOperation.serviceCall(mockDynamoDbClient).apply(queryRequest);

    assertThat(response, is(mockQueryIterable));
    verify(mockDynamoDbClient).queryPaginator(queryRequest);
}
 
Example #15
Source File: QueryOperation.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Page<T> transformResponse(QueryResponse response,
                                 TableSchema<T> tableSchema,
                                 OperationContext context,
                                 DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) {

    return EnhancedClientUtils.readAndTransformPaginatedItems(response,
                                                              tableSchema,
                                                              context,
                                                              dynamoDbEnhancedClientExtension,
                                                              QueryResponse::items,
                                                              QueryResponse::lastEvaluatedKey);
}
 
Example #16
Source File: DynamoDBTest.java    From dynein with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetOverdueJobs_pagination() throws Exception {
  String partition = "test-partition";
  QueryRequest queryRequest = getQueryRequest(partition, JobStatus.SCHEDULED, Instant.now(clock));
  DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1");
  Schedule schedule = jobSpecToSchedule(jobSpec);

  List<Schedule> queryLimitSchedules = new ArrayList<>();

  for (int i = 0; i < ddbConfig.getQueryLimit() - 1; i++) {
    queryLimitSchedules.add(schedule);
  }

  QueryResponse queryResponse =
      QueryResponse.builder()
          .items(
              queryLimitSchedules
                  .stream()
                  .map(DynamoDBUtils::toAttributeMap)
                  .collect(Collectors.toList()))
          .count(ddbConfig.getQueryLimit() - 1)
          .lastEvaluatedKey(
              ImmutableMap.of("random", AttributeValue.builder().s("thing").build()))
          .build();

  when(ddbClient.query(queryRequest))
      .thenReturn(CompletableFuture.completedFuture(queryResponse));

  CompletableFuture<SchedulesQueryResponse> response = scheduleManager.getOverdueJobs(partition);
  Assert.assertEquals(
      response.get(1, TimeUnit.SECONDS), SchedulesQueryResponse.of(queryLimitSchedules, true));

  verify(ddbClient, times(1)).query(queryRequest);
  verifyNoMoreInteractions(ddbClient);
}
 
Example #17
Source File: DynamoDBTest.java    From dynein with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetOverdueJobs_queryLimit() throws Exception {
  String partition = "test-partition";
  QueryRequest queryRequest = getQueryRequest(partition, JobStatus.SCHEDULED, Instant.now(clock));
  DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1");
  Schedule schedule = jobSpecToSchedule(jobSpec);

  List<Schedule> queryLimitSchedules = new ArrayList<>();

  for (int i = 0; i < ddbConfig.getQueryLimit(); i++) {
    queryLimitSchedules.add(schedule);
  }

  QueryResponse queryResponse =
      QueryResponse.builder()
          .items(
              queryLimitSchedules
                  .stream()
                  .map(DynamoDBUtils::toAttributeMap)
                  .collect(Collectors.toList()))
          .count(ddbConfig.getQueryLimit())
          .lastEvaluatedKey(ImmutableMap.of())
          .build();

  when(ddbClient.query(queryRequest))
      .thenReturn(CompletableFuture.completedFuture(queryResponse));

  CompletableFuture<SchedulesQueryResponse> response = scheduleManager.getOverdueJobs(partition);
  Assert.assertEquals(
      response.get(1, TimeUnit.SECONDS), SchedulesQueryResponse.of(queryLimitSchedules, true));

  verify(ddbClient, times(1)).query(queryRequest);
  verifyNoMoreInteractions(ddbClient);
}
 
Example #18
Source File: DynamoDBTest.java    From dynein with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetOverdueJobs() throws Exception {
  String partition = "test-partition";
  QueryRequest queryRequest = getQueryRequest(partition, JobStatus.SCHEDULED, Instant.now(clock));
  DyneinJobSpec jobSpec1 = getTestJobSpec(validToken, "test1");
  Schedule schedule1 = jobSpecToSchedule(jobSpec1);
  DyneinJobSpec jobSpec2 = getTestJobSpec(getToken(4), "test2");
  Schedule schedule2 = jobSpecToSchedule(jobSpec2);

  QueryResponse queryResponse =
      QueryResponse.builder()
          .items(
              asList(
                  DynamoDBUtils.toAttributeMap(schedule1),
                  DynamoDBUtils.toAttributeMap(schedule2)))
          .count(2)
          .lastEvaluatedKey(ImmutableMap.of())
          .build();

  when(ddbClient.query(queryRequest))
      .thenReturn(CompletableFuture.completedFuture(queryResponse));

  CompletableFuture<SchedulesQueryResponse> response = scheduleManager.getOverdueJobs(partition);
  Assert.assertEquals(
      response.get(1, TimeUnit.SECONDS),
      SchedulesQueryResponse.of(asList(schedule1, schedule2), false));

  verify(ddbClient, times(1)).query(queryRequest);
  verifyNoMoreInteractions(ddbClient);
}
 
Example #19
Source File: ApplicationsServiceTest.java    From realworld-serverless-application with Apache License 2.0 5 votes vote down vote up
@Test
public void listApplications_maxItems() {
  String userId = UUID.randomUUID().toString();
  String applicationId = UUID.randomUUID().toString();
  Integer maxItems = ApplicationsService.DEFAULT_LIST_APPLICATIONS_LIMIT * 2;

  Map<String, AttributeValue> recordMap = keyMap(userId, applicationId);

  Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
  expressionAttributeValues.put(":u", AttributeValue.builder()
        .s(userId)
        .build());
  QueryRequest expectedQueryRequest = QueryRequest.builder()
        .consistentRead(true)
        .tableName(TABLE_NAME)
        .keyConditionExpression(String.format("%s = :u",
              ApplicationRecord.USER_ID_ATTRIBUTE_NAME))
        .expressionAttributeValues(expressionAttributeValues)
        .limit(maxItems)
        .build();

  QueryResponse queryResponse = QueryResponse.builder()
        .items(Collections.singletonList(recordMap))
        .build();
  when(principal.getName()).thenReturn(userId);
  when(dynamodb.query(any(QueryRequest.class))).thenReturn(queryResponse);

  ApplicationList applicationList = service.listApplications(null, maxItems);
  List<ApplicationSummary> applicationSummaries = applicationList.getApplications();

  ArgumentCaptor<QueryRequest> queryRequestArgumentCaptor = ArgumentCaptor.forClass(QueryRequest.class);
  verify(dynamodb).query(queryRequestArgumentCaptor.capture());
  assertThat(queryRequestArgumentCaptor.getValue()).isEqualTo(expectedQueryRequest);
  assertThat(applicationSummaries.get(0).getApplicationId()).isEqualTo(applicationId);
  assertThat(applicationList.getNextToken()).isNull();
}
 
Example #20
Source File: ApplicationsServiceTest.java    From realworld-serverless-application with Apache License 2.0 5 votes vote down vote up
@Test
public void listApplications() {
  String userId = UUID.randomUUID().toString();
  String applicationId = UUID.randomUUID().toString();

  Map<String, AttributeValue> recordMap = keyMap(userId, applicationId);

  Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
  expressionAttributeValues.put(":u", AttributeValue.builder()
        .s(userId)
        .build());
  QueryRequest expectedQueryRequest = QueryRequest.builder()
        .consistentRead(true)
        .tableName(TABLE_NAME)
        .keyConditionExpression(String.format("%s = :u",
              ApplicationRecord.USER_ID_ATTRIBUTE_NAME))
        .expressionAttributeValues(expressionAttributeValues)
        .limit(ApplicationsService.DEFAULT_LIST_APPLICATIONS_LIMIT)
        .build();

  QueryResponse queryResponse = QueryResponse.builder()
        .items(Collections.singletonList(recordMap))
        .build();
  when(principal.getName()).thenReturn(userId);
  when(dynamodb.query(any(QueryRequest.class))).thenReturn(queryResponse);

  ApplicationList applicationList = service.listApplications(null, null);
  List<ApplicationSummary> applicationSummaries = applicationList.getApplications();

  ArgumentCaptor<QueryRequest> queryRequestArgumentCaptor = ArgumentCaptor.forClass(QueryRequest.class);
  verify(dynamodb).query(queryRequestArgumentCaptor.capture());
  assertThat(queryRequestArgumentCaptor.getValue()).isEqualTo(expectedQueryRequest);
  assertThat(applicationSummaries.get(0).getApplicationId()).isEqualTo(applicationId);
  assertThat(applicationList.getNextToken()).isNull();
}
 
Example #21
Source File: QueryOperation.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public Function<QueryRequest, SdkPublisher<QueryResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient) {
    return dynamoDbAsyncClient::queryPaginator;
}
 
Example #22
Source File: QueryOperation.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public Function<QueryRequest, SdkIterable<QueryResponse>> serviceCall(DynamoDbClient dynamoDbClient) {
    return dynamoDbClient::queryPaginator;
}
 
Example #23
Source File: QueryOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private static QueryResponse generateFakeQueryResults(List<Map<String, AttributeValue>> queryItemMapsPage) {
    return QueryResponse.builder().items(queryItemMapsPage).build();
}
 
Example #24
Source File: QueryOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private static QueryResponse generateFakeQueryResults(List<Map<String, AttributeValue>> queryItemMapsPage,
                                                      Map<String, AttributeValue> lastEvaluatedKey) {
    return QueryResponse.builder().items(queryItemMapsPage).lastEvaluatedKey(lastEvaluatedKey).build();

}
 
Example #25
Source File: EnhancedClientQueryV1MapperComparisonBenchmark.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private static DynamoDbClient getV2Client(Blackhole bh, QueryResponse queryResponse) {
    return new V2TestDynamoDbQueryClient(bh, queryResponse);
}
 
Example #26
Source File: V2TestDynamoDbQueryClient.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
public V2TestDynamoDbQueryClient(Blackhole bh, QueryResponse queryResponse) {
    super(bh);
    this.queryResponse = queryResponse;
}
 
Example #27
Source File: V2TestDynamoDbQueryClient.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public QueryResponse query(QueryRequest queryRequest) {
    bh.consume(queryRequest);
    return this.queryResponse;
}
 
Example #28
Source File: LocalDynamoDb.java    From aws-dynamodb-encryption-java with Apache License 2.0 4 votes vote down vote up
@Override
public QueryResponse query(QueryRequest queryRequest) {
    return wrappedClient.query(queryRequest);
}
 
Example #29
Source File: ApplicationsServiceTest.java    From realworld-serverless-application with Apache License 2.0 4 votes vote down vote up
@Test
public void listApplications_nextToken() throws Exception {
  String userId = UUID.randomUUID().toString();
  String applicationId = UUID.randomUUID().toString();
  String nextToken = UUID.randomUUID().toString();

  Map<String, AttributeValue> recordMap = keyMap(userId, applicationId);

  Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
  expressionAttributeValues.put(":u", AttributeValue.builder()
        .s(userId)
        .build());
  QueryRequest expectedQueryRequest = QueryRequest.builder()
        .consistentRead(true)
        .tableName(TABLE_NAME)
        .keyConditionExpression(String.format("%s = :u",
              ApplicationRecord.USER_ID_ATTRIBUTE_NAME))
        .expressionAttributeValues(expressionAttributeValues)
        .limit(ApplicationsService.DEFAULT_LIST_APPLICATIONS_LIMIT)
        .exclusiveStartKey(recordMap)
        .build();

  QueryResponse queryResponse = QueryResponse.builder()
        .items(Collections.singletonList(recordMap))
        .lastEvaluatedKey(expressionAttributeValues)
        .build();
  when(principal.getName()).thenReturn(userId);
  when(dynamodb.query(any(QueryRequest.class))).thenReturn(queryResponse);
  when(tokenSerializer.deserialize(nextToken)).thenReturn(recordMap);
  when(tokenSerializer.serialize(expressionAttributeValues)).thenReturn(nextToken);

  ApplicationList applicationList = service.listApplications(nextToken, null);
  List<ApplicationSummary> applicationSummaries = applicationList.getApplications();

  ArgumentCaptor<QueryRequest> queryRequestArgumentCaptor = ArgumentCaptor.forClass(QueryRequest.class);
  verify(dynamodb).query(queryRequestArgumentCaptor.capture());
  verify(tokenSerializer).deserialize(nextToken);
  verify(tokenSerializer).serialize(expressionAttributeValues);
  assertThat(queryRequestArgumentCaptor.getValue()).isEqualTo(expectedQueryRequest);
  assertThat(applicationSummaries.get(0).getApplicationId()).isEqualTo(applicationId);
  assertThat(applicationList.getNextToken()).isEqualTo(nextToken);
}