Java Code Examples for com.google.appengine.api.datastore.PreparedQuery#asList()

The following examples show how to use com.google.appengine.api.datastore.PreparedQuery#asList() . 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: TestReport.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the {@code TestReport} with the given build type id ordered by build id in the descendant order.
 *
 * @param buildTypeId      the build type id.
 * @param limit            the optional fetch limit, by default {@link com.google.appengine.tck.site.endpoints.TestReport#DEFAULT_FETCH_LIMIT}.
 * @param reports          the reports entry point
 * @return the matching test reports list or an empty one if none.
 */
@SuppressWarnings("unchecked")
public static List<TestReport> findByBuildTypeIdOrderByBuildIdDesc(String buildTypeId, Optional<Integer> limit, Reports reports) {
    final MemcacheService memcacheService = reports.getMemcacheService();
    List<TestReport> results = (List<TestReport>) memcacheService.get(buildTypeId);
    if (results == null) {
        final Filter buildTypeFilter = new Query.FilterPredicate("buildTypeId", FilterOperator.EQUAL, buildTypeId);
        final Query query = new Query(TEST_REPORT).setFilter(buildTypeFilter).addSort("buildId", DESCENDING);

        final DatastoreService datastoreService = reports.getDatastoreService();
        final PreparedQuery preparedQuery = datastoreService.prepare(query);
        final List<Entity> entities = preparedQuery.asList(FetchOptions.Builder.withLimit(limit.or(DEFAULT_FETCH_LIMIT)));

        results = new ArrayList<>();
        for (Entity oneEntity : entities) {
            final TestReport report = from(oneEntity);
            results.add(report);
        }

        memcacheService.put(buildTypeId, results);
    }
    return results;
}
 
Example 2
Source File: QueryFilteringByGAEPropertyTypesTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilterByEntityKey() {
    Entity parentEntity = createTestEntityWithUniqueMethodNameKey(TEST_ENTITY_KIND, "testFilterByEntityKey");
    Key parentKey = parentEntity.getKey();

    Key fooKey = KeyFactory.createKey(parentKey, "foo", 1);
    Entity fooEntity = new Entity(fooKey);
    service.put(fooEntity);

    Query query = new Query("foo")
        .setAncestor(parentKey)
        .setFilter(new Query.FilterPredicate(Entity.KEY_RESERVED_PROPERTY, EQUAL, fooKey));

    PreparedQuery preparedQuery = service.prepare(query);
    List<Entity> results = preparedQuery.asList(FetchOptions.Builder.withDefaults());

    assertEquals(1, results.size());
    assertEquals(fooEntity, results.get(0));
}
 
Example 3
Source File: QueryBasicsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryWithoutAnyConstraints() throws Exception {
    Key parentKey = createQueryBasicsTestParent("testQueryWithoutAnyConstraints");

    Entity person = new Entity("Person", parentKey);
    service.put(person);

    Entity address = new Entity("Address", parentKey);
    service.put(address);

    PreparedQuery preparedQuery = service.prepare(new Query().setAncestor(parentKey));
    assertTrue(preparedQuery.countEntities(withDefaults()) >= 2);

    List<Entity> results = preparedQuery.asList(withDefaults());
    assertTrue(results.containsAll(Arrays.asList(person, address)));
}
 
Example 4
Source File: GuestbookTestUtilities.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void cleanDatastore(DatastoreService ds, String book) {
  Query query =
      new Query("Greeting")
          .setAncestor(new KeyFactory.Builder("Guestbook", book).getKey())
          .setKeysOnly();
  PreparedQuery pq = ds.prepare(query);
  List<Entity> entities = pq.asList(FetchOptions.Builder.withDefaults());
  ArrayList<Key> keys = new ArrayList<>(entities.size());

  for (Entity e : entities) {
    keys.add(e.getKey());
  }
  ds.delete(keys);
}
 
Example 5
Source File: TransactionsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void usesForTransactions_readSnapshot() throws Exception {
  String boardName = "my-message-board";
  Entity b = new Entity("MessageBoard", boardName);
  b.setProperty("count", 13);
  datastore.put(b);

  // [START uses_for_transactions_3]
  DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

  // Display information about a message board and its first 10 messages.
  Key boardKey = KeyFactory.createKey("MessageBoard", boardName);

  Transaction txn = datastore.beginTransaction();

  Entity messageBoard = datastore.get(boardKey);
  long count = (Long) messageBoard.getProperty("count");

  Query q = new Query("Message", boardKey);

  // This is an ancestor query.
  PreparedQuery pq = datastore.prepare(txn, q);
  List<Entity> messages = pq.asList(FetchOptions.Builder.withLimit(10));

  txn.commit();
  // [END uses_for_transactions_3]

  assertWithMessage("board.count").that(count).isEqualTo(13L);
}
 
Example 6
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private List<Entity> getTallestPeople() {
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  Query q = new Query("Person").addSort("height", SortDirection.DESCENDING);

  PreparedQuery pq = datastore.prepare(q);
  return pq.asList(FetchOptions.Builder.withLimit(5));
}
 
Example 7
Source File: NotificationCleanupServlet.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
private void doCleanup() {
  log.log(Level.INFO, "Starting a job to clean up processed notification records");

  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  Calendar cutoffTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  cutoffTime.add(Calendar.HOUR, -HOURS_TO_KEEP_RECORDS_OF_PROCESSED_NOTIFICATIONS);

  Query query = new Query(Worker.PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND)
    .setFilter(new FilterPredicate("processedAt", FilterOperator.LESS_THAN, cutoffTime.getTime()))
    .setKeysOnly();

  PreparedQuery preparedQuery = datastore.prepare(query);

  // Delete in batches
  List<Entity> entitiesToBeDeleted = null;
  do {
    entitiesToBeDeleted = preparedQuery.asList(FetchOptions.Builder.withLimit(5));

    List<Key> keys = new ArrayList<Key>();

    for (Entity entity : entitiesToBeDeleted) {
      keys.add(entity.getKey());
    }

    datastore.delete(keys);
  } while (entitiesToBeDeleted.size() > 0);

  log.log(Level.INFO, "Finished a job to clean up processed notification records");
}
 
Example 8
Source File: NotificationCleanupServlet.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
private void doCleanup() {
  log.log(Level.INFO, "Starting a job to clean up processed notification records");

  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  Calendar cutoffTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  cutoffTime.add(Calendar.HOUR, -HOURS_TO_KEEP_RECORDS_OF_PROCESSED_NOTIFICATIONS);

  Query query = new Query(Worker.PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND)
    .setFilter(new FilterPredicate("processedAt", FilterOperator.LESS_THAN, cutoffTime.getTime()))
    .setKeysOnly();

  PreparedQuery preparedQuery = datastore.prepare(query);

  // Delete in batches
  List<Entity> entitiesToBeDeleted = null;
  do {
    entitiesToBeDeleted = preparedQuery.asList(FetchOptions.Builder.withLimit(5));

    List<Key> keys = new ArrayList<Key>();

    for (Entity entity : entitiesToBeDeleted) {
      keys.add(entity.getKey());
    }

    datastore.delete(keys);
  } while (entitiesToBeDeleted.size() > 0);

  log.log(Level.INFO, "Finished a job to clean up processed notification records");
}
 
Example 9
Source File: QueryOptimizationsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testProjectionOfCollectionProperties() throws Exception {
    String methodName = "testProjectionOfCollectionProperties";
    String entityKind = "test-proj";
    Entity parent = createTestEntityWithUniqueMethodNameKey(entityKind, methodName);
    Key key = parent.getKey();

    Entity e = createEntity(entityKind, key)
        .withProperty("prop", Arrays.asList("bbb", "ccc", "aaa"))
        .store();

    Query query = new Query(entityKind)
        .setAncestor(key)
        .addProjection(new PropertyProjection("prop", String.class))
        .addSort("prop");

    PreparedQuery preparedQuery = service.prepare(query);
    List<Entity> results = preparedQuery.asList(withDefaults());
    assertEquals(3, results.size());

    Entity firstResult = results.get(0);
    Entity secondResult = results.get(1);
    Entity thirdResult = results.get(2);

    assertEquals(e.getKey(), firstResult.getKey());
    assertEquals(e.getKey(), secondResult.getKey());
    assertEquals(e.getKey(), thirdResult.getKey());
    assertEquals("aaa", firstResult.getProperty("prop"));
    assertEquals("bbb", secondResult.getProperty("prop"));
    assertEquals("ccc", thirdResult.getProperty("prop"));
}
 
Example 10
Source File: QueryOptimizationsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testProjectionOfCollectionPropertyWithFilterOnCollectionProperty() throws Exception {
    String methodName = "testProjectionOfCollectionPropertyWithFilterOnCollectionProperty";
    Entity parent = createTestEntityWithUniqueMethodNameKey("Product", methodName);
    Key key = parent.getKey();

    Entity e = createEntity("Product", key)
        .withProperty("name", Arrays.asList("aaa", "bbb"))
        .withProperty("price", Arrays.asList(10L, 20L))
        .store();

    Query query = new Query("Product")
        .setAncestor(key)
        .addProjection(new PropertyProjection("name", String.class))
        .setFilter(new Query.FilterPredicate("price", GREATER_THAN, 0L))
        .addSort("price")
        .addSort("name");

    PreparedQuery preparedQuery = service.prepare(query);
    List<Entity> results = preparedQuery.asList(withDefaults());
    assertEquals(4, results.size());

    assertEquals(e.getKey(), results.get(0).getKey());
    assertEquals(e.getKey(), results.get(1).getKey());
    assertEquals(e.getKey(), results.get(2).getKey());
    assertEquals(e.getKey(), results.get(3).getKey());

    assertEquals("aaa", results.get(0).getProperty("name"));
    assertEquals("bbb", results.get(1).getProperty("name"));
    assertEquals("aaa", results.get(2).getProperty("name"));
    assertEquals("bbb", results.get(3).getProperty("name"));
}
 
Example 11
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private void assertIAEWhenAccessingList(PreparedQuery preparedQuery) {
    List<Entity> list = preparedQuery.asList(withDefaults());
    try {
        list.size();
        fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException ex) {
        // pass
    }
}
 
Example 12
Source File: QueryBasicsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilteringByKind() throws Exception {
    Key parentKey = createQueryBasicsTestParent("testFilteringByKind");
    Entity foo = createEntity("foo", parentKey).store();
    Entity bar = createEntity("bar", parentKey).store();

    PreparedQuery preparedQuery = service.prepare(new Query("foo").setAncestor(parentKey));
    List<Entity> results = preparedQuery.asList(withDefaults());
    assertEquals(1, results.size());
    assertEquals(foo, results.get(0));
}
 
Example 13
Source File: NotificationCleanupServlet.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 5 votes vote down vote up
private void doCleanup() {
  log.log(Level.INFO, "Starting a job to clean up processed notification records");
  
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  Calendar cutoffTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  cutoffTime.add(Calendar.HOUR, -HOURS_TO_KEEP_RECORDS_OF_PROCESSED_NOTIFICATIONS);
  
  Query query = new Query(PushNotificationWorker.PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND)
    .setFilter(new FilterPredicate("processedAt", FilterOperator.LESS_THAN, cutoffTime.getTime()))
    .setKeysOnly();
  
  PreparedQuery preparedQuery = datastore.prepare(query);

  // Delete in batches
  List<Entity> entitiesToBeDeleted = null;
  do {
    entitiesToBeDeleted = preparedQuery.asList(FetchOptions.Builder.withLimit(5));
    
    List<Key> keys = new ArrayList<Key>();
    
    for (Entity entity : entitiesToBeDeleted) {
      keys.add(entity.getKey());
    }
  
    datastore.delete(keys);
  } while (entitiesToBeDeleted.size() > 0);

  log.log(Level.INFO, "Finished a job to clean up processed notification records");
}
 
Example 14
Source File: RequiredIndexesTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
private void executeQuery(Query query) {
    PreparedQuery preparedQuery = service.prepare(query);
    List<Entity> list = preparedQuery.asList(withDefaults());
    list.size();    // only here is the query actually executed
}