Java Code Examples for com.google.cloud.datastore.QueryResults

The following examples show how to use com.google.cloud.datastore.QueryResults. These examples are extracted from open source projects. 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
/**
 * Removes all deleted blobs tracked in this index.
 *
 */
void removeData() {
  log.warn("removing all entries in the index of soft-deleted blobs...");
  Query<Entity> query = Query.newEntityQueryBuilder()
      .setNamespace(namespace)
      .setKind(DELETED_BLOBS)
      .build();
  QueryResults<Entity> results = gcsDatastore.run(query);
  List<Key> keys = StreamSupport.stream(
      Spliterators.spliteratorUnknownSize(results, Spliterator.ORDERED),
      false).map(entity -> entity.getKey()).collect(Collectors.toList());

  // datastore has a hard limit of 500 keys in a single delete
  List<List<Key>> partitions = Lists.partition(keys, 500);
  partitions.stream().forEach(partition -> gcsDatastore.delete(partition.toArray(new Key[partition.size()])) );

  log.warn("deleted {} blobIds from the soft-deleted blob index", keys.size());
}
 
Example 2
private Long getCount(String fieldName) {
  Transaction txn = datastore.newTransaction(
      TransactionOptions.newBuilder()
          .setReadOnly(ReadOnly.newBuilder().build())
          .build()
  );

  QueryResults<ProjectionEntity> results;
  try {
    Query<ProjectionEntity> countQuery = Query.newProjectionEntityQueryBuilder()
        .setKind(SHARD)
        .setNamespace(namespace)
        .setProjection(fieldName)
        .build();

    results = datastore.run(countQuery);
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(results, Spliterator.NONNULL), false)
        .map(entity -> Long.valueOf(entity.getLong(fieldName)))
        .reduce(0L, (valueA, valueB) -> valueA + valueB);
  } finally {
    if (txn.isActive()) {
      txn.rollback();
    }
  }
}
 
Example 3
Source Project: data-transfer-project   Source File: GoogleJobStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Finds the ID of the first {@link PortabilityJob} in state {@code jobState} in Datastore, or
 * null if none found.
 *
 * <p>TODO(rtannenbaum): Order by creation time so we can process jobs in a FIFO manner. Trying to
 * OrderBy.asc("created") currently fails because we don't yet have an index set up.
 */
@Override
public UUID findFirst(JobAuthorization.State jobState) {
  Query<Key> query =
      Query.newKeyQueryBuilder()
          .setKind(JOB_KIND)
          .setFilter(PropertyFilter.eq(PortabilityJob.AUTHORIZATION_STATE, jobState.name()))
          // .setOrderBy(OrderBy.asc("created"))
          .setLimit(1)
          .build();
  QueryResults<Key> results = datastore.run(query);
  if (!results.hasNext()) {
    return null;
  }
  Key key = results.next();
  return UUID.fromString(key.getName());
}
 
Example 4
Source Project: spring-cloud-gcp   Source File: DatastoreTemplateTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void deleteAllTest() {
	QueryResults<Key> queryResults = mock(QueryResults.class);
	when(queryResults.getResultClass()).thenReturn((Class) Key.class);
	doAnswer((invocation) -> {
		Arrays.asList(this.key1, this.key2).iterator()
				.forEachRemaining(invocation.getArgument(0));
		return null;
	}).when(queryResults).forEachRemaining(any());
	when(this.datastore
			.run(eq(Query.newKeyQueryBuilder().setKind("custom_test_kind").build())))
					.thenReturn(queryResults);

	verifyBeforeAndAfterEvents(
			new BeforeDeleteEvent(new Key[] { this.key1, this.key2 }, TestEntity.class, null, null),
			new AfterDeleteEvent(new Key[] { this.key1, this.key2 }, TestEntity.class, null, null),
			() -> assertThat(this.datastoreTemplate.deleteAll(TestEntity.class)).isEqualTo(2),
			x -> x.verify(this.datastore, times(1)).delete(same(this.key1), same(this.key2)));
}
 
Example 5
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of running a query to find all entities with an ancestor. */
// [TARGET run(Query)]
// [VARIABLE "my_parent_key_name"]
public List<Entity> run(String parentKeyName) {
  Datastore datastore = transaction.getDatastore();
  // [START run]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("ParentKind");
  Key parentKey = keyFactory.newKey(parentKeyName);
  // Build a query
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind("MyKind")
          .setFilter(PropertyFilter.hasAncestor(parentKey))
          .build();
  QueryResults<Entity> results = transaction.run(query);
  List<Entity> entities = Lists.newArrayList();
  while (results.hasNext()) {
    Entity result = results.next();
    // do something with result
    entities.add(result);
  }
  transaction.commit();
  // [END run]
  return entities;
}
 
Example 6
Source Project: catatumbo   Source File: DatastoreStatsTest.java    License: 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 7
Source Project: google-cloud-java   Source File: DatastoreSnippets.java    License: 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 8
Source Project: java-docs-samples   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void wipeDatastore() {
  Datastore datastore = getDatastore();
  QueryResults<Key> guestbooks =
      datastore.run(Query.newKeyQueryBuilder().setKind("Greeting").build());
  ArrayList<Key> keys = Lists.newArrayList(guestbooks);

  if (!keys.isEmpty()) {
    datastore.delete(keys.toArray(new Key[keys.size()]));
  }
}
 
Example 9
Source Project: styx   Source File: ShardedCounterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIncrementCounter() throws IOException {
  // init counter
  assertEquals(0, shardedCounter.getCounter(COUNTER_ID1));

  //increment counter by 1
  updateCounterInTransaction(COUNTER_ID1, 1L);

  QueryResults<Entity> results = datastore.run(EntityQuery.newEntityQueryBuilder()
      .setKind(KIND_COUNTER_SHARD)
      .setFilter(CompositeFilter.and(PropertyFilter.eq(PROPERTY_COUNTER_ID, COUNTER_ID1),
          PropertyFilter.eq(PROPERTY_SHARD_VALUE,1)))
      .build());
  // assert there's one and only one shard with the value set to 1
  assertEquals(1L, results.next().getLong(PROPERTY_SHARD_VALUE));
  assertFalse(results.hasNext());

  // assert the correct value is fetched after cache expiry
  shardedCounter.inMemSnapshot.invalidate(COUNTER_ID1);
  assertEquals(1L, shardedCounter.getCounter(COUNTER_ID1));
}
 
Example 10
Source Project: styx   Source File: ShardedCounterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeleteOnlySpecifiedCounterAndLimit() throws IOException {
  //init counter
  assertEquals(0L, shardedCounter.getCounter(COUNTER_ID1));
  assertEquals(0L, shardedCounter.getCounter(COUNTER_ID2));

  // create limit
  storage.runInTransactionWithRetries(transaction -> {
    shardedCounter.updateLimit(transaction, COUNTER_ID1, 10);
    shardedCounter.updateLimit(transaction, COUNTER_ID2, 10);
    return null;
  });

  storage.deleteResource(COUNTER_ID1);

  QueryResults<Entity> shardsCounter1 = getShardsForCounter(COUNTER_ID1);
  QueryResults<Entity> shardsCounter2 = getShardsForCounter(COUNTER_ID2);

  assertFalse(shardsCounter1.hasNext());
  assertNull(getLimitFromStorage(COUNTER_ID1));

  assertTrue(shardsCounter2.hasNext());
  assertNotNull(getLimitFromStorage(COUNTER_ID2));
}
 
Example 11
Source Project: styx   Source File: InstrumentedDatastoreTest.java    License: Apache License 2.0 6 votes vote down vote up
private <T extends BaseEntity<?>> void testInstrumentedQueryResults(QueryResults<T> instrumented,
    QueryResults<T> delegate) {
  when(delegate.hasNext()).thenReturn(true);
  when(delegate.next()).thenReturn((T) entity);
  when(delegate.getSkippedResults()).thenReturn(17);
  when(delegate.getMoreResults()).thenReturn(MORE_RESULTS_AFTER_CURSOR);
  assertThat(instrumented.hasNext(), is(true));
  verify(delegate).hasNext();
  assertThat(instrumented.next(), is(entity));
  verify(delegate).next();
  assertThat(instrumented.getSkippedResults(), is(17));
  assertThat(instrumented.getMoreResults(), is(MORE_RESULTS_AFTER_CURSOR));
  verify(delegate).getSkippedResults();
  verify(delegate).getMoreResults();
  verify(stats).recordDatastoreEntityReads(TEST_KIND, 1);
}
 
Example 12
Source Project: getting-started-java   Source File: DatastoreDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooks(String startCursorString) {
  Cursor startCursor = null;
  if (startCursorString != null && !startCursorString.equals("")) {
    startCursor = Cursor.fromUrlSafe(startCursorString);    // Where we left off
  }
  Query<Entity> query = Query.newEntityQueryBuilder()       // Build the Query
      .setKind("Book5")                                     // We only care about Books
      .setLimit(10)                                         // Only show 10 at a time
      .setStartCursor(startCursor)                          // Where we left off
      .setOrderBy(OrderBy.asc(Book.TITLE))                  // Use default Index "title"
      .build();
  QueryResults<Entity> resultList = datastore.run(query);   // Run the query
  List<Book> resultBooks = entitiesToBooks(resultList);     // Retrieve and convert Entities
  Cursor cursor = resultList.getCursorAfter();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toUrlSafe();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example 13
Source Project: getting-started-java   Source File: DatastoreDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooksByUser(String userId, String startCursorString) {
  Cursor startCursor = null;
  if (startCursorString != null && !startCursorString.equals("")) {
    startCursor = Cursor.fromUrlSafe(startCursorString);    // Where we left off
  }
  Query<Entity> query = Query.newEntityQueryBuilder()          // Build the Query
      .setKind("Book5")                                        // We only care about Books
      .setFilter(PropertyFilter.eq(Book.CREATED_BY_ID, userId))// Only for this user
      .setLimit(10)                                            // Only show 10 at a time
      .setStartCursor(startCursor)                             // Where we left off
      // a custom datastore index is required since you are filtering by one property
      // but ordering by another
      .setOrderBy(OrderBy.asc(Book.TITLE))
      .build();
  QueryResults<Entity> resultList = datastore.run(query);   // Run the Query
  List<Book> resultBooks = entitiesToBooks(resultList);     // Retrieve and convert Entities
  Cursor cursor = resultList.getCursorAfter();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toUrlSafe();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example 14
@Override
public void init(FilterConfig config) throws ServletException {
  // initialize local copy of datastore session variables

  datastore = DatastoreOptions.getDefaultInstance().getService();
  keyFactory = datastore.newKeyFactory().setKind("SessionVariable");
  // Delete all sessions unmodified for over two days
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  Query<Entity> query = Query.newEntityQueryBuilder()
      .setKind("SessionVariable")
      .setFilter(PropertyFilter.le("lastModified", dt.minusDays(2).toString(dtf)))
      .build();
  QueryResults<Entity> resultList = datastore.run(query);
  while (resultList.hasNext()) {
    Entity stateEntity = resultList.next();
    datastore.delete(stateEntity.getKey());
  }
}
 
Example 15
Source Project: getting-started-java   Source File: DatastoreDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooks(String startCursorString) {
  Cursor startCursor = null;
  if (startCursorString != null && !startCursorString.equals("")) {
    startCursor = Cursor.fromUrlSafe(startCursorString);    // Where we left off
  }
  Query<Entity> query = Query.newEntityQueryBuilder()       // Build the Query
      .setKind("Book2")                                     // We only care about Books
      .setLimit(10)                                         // Only show 10 at a time
      .setStartCursor(startCursor)                          // Where we left off
      .setOrderBy(OrderBy.asc(Book.TITLE))                  // Use default Index "title"
      .build();
  QueryResults<Entity> resultList = datastore.run(query);   // Run the query
  List<Book> resultBooks = entitiesToBooks(resultList);     // Retrieve and convert Entities
  Cursor cursor = resultList.getCursorAfter();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toUrlSafe();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example 16
Source Project: google-cloud-java   Source File: DatastoreSnippets.java    License: 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 17
protected void deleteSessionWithValue(String varName, String varValue) {
  Transaction transaction = datastore.newTransaction();
  try {
    Query<Entity> query = Query.newEntityQueryBuilder()
        .setKind("SessionVariable")
        .setFilter(PropertyFilter.eq(varName, varValue))
        .build();
    QueryResults<Entity> resultList = transaction.run(query);
    while (resultList.hasNext()) {
      Entity stateEntity = resultList.next();
      transaction.delete(stateEntity.getKey());
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 18
Source Project: getting-started-java   Source File: DatastoreDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooks(String startCursorString) {
  Cursor startCursor = null;
  if (startCursorString != null && !startCursorString.equals("")) {
    startCursor = Cursor.fromUrlSafe(startCursorString);    // Where we left off
  }
  Query<Entity> query = Query.newEntityQueryBuilder()       // Build the Query
      .setKind("Book3")                                     // We only care about Books
      .setLimit(10)                                         // Only show 10 at a time
      .setStartCursor(startCursor)                          // Where we left off
      .setOrderBy(OrderBy.asc(Book.TITLE))                  // Use default Index "title"
      .build();
  QueryResults<Entity> resultList = datastore.run(query);   // Run the query
  List<Book> resultBooks = entitiesToBooks(resultList);     // Retrieve and convert Entities
  Cursor cursor = resultList.getCursorAfter();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toUrlSafe();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example 19
@Override
public void init(FilterConfig config) throws ServletException {
  // initialize local copy of datastore session variables

  datastore = DatastoreOptions.getDefaultInstance().getService();
  keyFactory = datastore.newKeyFactory().setKind("SessionVariable");
  // Delete all sessions unmodified for over two days
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  Query<Entity> query = Query.newEntityQueryBuilder()
      .setKind("SessionVariable")
      .setFilter(PropertyFilter.le("lastModified", dt.minusDays(2).toString(dtf)))
      .build();
  QueryResults<Entity> resultList = datastore.run(query);
  while (resultList.hasNext()) {
    Entity stateEntity = resultList.next();
    datastore.delete(stateEntity.getKey());
  }
}
 
Example 20
protected void deleteSessionWithValue(String varName, String varValue) {
  Transaction transaction = datastore.newTransaction();
  try {
    Query<Entity> query = Query.newEntityQueryBuilder()
        .setKind("SessionVariable")
        .setFilter(PropertyFilter.eq(varName, varValue))
        .build();
    QueryResults<Entity> resultList = transaction.run(query);
    while (resultList.hasNext()) {
      Entity stateEntity = resultList.next();
      transaction.delete(stateEntity.getKey());
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 21
Source Project: getting-started-java   Source File: DatastoreDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooks(String startCursorString) {
  Cursor startCursor = null;
  if (startCursorString != null && !startCursorString.equals("")) {
    startCursor = Cursor.fromUrlSafe(startCursorString);    // Where we left off
  }
  Query<Entity> query = Query.newEntityQueryBuilder()       // Build the Query
      .setKind("Book4")                                     // We only care about Books
      .setLimit(10)                                         // Only show 10 at a time
      .setStartCursor(startCursor)                          // Where we left off
      .setOrderBy(OrderBy.asc(Book.TITLE))                  // Use default Index "title"
      .build();
  QueryResults<Entity> resultList = datastore.run(query);   // Run the query
  List<Book> resultBooks = entitiesToBooks(resultList);     // Retrieve and convert Entities
  Cursor cursor = resultList.getCursorAfter();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toUrlSafe();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example 22
Source Project: getting-started-java   Source File: DatastoreDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooksByUser(String userId, String startCursorString) {
  Cursor startCursor = null;
  if (startCursorString != null && !startCursorString.equals("")) {
    startCursor = Cursor.fromUrlSafe(startCursorString);    // Where we left off
  }
  Query<Entity> query = Query.newEntityQueryBuilder()          // Build the Query
      .setKind("Book4")                                        // We only care about Books
      .setFilter(PropertyFilter.eq(Book.CREATED_BY_ID, userId))// Only for this user
      .setLimit(10)                                            // Only show 10 at a time
      .setStartCursor(startCursor)                             // Where we left off
      // a custom datastore index is required since you are filtering by one property
      // but ordering by another
      .setOrderBy(OrderBy.asc(Book.TITLE))
      .build();
  QueryResults<Entity> resultList = datastore.run(query);   // Run the Query
  List<Book> resultBooks = entitiesToBooks(resultList);     // Retrieve and convert Entities
  Cursor cursor = resultList.getCursorAfter();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toUrlSafe();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example 23
@Override
public void init(FilterConfig config) throws ServletException {
  // initialize local copy of datastore session variables

  datastore = DatastoreOptions.getDefaultInstance().getService();
  keyFactory = datastore.newKeyFactory().setKind("SessionVariable");
  // Delete all sessions unmodified for over two days
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  Query<Entity> query = Query.newEntityQueryBuilder()
      .setKind("SessionVariable")
      .setFilter(PropertyFilter.le("lastModified", dt.minusDays(2).toString(dtf)))
      .build();
  QueryResults<Entity> resultList = datastore.run(query);
  while (resultList.hasNext()) {
    Entity stateEntity = resultList.next();
    datastore.delete(stateEntity.getKey());
  }
}
 
Example 24
protected void deleteSessionWithValue(String varName, String varValue) {
  Transaction transaction = datastore.newTransaction();
  try {
    Query<Entity> query = Query.newEntityQueryBuilder()
        .setKind("SessionVariable")
        .setFilter(PropertyFilter.eq(varName, varValue))
        .build();
    QueryResults<Entity> resultList = transaction.run(query);
    while (resultList.hasNext()) {
      Entity stateEntity = resultList.next();
      transaction.delete(stateEntity.getKey());
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 25
Source Project: tomcat-runtime   Source File: DatastoreStoreTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  store = new DatastoreStore();
  KeyFactory keyFactory = new KeyFactory("project").setKind("kind");
  key = keyFactory.newKey(keyId);
  attributeKey = keyFactory.newKey("attribute");
  QueryResults<Key> keyQueryResults = new IteratorQueryResults<>(ImmutableList.of(key).iterator());

  when(datastore.newKeyFactory()).thenAnswer((invocation) -> new KeyFactory("project"));
  when(datastore.run(any(KeyQuery.class))).thenReturn(keyQueryResults);

  when(manager.getContext()).thenReturn(new StandardContext());
  when(manager.willAttributeDistribute(anyString(), any())).thenReturn(true);
  when(manager.createEmptySession()).thenReturn(new DatastoreSession(manager));

  store.setDatastore(datastore);
  store.setClock(clock);
  store.setSessionKind("kind");
  store.setManager(manager);
}
 
Example 26
Source Project: java-docs-samples   Source File: ConceptsTest.java    License: 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 27
Source Project: java-docs-samples   Source File: ConceptsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRunProjectionQuery() {
  setUpQueryTests();
  Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder()
      .setKind("Task")
      .setProjection("priority", "percent_complete")
      .build();
  // [START datastore_run_query_projection]
  List<Long> priorities = new LinkedList<>();
  List<Double> percentCompletes = new LinkedList<>();
  QueryResults<ProjectionEntity> tasks = datastore.run(query);
  while (tasks.hasNext()) {
    ProjectionEntity task = tasks.next();
    priorities.add(task.getLong("priority"));
    percentCompletes.add(task.getDouble("percent_complete"));
  }
  // [END datastore_run_query_projection]
  assertEquals(ImmutableList.of(4L), priorities);
  assertEquals(ImmutableList.of(10.0), percentCompletes);
}
 
Example 28
Source Project: java-docs-samples   Source File: ConceptsTest.java    License: Apache License 2.0 6 votes vote down vote up
private Cursor cursorPaging(int pageSize, Cursor pageCursor) {
  // [START datastore_cursor_paging]
  EntityQuery.Builder queryBuilder = Query.newEntityQueryBuilder().setKind("Task")
      .setLimit(pageSize);
  if (pageCursor != null) {
    queryBuilder.setStartCursor(pageCursor);
  }
  QueryResults<Entity> tasks = datastore.run(queryBuilder.build());
  while (tasks.hasNext()) {
    Entity task = tasks.next();
    // do something with the task
  }
  Cursor nextPageCursor = tasks.getCursorAfter();
  // [END datastore_cursor_paging]
  return nextPageCursor;
}
 
Example 29
Source Project: java-docs-samples   Source File: ConceptsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNamespaceRunQuery() {
  setUpQueryTests();
  // [START datastore_namespace_run_query]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("__namespace__");
  Key startNamespace = keyFactory.newKey("g");
  Key endNamespace = keyFactory.newKey("h");
  Query<Key> query = Query.newKeyQueryBuilder()
      .setKind("__namespace__")
      .setFilter(CompositeFilter.and(
          PropertyFilter.gt("__key__", startNamespace),
          PropertyFilter.lt("__key__", endNamespace)))
      .build();
  List<String> namespaces = new ArrayList<>();
  QueryResults<Key> results = datastore.run(query);
  while (results.hasNext()) {
    namespaces.add(results.next().getName());
  }
  // [END datastore_namespace_run_query]
  assertEquals(ImmutableList.of("ghijklmnop"), namespaces);
}
 
Example 30
Source Project: java-docs-samples   Source File: ConceptsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertyRunQuery() {
  setUpQueryTests();
  // [START datastore_property_run_query]
  Query<Key> query = Query.newKeyQueryBuilder().setKind("__property__").build();
  QueryResults<Key> keys = datastore.run(query);
  Map<String, Collection<String>> propertiesByKind = new HashMap<>();
  while (keys.hasNext()) {
    Key key = keys.next();
    String kind = key.getParent().getName();
    String propertyName = key.getName();
    Collection<String> properties = propertiesByKind.get(kind);
    if (properties == null) {
      properties = new HashSet<>();
      propertiesByKind.put(kind, properties);
    }
    properties.add(propertyName);
  }
  // [END datastore_property_run_query]
  Map<String, ImmutableSet<String>> expected = ImmutableMap.of("Task", ImmutableSet.of(
      "done", "category", "done", "completed", "priority", "created", "percent_complete", "tag"));
  assertEquals(expected, propertiesByKind);
}