Java Code Examples for com.google.appengine.api.datastore.Query#setFilter()

The following examples show how to use com.google.appengine.api.datastore.Query#setFilter() . 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: 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 2
Source File: TestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private static <T extends TempData> List<T> getAllTempData(Class<T> type, boolean unreadOnly) {
    try {
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        String kind = getKind(type);
        Query query = new Query(kind);
        if (unreadOnly) {
            query.setFilter(new Query.FilterPredicate(TEMP_DATA_READ_PROPERTY, Query.FilterOperator.EQUAL, false));
        } else {
            query.addSort("timestamp", Query.SortDirection.ASCENDING);
        }
        PreparedQuery pq = ds.prepare(query);
        Iterator<Entity> iter = pq.asIterator();
        List<T> result = new ArrayList<>();
        while (iter.hasNext()) {
            Entity entity = iter.next();
            T data = readTempData(type, entity, ds);
            result.add(data);
        }
        return result;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 3
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 4
Source File: QueryTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithPropertyProjection() {
    Query query = new Query(kindName, rootKey);
    query.addProjection(new PropertyProjection("geoptData", GeoPt.class));
    Filter filter1 = Query.CompositeFilterOperator.or(
        Query.FilterOperator.LESS_THAN.of("intList", 5),
        Query.FilterOperator.GREATER_THAN.of("intList", 90));
    Filter filter2 = Query.FilterOperator.EQUAL.of("intList", 52);
    query.setFilter(Query.CompositeFilterOperator.and(filter1, filter2));
    // sql statement
    String sql = "SELECT geoptData FROM " + kindName;
    sql += " WHERE ((intList < 5 or intList > 90) AND intList = 52)";
    sql += " AND __ancestor__ is " + rootKey;
    assertEquals(sql.toLowerCase(), query.toString().toLowerCase());
    // check query result
    List<Entity> results = service.prepare(query).asList(fo);
    Assert.assertTrue(results.size() > 0);
    assertEquals(new GeoPt((float) (2.12), (float) (2.98)), results.get(0).getProperty("geoptData"));
    for (Entity e : results) {
        assertEquals(1, e.getProperties().size());
        assertTrue(e.getProperties().containsKey("geoptData"));
    }
}
 
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: QueryOptimizationsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testOrderOfReturnedResultsIsSameAsOrderOfElementsInInStatementWhenUsingKeysOnly() throws Exception {
    String methodName = "testOrderOfReturnedResultsIsSameAsOrderOfElementsInInStatementWhenUsingKeysOnly";
    Entity parent = createTestEntityWithUniqueMethodNameKey("Product", methodName);
    Key key = parent.getKey();

    Entity b = createEntity("Product", key)
        .withProperty("name", "b")
        .store();

    Entity a = createEntity("Product", key)
        .withProperty("name", "a")
        .store();

    Query query = new Query("Product")
        .setAncestor(key)
        .setKeysOnly()
        .setFilter(new Query.FilterPredicate("name", IN, Arrays.asList("a", "b")));
    assertResultsInOrder(query, a, b);

    query = query.setFilter(new Query.FilterPredicate("name", IN, Arrays.asList("b", "a")));
    assertResultsInOrder(query, b, a);
}
 
Example 7
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 8
Source File: QueryOptimizationsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testOrderOfReturnedResultsIsSameAsOrderOfElementsInInStatementWhenUsingProjections() throws Exception {
    String methodName = "testOrderOfReturnedResultsIsSameAsOrderOfElementsInInStatementWhenUsingProjections";
    Entity parent = createTestEntityWithUniqueMethodNameKey("Product", methodName);
    Key key = parent.getKey();

    Entity b = createEntity("Product", key)
        .withProperty("name", "b")
        .withProperty("price", 1L)
        .store();

    Entity a = createEntity("Product", key)
        .withProperty("name", "a")
        .withProperty("price", 2L)
        .store();

    Query query = new Query("Product")
        .setAncestor(key)
        .addProjection(new PropertyProjection("price", Long.class))
        .setFilter(new Query.FilterPredicate("name", IN, Arrays.asList("a", "b")));
    assertResultsInOrder(query, a, b);

    query = query.setFilter(new Query.FilterPredicate("name", IN, Arrays.asList("b", "a")));
    assertResultsInOrder(query, b, a);
}
 
Example 9
Source File: PersistingTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void putStoresEntity() throws Exception {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Entity client = new Entity("Client");
    client.setProperty("username", "alesj");
    client.setProperty("password", "password");
    final Key key = ds.put(client);
    try {
        Query query = new Query("Client");
        query.setFilter(new Query.FilterPredicate("username", Query.FilterOperator.EQUAL, "alesj"));
        PreparedQuery pq = ds.prepare(query);
        Entity result = pq.asSingleEntity();
        Assert.assertNotNull(result);
        Assert.assertEquals(key, result.getKey());
        Assert.assertEquals("alesj", result.getProperty("username"));
        Assert.assertEquals("password", result.getProperty("password"));
    } finally {
        ds.delete(key);
    }
}
 
Example 10
Source File: DistinctTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testDistinctFilter2() {
    Query query = new Query(kindName, rootKey);
    query.addProjection(new PropertyProjection("stringData", String.class));
    query.addProjection(new PropertyProjection("floatData", Float.class));
    query.setFilter(new FilterPredicate("stringData", Query.FilterOperator.GREATER_THAN,
        "string0"));
    query.addSort("stringData", Query.SortDirection.DESCENDING);
    query.addSort("floatData", Query.SortDirection.DESCENDING);
    query.setDistinct(true);
    assertEquals(2, service.prepare(query).countEntities(fo));
    assertTrue(query.getDistinct());
}
 
Example 11
Source File: QueryTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilterPredicate() {
    Query query = new Query(kindName, rootKey);
    query.setFilter(new FilterPredicate("intData", Query.FilterOperator.EQUAL, 20));
    Entity e = service.prepare(query).asSingleEntity();
    assertEquals("check query kind", kindName, query.getKind());
    assertEquals("check query ancesor", rootKey, query.getAncestor());
    Query.FilterPredicate fp = (Query.FilterPredicate) query.getFilter();
    assertEquals("check FilterPredicate name", "intData", fp.getPropertyName());
    assertEquals("check FilterPredicate operator", Query.FilterOperator.EQUAL, fp.getOperator());
    assertEquals("check FilterPredicate value", e.getProperty("intData").toString(), fp.getValue().toString());
}
 
Example 12
Source File: BatchTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(9)
public void testStep9BigFilterIn() {
    int filterNum = 500;
    Query q = new Query(kindName, rootKey);
    q.setFilter(new FilterPredicate("count", FilterOperator.IN, getFilterIn(filterNum)));
    FetchOptions fo = FetchOptions.Builder.withDefaults();
    int ttl = service.prepare(q).countEntities(fo);
    assertEquals(filterNum, ttl);
}
 
Example 13
Source File: DistinctTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testDistinctFilter() {
    Query query = new Query(kindName, rootKey);
    query.addProjection(new PropertyProjection("stringData", String.class));
    query.addProjection(new PropertyProjection("floatData", Float.class));
    query.setFilter(new FilterPredicate("stringData", Query.FilterOperator.NOT_EQUAL, "string1"));
    query.addSort("stringData", Query.SortDirection.DESCENDING);
    query.setDistinct(true);
    assertEquals(5, service.prepare(query).countEntities(fo));
    assertTrue(query.getDistinct());
}
 
Example 14
Source File: IndexQueryTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryFilter() {
    Query query = new Query(kindName, rootKey);
    query.addProjection(new PropertyProjection("stringData", String.class));
    query.setFilter(new FilterPredicate("intData", FilterOperator.NOT_EQUAL, 50));
    query.addSort("intData");
    List<Entity> results = service.prepare(query).asList(fetchOption);
    assertEquals(count - 1, results.size());
    for (Entity e : results) {
        assertTrue(e.getProperty("stringData").toString().contains("5") == false);
    }
}
 
Example 15
Source File: PhotoManagerNoSql.java    From solutions-photo-sharing-demo-java with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<Photo> getOwnedPhotos(String userId) {
  Query query = new Query(getKind());
  query.setAncestor(userManager.createDemoUserKey(userId));
  Query.Filter filter = new Query.FilterPredicate(PhotoNoSql.FIELD_NAME_ACTIVE,
      FilterOperator.EQUAL, true);
  query.setFilter(filter);
  FetchOptions options = FetchOptions.Builder.withDefaults();
  return queryEntities(query, options);
}
 
Example 16
Source File: NamespaceTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiffNamespace() {
    NamespaceManager.set(namespaceDat[1]);
    Query q = new Query(kindName);
    q.setFilter(new FilterPredicate("jobType", Query.FilterOperator.EQUAL, stringDat[2] + 1));
    int ttl = service.prepare(q).countEntities(FetchOptions.Builder.withDefaults());
    assertEquals(0, ttl);
}
 
Example 17
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 18
Source File: AppEngineBackEnd.java    From appengine-pipelines with Apache License 2.0 5 votes vote down vote up
public List<Entity> queryAll(final String kind, final Key rootJobKey) {
  Query query = new Query(kind);
  query.setFilter(new FilterPredicate(ROOT_JOB_KEY_PROPERTY, EQUAL, rootJobKey));
  final PreparedQuery preparedQuery = dataStore.prepare(query);
  final FetchOptions options = FetchOptions.Builder.withChunkSize(500);
  return tryFiveTimes(new Operation<List<Entity>>("queryFullPipeline") {
    @Override
    public List<Entity> call() {
      return preparedQuery.asList(options);
    }
  });
}
 
Example 19
Source File: PhotoManagerNoSql.java    From solutions-photo-sharing-demo-java with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<Photo> getActivePhotos() {
  Query query = new Query(getKind());
  Query.Filter filter = new Query.FilterPredicate(PhotoNoSql.FIELD_NAME_ACTIVE,
      FilterOperator.EQUAL, true);
  query.addSort(PhotoNoSql.FIELD_NAME_UPLOAD_TIME, SortDirection.DESCENDING);
  query.setFilter(filter);
  FetchOptions options = FetchOptions.Builder.withDefaults();
  return queryEntities(query, options);
}
 
Example 20
Source File: DatastoreUtil.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
private Entity fetchEntity(String testMethodTag) {
    DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query(entityName);
    query.setFilter(getTestMethodFilter(testMethodTag));
    return datastoreService.prepare(query).asSingleEntity();
}