com.google.cloud.datastore.StructuredQuery Java Examples

The following examples show how to use com.google.cloud.datastore.StructuredQuery. 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: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void findAllTestSort() {
	EntityQuery.Builder builder = Query.newEntityQueryBuilder().setKind("custom_test_kind");

	this.datastoreTemplate.findAll(TestEntity.class,
			new DatastoreQueryOptions.Builder().setSort(Sort.by("sortProperty"))
					.build());
	verify(this.datastore, times(1)).run(
			builder.setOrderBy(
					new StructuredQuery.OrderBy("prop", StructuredQuery.OrderBy.Direction.ASCENDING)).build());

	this.datastoreTemplate.findAll(TestEntity.class,
			new DatastoreQueryOptions.Builder()
					.setSort(Sort.by(Sort.Direction.DESC, "sortProperty")).build());
	verify(this.datastore, times(1)).run(
			builder.setOrderBy(
					new StructuredQuery.OrderBy("prop", StructuredQuery.OrderBy.Direction.DESCENDING)).build());
}
 
Example #2
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of running a query to find all entities with a matching property value. */
// [TARGET run(Query, ReadOption...)]
// [VARIABLE "my_kind"]
// [VARIABLE "my_property"]
// [VARIABLE "my_value"]
public List<Entity> runQueryOnProperty(String kind, String property, String value) {
  // TODO change so that it's not necessary to hold the entities in a list for integration testing
  // [START runQueryOnProperty]
  StructuredQuery<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind(kind)
          .setFilter(PropertyFilter.eq(property, value))
          .build();
  QueryResults<Entity> results = datastore.run(query);
  List<Entity> entities = Lists.newArrayList();
  while (results.hasNext()) {
    Entity result = results.next();
    // do something with result
    entities.add(result);
  }
  // [END runQueryOnProperty]
  return entities;
}
 
Example #3
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of running a query to find all entities of one kind. */
// [TARGET run(Query, ReadOption...)]
// [VARIABLE "my_kind"]
public List<Entity> runQuery(String kind) {
  // TODO change so that it's not necessary to hold the entities in a list for integration testing
  // [START runQuery]
  StructuredQuery<Entity> query = Query.newEntityQueryBuilder().setKind(kind).build();
  QueryResults<Entity> results = datastore.run(query);
  List<Entity> entities = Lists.newArrayList();
  while (results.hasNext()) {
    Entity result = results.next();
    // do something with result
    entities.add(result);
  }
  // [END runQuery]
  return entities;
}
 
Example #4
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes Datastore and cleans out any residual values.  Also initializes global variables
 * used for testing.
 */
@Before
public void setUp() {
  datastore = HELPER.getOptions().toBuilder().setNamespace("ghijklmnop").build().getService();
  StructuredQuery<Key> query = Query.newKeyQueryBuilder().build();
  QueryResults<Key> result = datastore.run(query);
  datastore.delete(Iterators.toArray(result, Key.class));
  keyFactory = datastore.newKeyFactory().setKind("Task");
  taskKey = keyFactory.newKey("some-arbitrary-key");
  testEntity = Entity.newBuilder(taskKey, TEST_FULL_ENTITY).build();
  Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  calendar.set(1990, JANUARY, 1);
  startDate = Timestamp.of(calendar.getTime());
  calendar.set(2000, JANUARY, 1);
  endDate = Timestamp.of(calendar.getTime());
  calendar.set(1999, DECEMBER, 31);
  includedDate = Timestamp.of(calendar.getTime());
}
 
Example #5
Source File: DatastoreStatsTest.java    From catatumbo with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetKindNs_Namespace_KindName() {
  final String namespace = "junit";
  final String kindName = "StringField";
  StatKindNs statEntity = stats.getKindNs(namespace, kindName);
  Query query = Query.newEntityQueryBuilder().setNamespace(namespace)
      .setKind(StatConstants.STAT_KIND_NS)
      .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName))
      .build();
  QueryResults<com.google.cloud.datastore.Entity> results = datastore.run(query);
  com.google.cloud.datastore.Entity nativeEntity = null;
  if (results.hasNext()) {
    nativeEntity = results.next();
  }
  assertTrue(equals(statEntity, nativeEntity));
}
 
Example #6
Source File: PartTreeDatastoreQuery.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
/**
 * In case the return type is a closed projection (only the projection fields are necessary
 * to construct an entity object), this method returns a {@link ProjectionEntityQuery.Builder}
 * with projection fields only.
 * Otherwise returns a {@link EntityQuery.Builder}.
 */
private Builder<?> getEntityOrProjectionQueryBuilder() {
	ProjectionInformation projectionInformation =
			this.projectionFactory.getProjectionInformation(this.queryMethod.getReturnedObjectType());

	if (projectionInformation != null &&
			projectionInformation.getType() != this.entityType
			&& projectionInformation.isClosed()) {
		ProjectionEntityQuery.Builder projectionEntityQueryBuilder = Query.newProjectionEntityQueryBuilder();
		projectionInformation.getInputProperties().forEach(
				propertyDescriptor ->
						projectionEntityQueryBuilder.addProjection(mapToFieldName(propertyDescriptor)));
		return projectionEntityQueryBuilder;
	}
	return StructuredQuery.newEntityQueryBuilder();
}
 
Example #7
Source File: PartTreeDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void nonCollectionReturnType() throws NoSuchMethodException {
	Trade trade = new Trade();
	queryWithMockResult("findByAction", null,
			getClass().getMethod("findByAction", String.class), true, null);

	Object[] params = new Object[] { "BUY", };

	when(this.datastoreTemplate.queryKeysOrEntities(any(), any())).thenAnswer((invocation) -> {
		EntityQuery statement = invocation.getArgument(0);

		EntityQuery expected = StructuredQuery.newEntityQueryBuilder()
				.setFilter(PropertyFilter.eq("action", "BUY"))
				.setKind("trades")
				.setLimit(1).build();

		assertThat(statement).isEqualTo(expected);

		List<Trade> results = Collections.singletonList(trade);
		return new DatastoreResultsIterable(results.iterator(), null);
	});

	assertThat(this.partTreeDatastoreQuery.execute(params)).isEqualTo(trade);
}
 
Example #8
Source File: PartTreeDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private void prepareDeleteResults(boolean isCollection) {
	Cursor cursor = Cursor.copyFrom("abc".getBytes());
	List<Integer> datastoreMatchingRecords = Arrays.asList(3, 4, 5);
	when(this.datastoreTemplate.queryKeysOrEntities(any(), any())).thenAnswer((invocation) -> {
		StructuredQuery<?> statement = invocation.getArgument(0);
		StructuredQuery.Builder builder = isCollection ? StructuredQuery.newEntityQueryBuilder()
				: StructuredQuery.newKeyQueryBuilder();
		StructuredQuery<?> expected = builder
				.setFilter(PropertyFilter.eq("action", "BUY"))
				.setKind("trades")
				.build();

		assertThat(statement).isEqualTo(expected);
		return new DatastoreResultsIterable(datastoreMatchingRecords.iterator(), cursor);
	});
}
 
Example #9
Source File: PartTreeDatastoreQuery.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private Slice executeSliceQuery(Object[] parameters) {
	StructuredQuery.Builder builder = getEntityOrProjectionQueryBuilder()
			.setKind(this.datastorePersistentEntity.kindName());
	StructuredQuery query = applyQueryBody(parameters, builder, false, false, null);
	DatastoreResultsIterable<?> resultList = this.datastoreOperations.queryKeysOrEntities(query, this.entityType);

	ParameterAccessor paramAccessor = new ParametersParameterAccessor(getQueryMethod().getParameters(), parameters);

	Pageable pageable = DatastorePageable.from(paramAccessor.getPageable(), resultList.getCursor(), null);

	EntityQuery.Builder builderNext = newEntityQueryBuilder().setKind(this.datastorePersistentEntity.kindName());
	StructuredQuery queryNext = applyQueryBody(parameters, builderNext, false, true, resultList.getCursor());
	Iterable nextResult = this.datastoreOperations.query(queryNext, x -> x);

	List<Object> result =
					StreamSupport.stream(resultList.spliterator(), false).collect(Collectors.toList());

	return (Slice) this.processRawObjectForProjection(
			new SliceImpl(result, pageable, nextResult.iterator().hasNext()));
}
 
Example #10
Source File: PartTreeDatastoreQuery.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
ExecutionOptions(Class returnedElementType, Class<?> collectionType, boolean requiresCount) {

			returnedTypeIsNumber = Number.class.isAssignableFrom(returnedElementType)
					|| returnedElementType == int.class || returnedElementType == long.class;

			isCountingQuery = PartTreeDatastoreQuery.this.tree.isCountProjection()
					|| (PartTreeDatastoreQuery.this.tree.isDelete() && returnedTypeIsNumber) || requiresCount;

			structuredQueryBuilder =
					!((isCountingQuery && !PartTreeDatastoreQuery.this.tree.isDelete())
							|| PartTreeDatastoreQuery.this.tree.isExistsProjection())
					&& !returnedTypeIsNumber
					? getEntityOrProjectionQueryBuilder()
					: StructuredQuery.newKeyQueryBuilder();

			structuredQueryBuilder.setKind(PartTreeDatastoreQuery.this.datastorePersistentEntity.kindName());

			singularResult = (!isCountingQuery && collectionType == null) && !PartTreeDatastoreQuery.this.tree.isDelete();
		}
 
Example #11
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void queryByExampleIncludeNullValuesTest() {
	EntityQuery.Builder builder = Query.newEntityQueryBuilder().setKind("test_kind");
	this.datastoreTemplate.queryByExample(
			Example.of(this.simpleTestEntityNullVallues,
					ExampleMatcher.matching().withIgnorePaths("id").withIncludeNullValues()),
			null);

	StructuredQuery.CompositeFilter filter = StructuredQuery.CompositeFilter
			.and(PropertyFilter.eq("color", NullValue.of()),
					PropertyFilter.eq("int_field", NullValue.of()));
	verify(this.datastore, times(1)).run(builder.setFilter(filter).build());
}
 
Example #12
Source File: MessageRepositoryImpl.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public List<Message> retrieve(int limit) {
  // Get Message saved in Datastore
  Datastore datastore = getDatastoreInstance();
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind(messagesKind)
          .setLimit(limit)
          .addOrderBy(StructuredQuery.OrderBy.desc("publishTime"))
          .build();
  QueryResults<Entity> results = datastore.run(query);

  List<Message> messages = new ArrayList<>();
  while (results.hasNext()) {
    Entity entity = results.next();
    Message message = new Message(entity.getString("messageId"));
    String data = entity.getString("data");
    if (data != null) {
      message.setData(data);
    }
    String publishTime = entity.getString("publishTime");
    if (publishTime != null) {
      message.setPublishTime(publishTime);
    }
    if (entity.contains("sourceLang")) {
      String sourceLang = entity.getString("sourceLang");
      if (sourceLang != null) {
        message.setSourceLang(sourceLang);
      }
    }
    if (entity.contains("targetLang")) {
      String targetLang = entity.getString("targetLang");
      if (targetLang != null) {
        message.setTargetLang(targetLang);
      }
    }
    messages.add(message);
  }
  return messages;
}
 
Example #13
Source File: MessageRepositoryImpl.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public List<Message> retrieve(int limit) {
  // Get Message saved in Datastore
  Datastore datastore = getDatastoreInstance();
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind(messagesKind)
          .setLimit(limit)
          .addOrderBy(StructuredQuery.OrderBy.desc("publishTime"))
          .build();
  QueryResults<Entity> results = datastore.run(query);

  List<Message> messages = new ArrayList<>();
  while (results.hasNext()) {
    Entity entity = results.next();
    Message message = new Message(entity.getString("messageId"));
    String data = entity.getString("data");
    if (data != null) {
      message.setData(data);
    }
    String publishTime = entity.getString("publishTime");
    if (publishTime != null) {
      message.setPublishTime(publishTime);
    }
    messages.add(message);
  }
  return messages;
}
 
Example #14
Source File: UserServiceTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  StructuredQuery<Key> query = Query.newKeyQueryBuilder().build();
  QueryResults<Key> result = DATASTORE.run(query);
  DATASTORE.delete(Iterators.toArray(result, Key.class));
  DATASTORE.add(USER_RECORD);
}
 
Example #15
Source File: MessageRepositoryImpl.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public List<Message> retrieve(int limit) {
  // Get Message saved in Datastore
  Datastore datastore = getDatastoreInstance();
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind(messagesKind)
          .setLimit(limit)
          .addOrderBy(StructuredQuery.OrderBy.desc("publishTime"))
          .build();
  QueryResults<Entity> results = datastore.run(query);

  List<Message> messages = new ArrayList<>();
  while (results.hasNext()) {
    Entity entity = results.next();
    Message message = new Message(entity.getString("messageId"));
    String data = entity.getString("data");
    if (data != null) {
      message.setData(data);
    }
    String publishTime = entity.getString("publishTime");
    if (publishTime != null) {
      message.setPublishTime(publishTime);
    }
    messages.add(message);
  }
  return messages;
}
 
Example #16
Source File: InstrumentedQueryResults.java    From styx with Apache License 2.0 5 votes vote down vote up
private static <T> String queryKind(Query<T> query) {
  final String kind;
  if (query instanceof StructuredQuery) {
    kind = ((StructuredQuery<T>) query).getKind();
  } else if (query instanceof GqlQuery) {
    kind = "<gql>";
  } else {
    kind = "<unknown>";
  }
  return kind;
}
 
Example #17
Source File: DatastoreTemplate.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
public static void applyQueryOptions(StructuredQuery.Builder builder, DatastoreQueryOptions queryOptions,
		DatastorePersistentEntity<?> persistentEntity) {
	if (persistentEntity.getDiscriminationFieldName() != null
			&& persistentEntity.getDiscriminatorValue() != null) {
		StructuredQuery.Filter discriminationFilter = PropertyFilter.eq(persistentEntity.getDiscriminationFieldName(),
				persistentEntity.getDiscriminatorValue());
		StructuredQuery.Filter filter = builder.build().getFilter();
		if (filter != null) {
			discriminationFilter = StructuredQuery.CompositeFilter.and(filter, discriminationFilter);
		}
		builder.setFilter(discriminationFilter);
	}
	if (queryOptions == null) {
		return;
	}
	if (queryOptions.getLimit() != null) {
		builder.setLimit(queryOptions.getLimit());
	}
	if (queryOptions.getCursor() == null && queryOptions.getOffset() != null) {
		builder.setOffset(queryOptions.getOffset());
	}
	if (queryOptions.getCursor() != null) {
		builder.setStartCursor(queryOptions.getCursor());
	}
	if (queryOptions.getSort() != null && persistentEntity != null) {
		queryOptions.getSort().stream()
				.map((order) -> createOrderBy(persistentEntity, order))
				.forEachOrdered((orderBy) -> builder.addOrderBy(orderBy));
	}
}
 
Example #18
Source File: DatastoreStatsTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetKindNs_KindName() {
  final String kindName = "StringField";
  StatKindNs statEntity = stats.getKindNs(kindName);
  Query query = Query.newEntityQueryBuilder().setKind(StatConstants.STAT_KIND_NS)
      .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName))
      .build();
  QueryResults<com.google.cloud.datastore.Entity> results = datastore.run(query);
  com.google.cloud.datastore.Entity nativeEntity = null;
  if (results.hasNext()) {
    nativeEntity = results.next();
  }
  assertTrue(equals(statEntity, nativeEntity));
}
 
Example #19
Source File: DatastoreStatsTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetKind() {
  final String kindName = "StringField";
  StatKind statEntity = stats.getKind(kindName);
  Query query = Query.newEntityQueryBuilder().setNamespace("").setKind(StatConstants.STAT_KIND)
      .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName))
      .build();
  QueryResults<com.google.cloud.datastore.Entity> results = datastore.run(query);
  com.google.cloud.datastore.Entity nativeEntity = null;
  if (results.hasNext()) {
    nativeEntity = results.next();
  }
  assertTrue(equals(statEntity, nativeEntity));

}
 
Example #20
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void queryByExampleOptions() {
	EntityQuery.Builder builder = Query.newEntityQueryBuilder().setKind("test_kind");
	this.datastoreTemplate.queryByExample(
			Example.of(this.simpleTestEntity, ExampleMatcher.matching().withIgnorePaths("id")),
			new DatastoreQueryOptions.Builder().setLimit(10).setOffset(1).setSort(Sort.by("intField"))
					.build());

	StructuredQuery.CompositeFilter filter = StructuredQuery.CompositeFilter
			.and(PropertyFilter.eq("color", "simple_test_color"),
					PropertyFilter.eq("int_field", 1));
	verify(this.datastore, times(1)).run(builder.setFilter(filter)
			.addOrderBy(StructuredQuery.OrderBy.asc("int_field")).setLimit(10).setOffset(1).build());
}
 
Example #21
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void queryByExampleIgnoreFieldTest() {
	EntityQuery.Builder builder = Query.newEntityQueryBuilder().setKind("test_kind");
	this.datastoreTemplate.queryByExample(
			Example.of(this.simpleTestEntity, ExampleMatcher.matching().withIgnorePaths("id", "intField")), null);

	StructuredQuery.CompositeFilter filter = StructuredQuery.CompositeFilter
			.and(PropertyFilter.eq("color", "simple_test_color"));
	verify(this.datastore, times(1)).run(builder.setFilter(filter).build());
}
 
Example #22
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void queryByExampleSimpleEntityTest() {
	EntityQuery.Builder builder = Query.newEntityQueryBuilder().setKind("test_kind");
	StructuredQuery.CompositeFilter filter = StructuredQuery.CompositeFilter
			.and(PropertyFilter.eq("color", "simple_test_color"),
					PropertyFilter.eq("int_field", 1));
	EntityQuery query = builder.setFilter(filter).build();
	verifyBeforeAndAfterEvents(null, new AfterQueryEvent(Collections.emptyList(), query),
			() -> this.datastoreTemplate.queryByExample(
					Example.of(this.simpleTestEntity, ExampleMatcher.matching().withIgnorePaths("id")), null),
			x -> x.verify(this.datastore, times(1)).run(query));
}
 
Example #23
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void findAllTestSortLimitOffset() {
	EntityQuery.Builder builder = Query.newEntityQueryBuilder().setKind("custom_test_kind");

	this.datastoreTemplate.findAll(TestEntity.class,
			new DatastoreQueryOptions.Builder().setLimit(2).setOffset(3)
					.setSort(Sort.by("sortProperty")).build());
	verify(this.datastore, times(1)).run(
			builder.setLimit(2).setOffset(3)
					.setOrderBy(
							new StructuredQuery.OrderBy("prop", StructuredQuery.OrderBy.Direction.ASCENDING))
					.build());
}
 
Example #24
Source File: DatastoreTemplate.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private static StructuredQuery.OrderBy createOrderBy(DatastorePersistentEntity<?> persistentEntity,
		Sort.Order order) {
	if (order.isIgnoreCase()) {
		throw new DatastoreDataException("Datastore doesn't support sorting ignoring case");
	}
	if (!order.getNullHandling().equals(Sort.NullHandling.NATIVE)) {
		throw new DatastoreDataException("Datastore supports only NullHandling.NATIVE null handling");
	}
	return new StructuredQuery.OrderBy(
			persistentEntity.getPersistentProperty(order.getProperty()).getFieldName(),
			(order.getDirection() == Sort.Direction.DESC)
					? StructuredQuery.OrderBy.Direction.DESCENDING
					: StructuredQuery.OrderBy.Direction.ASCENDING);
}
 
Example #25
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void combineFiltersDiscrimination() {
	PropertyFilter propertyFilter = PropertyFilter.eq("field", "some value");
	EntityQuery.Builder builder = Query.newEntityQueryBuilder().setKind("test_kind")
			.setFilter(propertyFilter);
	DatastoreTemplate.applyQueryOptions(builder,
			new DatastoreQueryOptions.Builder().setLimit(1).setOffset(2).build(),
			new DatastoreMappingContext().getPersistentEntity(SimpleDiscriminationTestEntity.class));

	assertThat(builder.build().getFilter()).isEqualTo(
			StructuredQuery.CompositeFilter.and(propertyFilter, PropertyFilter.eq("discrimination_field", "A")));

	assertThat(builder.build().getLimit()).isEqualTo(1);
	assertThat(builder.build().getOffset()).isEqualTo(2);
}
 
Example #26
Source File: PartTreeDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void usingIdField() throws NoSuchMethodException {
	Trade trade = new Trade();
	queryWithMockResult("findByActionAndId", null,
			getClass().getMethod("findByActionAndId", String.class, String.class), true, null);

	Object[] params = new Object[] { "BUY", "id1"};
	when(this.datastoreTemplate.createKey(eq("trades"), eq("id1")))
			.thenAnswer((invocation) ->
					Key.newBuilder("project", invocation.getArgument(0), invocation.getArgument(1)).build());

		when(this.datastoreTemplate.queryKeysOrEntities(any(), any())).thenAnswer((invocation) -> {
		EntityQuery statement = invocation.getArgument(0);

		EntityQuery expected = StructuredQuery.newEntityQueryBuilder()
				.setFilter(
						CompositeFilter.and(
								PropertyFilter.eq("action", "BUY"),
								PropertyFilter.eq("__key__",
										KeyValue.of(Key.newBuilder("project", "trades", "id1").build()))))
				.setKind("trades")
				.setLimit(1).build();

		assertThat(statement).isEqualTo(expected);

		List<Trade> results = Collections.singletonList(trade);
		return new DatastoreResultsIterable(results.iterator(), null);
	});

	assertThat(this.partTreeDatastoreQuery.execute(params)).isEqualTo(trade);
}
 
Example #27
Source File: PartTreeDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void compoundNameConventionTest() throws NoSuchMethodException {
	queryWithMockResult("findTop333ByActionAndSymbolAndPriceLessThan"
					+ "AndPriceGreaterThanEqual"
					+ "AndEmbeddedEntityStringFieldEquals"
					+ "AndIdIsNullOrderByIdDesc", null,
			getClass().getMethod("tradeMethod", String.class, String.class, double.class, double.class, String.class));

	Object[] params = new Object[] { "BUY", "abcd",
			// this int param requires custom conversion
			8, 3.33, "abc" };

	when(this.datastoreTemplate.queryKeysOrEntities(any(), any())).thenAnswer((invocation) -> {
		EntityQuery statement = invocation.getArgument(0);

		EntityQuery expected = StructuredQuery.newEntityQueryBuilder()
				.setFilter(CompositeFilter.and(PropertyFilter.eq("action", "BUY"),
						PropertyFilter.eq("ticker", "abcd"),
						PropertyFilter.lt("price", 8L),
						PropertyFilter.ge("price", 3.33),
						PropertyFilter.eq("embeddedEntity.stringField", "abc"),
						PropertyFilter.isNull("__key__")))
				.setKind("trades")
				.setOrderBy(OrderBy.desc("__key__")).setLimit(333).build();

		assertThat(statement).isEqualTo(expected);

		return EMPTY_RESPONSE;
	});

	when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class);

	this.partTreeDatastoreQuery.execute(params);
	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), any());
}
 
Example #28
Source File: PartTreeDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void pageableParam() throws NoSuchMethodException {
	queryWithMockResult("findByActionAndSymbolAndPriceLessThanAndPriceGreater"
			+ "ThanEqualAndIdIsNull", null,
			getClass().getMethod("tradeMethod", String.class, String.class, double.class, double.class,
					Pageable.class));

	Object[] params = new Object[] { "BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 444, Sort.Direction.DESC, "id") };

	when(this.datastoreTemplate.queryKeysOrEntities(any(), any())).thenAnswer((invocation) -> {
		EntityQuery statement = invocation.getArgument(0);

		EntityQuery expected = StructuredQuery.newEntityQueryBuilder()
				.setFilter(FILTER)
				.setKind("trades")
				.setOffset(444)
				.setOrderBy(OrderBy.desc("__key__")).setLimit(444).build();

		assertThat(statement).isEqualTo(expected);

		return EMPTY_RESPONSE;
	});

	when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class);

	this.partTreeDatastoreQuery.execute(params);
	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), any());
}
 
Example #29
Source File: PartTreeDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void nullSort() throws NoSuchMethodException {
	queryWithMockResult("findByActionAndSymbolAndPriceLessThanAndPriceGreater"
					+ "ThanEqualAndIdIsNullOrderByIdDesc", null,
			getClass().getMethod("tradeMethod", String.class, String.class, double.class, double.class,
					Sort.class));

	Object[] params = new Object[] { "BUY", "abcd", 8.88, 3.33, null };

	when(this.datastoreTemplate.queryKeysOrEntities(any(), any())).thenAnswer((invocation) -> {
		EntityQuery statement = invocation.getArgument(0);

		EntityQuery expected = StructuredQuery.newEntityQueryBuilder()
				.setFilter(FILTER)
				.setKind("trades")
				.setOrderBy(OrderBy.desc("__key__")).build();

		assertThat(statement).isEqualTo(expected);

		return EMPTY_RESPONSE;
	});

	when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class);

	this.partTreeDatastoreQuery.execute(params);
	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), any());
}
 
Example #30
Source File: PartTreeDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void ambiguousSort() throws NoSuchMethodException {
	queryWithMockResult("findByActionAndSymbolAndPriceLessThanAndPriceGreater"
			+ "ThanEqualAndIdIsNullOrderByIdDesc", null,
			getClass().getMethod("tradeMethod", String.class, String.class, double.class, double.class,
					Sort.class));

	Object[] params = new Object[] { "BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Direction.ASC, "price") };

	when(this.datastoreTemplate.queryKeysOrEntities(any(), any())).thenAnswer((invocation) -> {
		EntityQuery statement = invocation.getArgument(0);

		EntityQuery expected = StructuredQuery.newEntityQueryBuilder()
				.setFilter(FILTER)
				.setKind("trades")
				.setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")).build();

		assertThat(statement).isEqualTo(expected);

		return EMPTY_RESPONSE;
	});

	when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class);

	this.partTreeDatastoreQuery.execute(params);
	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), any());
}