com.google.cloud.datastore.QueryResults Java Examples

The following examples show how to use com.google.cloud.datastore.QueryResults. 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: DeletedBlobIndex.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 7 votes vote down vote up
/**
 * 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
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 7 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 #3
Source File: TestUtils.java    From java-docs-samples with 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 #4
Source File: MessageRepositoryImpl.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> retrieveClaims(int limit) {
  // Get claim saved in Datastore
  Datastore datastore = getDatastoreInstance();
  Query<Entity> query = Query.newEntityQueryBuilder().setKind(claimsKind).setLimit(limit).build();
  QueryResults<Entity> results = datastore.run(query);

  List<String> claims = new ArrayList<>();
  while (results.hasNext()) {
    Entity entity = results.next();
    String claim = entity.getString("claim");
    if (claim != null) {
      claims.add(claim);
    }
  }
  return claims;
}
 
Example #5
Source File: ConceptsTest.java    From java-docs-samples with 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 #6
Source File: Guestbook.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public List<Greeting> getGreetings() {
  // This query requires the index defined in index.yaml to work because of the orderBy on date.
  EntityQuery query =
      Query.newEntityQueryBuilder()
          .setKind("Greeting")
          .setFilter(hasAncestor(key))
          .setOrderBy(desc("date"))
          .setLimit(5)
          .build();

  QueryResults<Entity> results = getDatastore().run(query);

  Builder<Greeting> resultListBuilder = ImmutableList.builder();
  while (results.hasNext()) {
    resultListBuilder.add(new Greeting(results.next()));
  }

  return resultListBuilder.build();
}
 
Example #7
Source File: GoogleJobStore.java    From data-transfer-project with 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 #8
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with 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 #9
Source File: TransactionSnippets.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 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 #10
Source File: ConceptsTest.java    From java-docs-samples with 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 #11
Source File: ConceptsTest.java    From java-docs-samples with 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);
}
 
Example #12
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 #13
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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 File: DatastoreDao.java    From getting-started-java with 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 #16
Source File: DatastoreDao.java    From getting-started-java with 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 #17
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 #18
Source File: DatastoreStoreTest.java    From tomcat-runtime with 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 #19
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
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 #20
Source File: ShardedCounterTest.java    From styx with 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 #21
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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 #22
Source File: ShardedCounterTest.java    From styx with 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 #23
Source File: DatastoreDao.java    From getting-started-java with 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 #24
Source File: InstrumentedDatastoreTest.java    From styx with 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 #25
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
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 #26
Source File: ShardedCounterMetricsStore.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 6 votes vote down vote up
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 #27
Source File: DatastoreDao.java    From getting-started-java with 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 #28
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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 #29
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 #30
Source File: DatastoreDao.java    From getting-started-java with 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);
  }
}