com.google.appengine.api.datastore.Query.FilterPredicate Java Examples

The following examples show how to use com.google.appengine.api.datastore.Query.FilterPredicate. 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: QueriesTest.java    From java-docs-samples with Apache License 2.0 9 votes vote down vote up
@Test
public void queryInterface_orFilter_printsMatchedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("height", 100);
  Entity b = new Entity("Person", "b");
  b.setProperty("height", 150);
  Entity c = new Entity("Person", "c");
  c.setProperty("height", 200);
  datastore.put(ImmutableList.<Entity>of(a, b, c));

  StringWriter buf = new StringWriter();
  PrintWriter out = new PrintWriter(buf);
  long minHeight = 125;
  long maxHeight = 175;

  // Act
  // [START gae_java8_datastore_interface_3]
  Filter tooShortFilter = new FilterPredicate("height", FilterOperator.LESS_THAN, minHeight);

  Filter tooTallFilter = new FilterPredicate("height", FilterOperator.GREATER_THAN, maxHeight);

  Filter heightOutOfRangeFilter = CompositeFilterOperator.or(tooShortFilter, tooTallFilter);

  Query q = new Query("Person").setFilter(heightOutOfRangeFilter);
  // [END gae_java8_datastore_interface_3]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).containsExactly(a, c);
}
 
Example #2
Source File: CachingService.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Account key associated with the specified authorization key.
 * @param pm               reference to the persistence manager
 * @param authorizationKey authorization key to return the account key for
 * @return the Account key associated with the specified authorization key; or <code>null</code> if the authorization key is invalid
 */
public static Key getAccountKeyByAuthKey( final PersistenceManager pm, final String authorizationKey ) {
	final String memcacheKey = CACHE_KEY_AUTH_KEY_ACCOUNT_KEY_PREFIX + authorizationKey;
	final String accountKeyString = (String) memcacheService.get( memcacheKey );
	if ( accountKeyString != null )
		return KeyFactory.stringToKey( accountKeyString );
	
	final Query q = new Query( Account.class.getSimpleName() );
	q.setFilter( new FilterPredicate( "authorizationKey", FilterOperator.EQUAL, authorizationKey ) );
	q.setKeysOnly();
	final List< Entity > entityList = DatastoreServiceFactory.getDatastoreService().prepare( q ).asList( FetchOptions.Builder.withDefaults() );
	if ( entityList.isEmpty() )
		return null;
	
	final Key accountKey = entityList.get( 0 ).getKey();
	try {
		memcacheService.put( memcacheKey, KeyFactory.keyToString( accountKey ) );
	}
	catch ( final MemcacheServiceException mse ) {
		LOGGER.log( Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse );
		// Ignore memcache errors, do not prevent serving user request
	}
	
	return accountKey;
}
 
Example #3
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void propertyFilterExample_returnsMatchingEntities() throws Exception {
  // Arrange
  Entity p1 = new Entity("Person");
  p1.setProperty("height", 120);
  Entity p2 = new Entity("Person");
  p2.setProperty("height", 180);
  Entity p3 = new Entity("Person");
  p3.setProperty("height", 160);
  datastore.put(ImmutableList.<Entity>of(p1, p2, p3));

  // Act
  long minHeight = 160;
  // [START gae_java8_datastore_property_filter]
  Filter propertyFilter =
      new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);
  Query q = new Query("Person").setFilter(propertyFilter);
  // [END gae_java8_datastore_property_filter]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).containsExactly(p2, p3);
}
 
Example #4
Source File: MetadataPropertiesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
Collection<String> representationsOfProperty(DatastoreService ds, String kind, String property) {

    // Start with unrestricted non-keys-only property query
    Query q = new Query(Entities.PROPERTY_METADATA_KIND);

    // Limit to specified kind and property
    q.setFilter(
        new FilterPredicate(
            "__key__", Query.FilterOperator.EQUAL, Entities.createPropertyKey(kind, property)));

    // Get query result
    Entity propInfo = ds.prepare(q).asSingleEntity();

    // Return collection of property representations
    return (Collection<String>) propInfo.getProperty("property_representation");
  }
 
Example #5
Source File: MetadataPropertiesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
void printPropertyRange(DatastoreService ds, PrintWriter writer) {

    // Start with unrestricted keys-only property query
    Query q = new Query(Entities.PROPERTY_METADATA_KIND).setKeysOnly();

    // Limit range
    q.setFilter(
        CompositeFilterOperator.and(
            new FilterPredicate(
                Entity.KEY_RESERVED_PROPERTY,
                Query.FilterOperator.GREATER_THAN_OR_EQUAL,
                Entities.createPropertyKey("Employee", "salary")),
            new FilterPredicate(
                Entity.KEY_RESERVED_PROPERTY,
                Query.FilterOperator.LESS_THAN_OR_EQUAL,
                Entities.createPropertyKey("Manager", "salary"))));
    q.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);

    // Print query results
    for (Entity e : ds.prepare(q).asIterable()) {
      writer.println(e.getKey().getParent().getName() + ": " + e.getKey().getName());
    }
  }
 
Example #6
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
/**
 * inChk
 * - true: check if fDat are in result and if result count is correct;
 * - false: only check if result count is correct
 */
protected void verifyFilter(String kind, String pName, Object fDat,
                            Query.FilterOperator operator, int rCont, boolean inChk) {
    Query query = new Query(kind, rootKey);
    query.setFilter(new FilterPredicate(pName, operator, fDat));
    Object[] result = getResult(query, pName);
    assertEquals(rCont, result.length);
    if (inChk) {
        boolean find = false;
        for (Object data : result) {
            if (data.toString().equals(fDat.toString())) {
                find = true;
            }
        }
        assertEquals(true, find);
    }
}
 
Example #7
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void queryRestrictions_compositeFilter_isInvalid() throws Exception {
  long minBirthYear = 1940;
  long maxHeight = 200;
  // [START gae_java8_datastore_inequality_filters_one_property_invalid]
  Filter birthYearMinFilter =
      new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);

  Filter heightMaxFilter =
      new FilterPredicate("height", FilterOperator.LESS_THAN_OR_EQUAL, maxHeight);

  Filter invalidFilter = CompositeFilterOperator.and(birthYearMinFilter, heightMaxFilter);

  Query q = new Query("Person").setFilter(invalidFilter);
  // [END gae_java8_datastore_inequality_filters_one_property_invalid]

  // Note: The local devserver behavior is different than the production
  // version of Cloud Datastore, so there aren't any assertions we can make
  // in this test.  The query appears to work with the local test runner,
  // but will fail in production.
}
 
Example #8
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void queryRestrictions_missingSortOnInequality_isInvalid() throws Exception {
  long minBirthYear = 1940;
  // [START gae_java8_datastore_inequality_filters_sort_orders_invalid_1]
  Filter birthYearMinFilter =
      new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);

  // Not valid. Missing sort on birthYear.
  Query q =
      new Query("Person")
          .setFilter(birthYearMinFilter)
          .addSort("lastName", SortDirection.ASCENDING);
  // [END gae_java8_datastore_inequality_filters_sort_orders_invalid_1]

  // Note: The local devserver behavior is different than the production
  // version of Cloud Datastore, so there aren't any assertions we can make
  // in this test.  The query appears to work with the local test runner,
  // but will fail in production.
}
 
Example #9
Source File: SchemaTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testKindMetadata() {
    // check non empty namespace only
    for (int i = 1; i < namespaceDat.length; i++) {
        NamespaceManager.set(namespaceDat[i]);
        Query q = new Query("__kind__").addSort(Entity.KEY_RESERVED_PROPERTY);
        int count = 0;
        for (Entity e : service.prepare(q).asIterable()) {
            // do not count those stats entities for namespace.
            if (!e.getKey().getName().startsWith("__Stat_Ns_")) {
                count++;
            }
        }
        // For each namespace, only 3 user defined kinds.
        assertEquals(3, count);
        // check a specified namespace
        Key key1 = Entities.createKindKey("testing");
        q.setFilter(new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.EQUAL, key1));
        assertEquals(1, service.prepare(q).countEntities(fo));
        Entity ke = service.prepare(q).asSingleEntity();
        assertEquals("testing", ke.getKey().getName());
        assertEquals(namespaceDat[i], ke.getKey().getNamespace());
        assertEquals(namespaceDat[i], ke.getNamespace());
    }
}
 
Example #10
Source File: IndexesServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  // [START exploding_index_example_1]
  Query q =
      new Query("Widget")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("x", FilterOperator.EQUAL, 1),
                  new FilterPredicate("y", FilterOperator.EQUAL, 2)))
          .addSort("date", Query.SortDirection.ASCENDING);
  // [END exploding_index_example_1]
  List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());

  PrintWriter out = resp.getWriter();
  out.printf("Got %d widgets.\n", results.size());
}
 
Example #11
Source File: SchemaTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertyMetadata() {
    NamespaceManager.set(namespaceDat[2]);
    // sort by kind/property, kindDat[1] < kindDat[0] < kindDat[2]
    Query q = new Query("__property__").addSort(Entity.KEY_RESERVED_PROPERTY).setKeysOnly();
    // filter out properties for kind "testing"
    Key key1 = Entities.createPropertyKey(kindDat[0], "urlData");
    Key key2 = Entities.createPropertyKey(kindDat[2], "urlData");
    q.setFilter(CompositeFilterOperator.and(
        new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, key1),
        new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.LESS_THAN_OR_EQUAL, key2)));
    List<Entity> el = service.prepare(q).asList(fo);
    // un-indexed property, textData, will not be returned in __property__ queries.
    assertEquals(13, el.size());
    for (int i = 0; i < el.size(); i++) {
        assertEquals(namespaceDat[2], el.get(i).getKey().getNamespace());
        assertEquals(kindDat[2], el.get(i).getKey().getParent().getName());
        if (i == 0) {
            assertEquals("adressData", el.get(0).getKey().getName());
        } else if (i == el.size() - 1) {
            assertEquals("urlData", el.get(el.size() - 1).getKey().getName());
        }
    }
}
 
Example #12
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void queryRestrictions_sortWrongOrderOnInequality_isInvalid() throws Exception {
  long minBirthYear = 1940;
  // [START gae_java8_datastore_inequality_filters_sort_orders_invalid_2]
  Filter birthYearMinFilter =
      new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);

  // Not valid. Sort on birthYear needs to be first.
  Query q =
      new Query("Person")
          .setFilter(birthYearMinFilter)
          .addSort("lastName", SortDirection.ASCENDING)
          .addSort("birthYear", SortDirection.ASCENDING);
  // [END gae_java8_datastore_inequality_filters_sort_orders_invalid_2]

  // Note: The local devserver behavior is different than the production
  // version of Cloud Datastore, so there aren't any assertions we can make
  // in this test.  The query appears to work with the local test runner,
  // but will fail in production.
}
 
Example #13
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void queryRestrictions_surprisingMultipleValuesAllMustMatch_returnsNoEntities()
    throws Exception {
  Entity a = new Entity("Widget", "a");
  List<Long> xs = Arrays.asList(1L, 2L);
  a.setProperty("x", xs);
  datastore.put(a);

  // [START gae_java8_datastore_surprising_behavior_1]
  Query q =
      new Query("Widget")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("x", FilterOperator.GREATER_THAN, 1),
                  new FilterPredicate("x", FilterOperator.LESS_THAN, 2)));
  // [END gae_java8_datastore_surprising_behavior_1]

  // Entity "a" will not match because no individual value matches all filters.
  // See the documentation for more details:
  // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions
  // #properties_with_multiple_values_can_behave_in_surprising_ways
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).isEmpty();
}
 
Example #14
Source File: CachingService.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Account key associated with the specified user.
 * @param pm   reference to the persistence manager
 * @param user user to return the account key for
 * @return the Account key associated with the specified user; or <code>null</code> if no account is associated with the specified user
 */
public static Key getAccountKeyByUser( final PersistenceManager pm, final User user ) {
	final String memcacheKey = CACHE_KEY_USER_ACCOUNT_KEY_PREFIX + user.getEmail();
	final String accountKeyString = (String) memcacheService.get( memcacheKey );
	if ( accountKeyString != null )
		return KeyFactory.stringToKey( accountKeyString );
	
	final Query q = new Query( Account.class.getSimpleName() );
	q.setFilter( new FilterPredicate( "user", FilterOperator.EQUAL, user ) );
	q.setKeysOnly();
	final List< Entity > entityList = DatastoreServiceFactory.getDatastoreService().prepare( q ).asList( FetchOptions.Builder.withDefaults() );
	if ( entityList.isEmpty() )
		return null;
	
	final Key accountKey = entityList.get( 0 ).getKey();
	try {
		memcacheService.put( memcacheKey, KeyFactory.keyToString( accountKey ) );
	}
	catch ( final MemcacheServiceException mse ) {
		LOGGER.log( Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse );
		// Ignore memcache errors, do not prevent serving user request
	}
	
	return accountKey;
}
 
Example #15
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.beginTransaction();
  try {
    Query query = new Query(SESSION_KIND)
        .setFilter(new FilterPredicate(varName, FilterOperator.EQUAL, varValue));
    Iterator<Entity> results = datastore.prepare(transaction, query).asIterator();
    while (results.hasNext()) {
      Entity stateEntity = results.next();
      datastore.delete(transaction, stateEntity.getKey());
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example #16
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.beginTransaction();
  try {
    Query query = new Query(SESSION_KIND)
        .setFilter(new FilterPredicate(varName, FilterOperator.EQUAL, varValue));
    Iterator<Entity> results = datastore.prepare(transaction, query).asIterator();
    while (results.hasNext()) {
      Entity stateEntity = results.next();
      datastore.delete(transaction, stateEntity.getKey());
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example #17
Source File: NamespaceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Override
public void verifyFilter(String kind, String pName, Object fDat,
                         Query.FilterOperator operator, int rCont, boolean inChk) {
    Query query = new Query(kind);
    query.setFilter(new FilterPredicate(pName, operator, fDat));
    Object[] result = getResult(query, pName);
    assertEquals(rCont, result.length);
    if (inChk) {
        boolean find = false;
        for (Object data : result) {
            if (data.toString().equals(fDat.toString())) {
                find = true;
            }
        }
        assertEquals(true, find);
    }
}
 
Example #18
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.beginTransaction();
  try {
    Query query = new Query(SESSION_KIND)
        .setFilter(new FilterPredicate(varName, FilterOperator.EQUAL, varValue));
    Iterator<Entity> results = datastore.prepare(transaction, query).asIterator();
    while (results.hasNext()) {
      Entity stateEntity = results.next();
      datastore.delete(transaction, stateEntity.getKey());
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example #19
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void queryInterface_singleFilter_returnsMatchedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("height", 100);
  Entity b = new Entity("Person", "b");
  b.setProperty("height", 150);
  Entity c = new Entity("Person", "c");
  c.setProperty("height", 300);
  datastore.put(ImmutableList.<Entity>of(a, b, c));

  // Act
  long minHeight = 150;
  // [START gae_java8_datastore_interface_2]
  Filter heightMinFilter =
      new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);

  Query q = new Query("Person").setFilter(heightMinFilter);
  // [END gae_java8_datastore_interface_2]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).containsExactly(b, c);
}
 
Example #20
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.beginTransaction();
  try {
    Query query = new Query(SESSION_KIND)
        .setFilter(new FilterPredicate(varName, FilterOperator.EQUAL, varValue));
    Iterator<Entity> results = datastore.prepare(transaction, query).asIterator();
    while (results.hasNext()) {
      Entity stateEntity = results.next();
      datastore.delete(transaction, stateEntity.getKey());
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example #21
Source File: AppEngineBackEnd.java    From appengine-pipelines with Apache License 2.0 6 votes vote down vote up
private void deleteAll(final String kind, final Key rootJobKey) {
  logger.info("Deleting all " + kind + " with rootJobKey=" + rootJobKey);
  final int chunkSize = 100;
  final FetchOptions fetchOptions = FetchOptions.Builder.withChunkSize(chunkSize);
  final PreparedQuery preparedQuery = dataStore.prepare(new Query(kind).setKeysOnly().setFilter(
      new FilterPredicate(ROOT_JOB_KEY_PROPERTY, EQUAL, rootJobKey)));
  tryFiveTimes(new Operation<Void>("delete") {
    @Override
    public Void call() {
      Iterator<Entity> iter = preparedQuery.asIterator(fetchOptions);
      while (iter.hasNext()) {
        ArrayList<Key> keys = new ArrayList<>(chunkSize);
        for (int i = 0; i < chunkSize && iter.hasNext(); i++) {
          keys.add(iter.next().getKey());
        }
        logger.info("Deleting  " + keys.size() + " " + kind + "s with rootJobKey=" + rootJobKey);
        dataStore.delete(null, keys);
      }
      return null;
    }
  });
}
 
Example #22
Source File: BatchTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(10)
public void testStep10FilterInWithOption() {
    int filterNum = 100;
    Query q = new Query(kindName, rootKey);
    q.setFilter(new FilterPredicate("count", FilterOperator.IN, getFilterIn(filterNum)));
    int ttl = service.prepare(q).countEntities(fo.offset(filterNum / 2));
    assertEquals((filterNum / 2), ttl);
}
 
Example #23
Source File: ListTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
/**
 * Google issueId:1458158
 */
@Test
public void testIntFilter() {
    Query q = new Query(kindName);
    Query.Filter filter = Query.CompositeFilterOperator.and(
        new FilterPredicate("intData1", Query.FilterOperator.LESS_THAN, 20),
        new FilterPredicate("intData1", Query.FilterOperator.GREATER_THAN, 1),
        new FilterPredicate("intData1", Query.FilterOperator.EQUAL, null));
    q.setFilter(filter);
    q.addSort("intData1", Query.SortDirection.ASCENDING);
    q.setAncestor(rootKey);
    assertEquals(1, service.prepare(q).countEntities(fo));
    List<Entity> elist = service.prepare(q).asList(fo);
    assertEquals(Arrays.asList(1L, 10L, null), elist.get(0).getProperty("intData1"));
}
 
Example #24
Source File: AppEngineBackEnd.java    From appengine-pipelines with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<? extends Iterable<JobRecord>, String> queryRootPipelines(String classFilter,
    String cursor, final int limit) {
  Query query = new Query(JobRecord.DATA_STORE_KIND);
  Filter filter = classFilter == null || classFilter.isEmpty() ? new FilterPredicate(
      ROOT_JOB_DISPLAY_NAME, GREATER_THAN, null)
      : new FilterPredicate(ROOT_JOB_DISPLAY_NAME, EQUAL, classFilter);
  query.setFilter(filter);
  final PreparedQuery preparedQuery = dataStore.prepare(query);
  final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
  if (limit > 0) {
    fetchOptions.limit(limit + 1);
  }
  if (cursor != null) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(cursor));
  }
  return tryFiveTimes(
      new Operation<Pair<? extends Iterable<JobRecord>, String>>("queryRootPipelines") {
        @Override
        public Pair<? extends Iterable<JobRecord>, String> call() {
          QueryResultIterator<Entity> entities =
              preparedQuery.asQueryResultIterable(fetchOptions).iterator();
          Cursor dsCursor = null;
          List<JobRecord> roots = new LinkedList<>();
          while (entities.hasNext()) {
            if (limit > 0 && roots.size() >= limit) {
              dsCursor = entities.getCursor();
              break;
            }
            JobRecord jobRecord = new JobRecord(entities.next());
            roots.add(jobRecord);
          }
          return Pair.of(roots, dsCursor == null ? null : dsCursor.toWebSafeString());
        }
      });
}
 
Example #25
Source File: ListTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testStrFilter() {
    Query q = new Query(kindName);
    q.setAncestor(rootKey);
    Query.Filter filter = Query.CompositeFilterOperator.and(
        new FilterPredicate("stringData", Query.FilterOperator.LESS_THAN, "qqq"),
        new FilterPredicate("stringData", Query.FilterOperator.GREATER_THAN, "mmm"));
    q.setFilter(filter);
    q.addSort("stringData", Query.SortDirection.ASCENDING);
    assertEquals(2, service.prepare(q).countEntities(fo));
    List<Entity> elist = service.prepare(q).asList(fo);
    assertEquals(Arrays.asList("abc", "xyz", "mno"), elist.get(0).getProperty("stringData"));
    assertEquals(Arrays.asList("ppp", "iii", "ddd"), elist.get(1).getProperty("stringData"));
}
 
Example #26
Source File: DatastoreUtil.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
public void purgeTestRunRecords() {
    DatastoreService datastoreService = DatastoreServiceFactory. getDatastoreService();
    FilterPredicate testRunFilter = new FilterPredicate(TEST_RUN_ID, FilterOperator.EQUAL, testRunId);
    Query query = new Query(entityName).setFilter(testRunFilter).setKeysOnly();
    for (Entity readRec : datastoreService.prepare(query).asIterable()) {
        datastoreService.delete(readRec.getKey());
    }
}
 
Example #27
Source File: DatastoreUtil.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
public Entity getMarker(String marker) {
    DatastoreService service = DatastoreServiceFactory.getDatastoreService();
    FilterPredicate testRunFilter = new FilterPredicate(TEST_RUN_ID, FilterOperator.EQUAL, testRunId);
    FilterPredicate markerFilter = new FilterPredicate(MARKER, FilterOperator.EQUAL, marker);
    CompositeFilter filter = CompositeFilterOperator.and(testRunFilter, markerFilter);
    Query query = new Query(entityName).setFilter(filter);
    return service.prepare(query).asSingleEntity();
}
 
Example #28
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 #29
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 #30
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");
}