Java 类com.google.appengine.api.datastore.Query.Filter 实例源码

项目:LeaderboardServer    文件:ScoreDAO.java   
/**
 * Method to retrieve the national high scores 
 * @return
 */
public List<Entity> getNationalHighScores(String countryCode){
    log.info("Retrieving national high scores");

    //create the country code filter
    Filter country = new FilterPredicate(Constants.COUNTRY_CODE,FilterOperator.EQUAL,countryCode);
    //create the query to read the records sorted by score
    Query q = new Query(Constants.RECORD).addSort(Constants.SCORE, SortDirection.DESCENDING);
    //set the filter to the query
    q.setFilter(country);

    PreparedQuery pq = datastore.prepare(q);

    //retrieve and return the list of records   
    return pq.asList(FetchOptions.Builder.withLimit(100));
}
项目:LeaderboardServer    文件:ScoreDAO.java   
/**
 * Method to retrieve the monthly high scores 
 * @return
 */
public List<Entity> getMonthlyHighScores(){
    log.info("Retrieving monthly high scores");

    //calculate calendar info
    Calendar calendar= Calendar.getInstance();      
    int year=calendar.get(Calendar.YEAR);
    int month=calendar.get(Calendar.MONTH);

    //create filters
    Filter yearFilter = new FilterPredicate(Constants.YEAR,FilterOperator.EQUAL,year);
    Filter monthFilter = new FilterPredicate(Constants.MONTH,FilterOperator.EQUAL,month);

    //create the query to read the records sorted by score
    Query q = new Query(Constants.RECORD).addSort(Constants.SCORE, SortDirection.DESCENDING);
    //set filters to the query
    q.setFilter(yearFilter);
    q.setFilter(monthFilter);

    //prepare query
    PreparedQuery pq = datastore.prepare(q);

    //retrieve and return the list of records   
    return pq.asList(FetchOptions.Builder.withLimit(100));
}
项目:LeaderboardServer    文件:ScoreDAO.java   
/**
 * Method to retrieve the weekly high scores 
 * @return
 */
public List<Entity> getWeeklyHighScores(){
    log.info("Retrieving weekly high scores");

    //calculate calendar info
    Calendar calendar= Calendar.getInstance();      
    int year=calendar.get(Calendar.YEAR);
    int week=calendar.get(Calendar.WEEK_OF_YEAR);

    //create filters
    Filter yearFilter = new FilterPredicate(Constants.YEAR,FilterOperator.EQUAL,year);
    Filter weekFilter = new FilterPredicate(Constants.WEEK_OF_THE_YEAR,FilterOperator.EQUAL,week);

    //create the query to read the records sorted by score
    Query q = new Query(Constants.RECORD).addSort(Constants.SCORE, SortDirection.DESCENDING);
    //set filters to the query
    q.setFilter(yearFilter);
    q.setFilter(weekFilter);

    //prepare query
    PreparedQuery pq = datastore.prepare(q);

    //retrieve and return the list of records   
    return pq.asList(FetchOptions.Builder.withLimit(100));
}
项目:LeaderboardServer    文件:ScoreDAO.java   
/**
 * Method to retrieve the daily high scores 
 * @return
 */
public List<Entity> getDailyHighScores(){
    log.info("Retrieving weekly high scores");

    //calculate calendar info
    Calendar calendar= Calendar.getInstance();
    int year=calendar.get(Calendar.YEAR);
    int day=calendar.get(Calendar.DAY_OF_YEAR);

    //create filters
    Filter yearFilter = new FilterPredicate(Constants.YEAR,FilterOperator.EQUAL,year);
    Filter dayFilter = new FilterPredicate(Constants.DAY_OF_THE_YEAR,FilterOperator.EQUAL,day);

    //create the query to read the records sorted by score
    Query q = new Query(Constants.RECORD).addSort(Constants.SCORE, SortDirection.DESCENDING);

    //set filters to the query
    q.setFilter(yearFilter);
    q.setFilter(dayFilter);

    //prepare query
    PreparedQuery pq = datastore.prepare(q);

    //retrieve and return the list of records   
    return pq.asList(FetchOptions.Builder.withLimit(100));
}
项目:gae-webmonitor    文件:DataStoreService.java   
/**
 * Remove an object from the datastore
 * 
 * @param uri The URI
 */
public void removeObject(String uri) {
    if (!isObjectRegistered(uri)) {
        return;
    }
    // Remove all WebObjectInstance entries associated
    Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
    Query instanceQuery = new Query(OBJECT_INSTANCE)
            .setFilter(uriFilter)
            .addSort("timestamp", SortDirection.DESCENDING);
    List<Entity> instances = datastoreService
            .prepare(instanceQuery)
            .asList(FetchOptions.Builder.withDefaults());
    List<Key> keys = new ArrayList<Key>();
    for (Entity e : instances) {
        keys.add(e.getKey());
    }
    datastoreService.delete(keys);

    // Remove actual WebObject entry
    Query objectQuery = new Query(OBJECT).setFilter(uriFilter);
    Entity object = datastoreService.prepare(objectQuery).asSingleEntity();
    datastoreService.delete(object.getKey());
}
项目:gae-webmonitor    文件:DataStoreService.java   
/**
 * Update the timestamp of an object instance
 * 
 * @param uri The URI of the Web object instance
 * @param oldTimestamp The old timestamp
 * @param newTimestamp The new timestamp
 */
public void updateObjectInstanceTimestamp(String uri, Date oldTimestamp,
        Date newTimestamp) {
    Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
    Filter timestampFilter = new FilterPredicate("timestamp", FilterOperator.EQUAL, oldTimestamp);
    Query query = new Query(OBJECT_INSTANCE)
        .setFilter(uriFilter)
        .setFilter(timestampFilter);
    Entity instance = datastoreService.prepare(query).asSingleEntity();
    if (instance == null) {
        throw new IllegalArgumentException(
                "No record with matching URI and timestamp was found");
    }
    instance.setProperty("timestamp", newTimestamp);
    datastoreService.put(instance);
}
项目:gae-webmonitor    文件:DataStoreService.java   
/**
 * Get all instances of an object present in the data store
 * 
 * @param uri The URI of the Web object
 * @return The list of Web instances
 */
public List<WebObjectInstance> getAllObjectInstances(String uri) {
    Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
    Query query = new Query(OBJECT_INSTANCE)
            .setFilter(uriFilter)
            .addSort("timestamp", SortDirection.DESCENDING);

    List<Entity> instances = datastoreService.prepare(query)
            .asList(FetchOptions.Builder.withDefaults());
    List<WebObjectInstance> instanceList = new ArrayList<WebObjectInstance>();
    for (Entity e : instances) {
        String content = ((Text) e.getProperty("content")).getValue();
        String contentType = (String) e.getProperty("contentType");
        int statusCode = ((Integer) e.getProperty("statusCode")).intValue();
        Date timestamp = (Date) e.getProperty("timestamp");
        instanceList.add(new WebObjectInstance(uri, content, contentType,
                timestamp, statusCode));
    }
    return instanceList;
}
项目:gae-webmonitor    文件:DataStoreService.java   
/**
 * Get the most recent instance of a web object available
 * 
 * @param uri The URI of the Web object
 * @return The instance of the Web object
 */
public WebObjectInstance getMostRecentObjectInstance(String uri) {
    Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
    Query query = new Query(OBJECT_INSTANCE)
            .setFilter(uriFilter)
            .addSort("timestamp", SortDirection.DESCENDING);
    List<Entity> instances = datastoreService.prepare(query).asList(
            FetchOptions.Builder.withDefaults());
    if (instances == null || instances.isEmpty()) {
        return null;
    }
    Entity mostRecentInstance = instances.get(0);
    String content = ((Text) mostRecentInstance.getProperty("content"))
            .getValue();
    String contentType = (String) mostRecentInstance
            .getProperty("contentType");
    Date timestamp = (Date) mostRecentInstance.getProperty("timestamp");
    int statusCode = ((Long) mostRecentInstance.getProperty("statusCode"))
            .intValue();
    return new WebObjectInstance(uri, content, contentType, timestamp,
            statusCode);
}
项目:java-docs-samples    文件:QueriesTest.java   
@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 property_filter_example]
  Filter propertyFilter =
      new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);
  Query q = new Query("Person").setFilter(propertyFilter);
  // [END property_filter_example]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results).named("query results").containsExactly(p2, p3);
}
项目:java-docs-samples    文件:QueriesTest.java   
@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 interface_2]
  Filter heightMinFilter =
      new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);

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

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results).named("query results").containsExactly(b, c);
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void queryRestrictions_compositeFilter_isInvalid() throws Exception {
  long minBirthYear = 1940;
  long maxHeight = 200;
  // [START inequality_filters_one_property_invalid_example]
  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 inequality_filters_one_property_invalid_example]

  // 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.
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void queryRestrictions_missingSortOnInequality_isInvalid() throws Exception {
  long minBirthYear = 1940;
  // [START inequality_filters_sort_orders_invalid_example_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 inequality_filters_sort_orders_invalid_example_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.
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void queryRestrictions_sortWrongOrderOnInequality_isInvalid() throws Exception {
  long minBirthYear = 1940;
  // [START inequality_filters_sort_orders_invalid_example_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 inequality_filters_sort_orders_invalid_example_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.
}
项目:java-docs-samples    文件:QueriesTest.java   
@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 property_filter_example]
  Filter propertyFilter =
      new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);
  Query q = new Query("Person").setFilter(propertyFilter);
  // [END property_filter_example]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results).named("query results").containsExactly(p2, p3);
}
项目:java-docs-samples    文件:QueriesTest.java   
@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 interface_2]
  Filter heightMinFilter =
      new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);

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

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results).named("query results").containsExactly(b, c);
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void queryRestrictions_compositeFilter_isInvalid() throws Exception {
  long minBirthYear = 1940;
  long maxHeight = 200;
  // [START inequality_filters_one_property_invalid_example]
  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 inequality_filters_one_property_invalid_example]

  // 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.
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void queryRestrictions_missingSortOnInequality_isInvalid() throws Exception {
  long minBirthYear = 1940;
  // [START inequality_filters_sort_orders_invalid_example_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 inequality_filters_sort_orders_invalid_example_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.
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void queryRestrictions_sortWrongOrderOnInequality_isInvalid() throws Exception {
  long minBirthYear = 1940;
  // [START inequality_filters_sort_orders_invalid_example_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 inequality_filters_sort_orders_invalid_example_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.
}
项目:Dendrite    文件:StoryPage.java   
public static List<StoryPage> getPagesWrittenBy(final String authorId,
        final int start, final int end) {
    final DatastoreQuery query = new DatastoreQuery(KIND_NAME);
    query.addSort(BEGINNING_NUMBER_PROPERTY);
    query.addSort(ID_NUMBER_PROPERTY);
    query.addSort(ID_VERSION_PROPERTY);
    final Filter filter = getAuthorIdFilter(authorId);
    query.setFilter(filter);
    final Store store = new Store();
    final PreparedQuery preparedQuery = store.prepare(query);
    final int limit = end - start;
    final FetchOptions fetchOptions = FetchOptions.Builder.withLimit(limit);
    final int offset = start;
    fetchOptions.offset(offset);
    final List<DatastoreEntity> entities = DatastoreEntity
            .fromPreparedQuery(preparedQuery, fetchOptions);
    final List<StoryPage> pages = getPagesFromEntities(entities);
    return pages;
}
项目:solutions-cloud-adventure-sample-backend-java    文件:GameUserEndpoint.java   
/**
 * Gets the user from the Datastore using their unique user handle.
 * 
 * @param handle the handle of the user
 * @return the {@link GameUser}
 */
@SuppressWarnings("unchecked")
@ApiMethod(path = "users/name/{handle}", name = "users.getByHandle")
public GameUser getUserByHandle(@Named("handle") String handle) {
  Filter userHandleFilter =
      new Query.FilterPredicate("user_handle", FilterOperator.EQUAL, handle);
  Query q = new Query("User").setFilter(userHandleFilter);
  Entity entity = StorageUtils.getDatastore().prepare(q).asSingleEntity();
  if (entity == null) {
    return null;
  }
  GameUser user = new GameUser();
  user.setAccount(entity.getKey().getName());
  user.setHandle((String) entity.getProperty("user_handle"));
  user.setFriends((ArrayList<String>) entity.getProperty("friends"));
  user.setTotalGames((Long) entity.getProperty("total_games"));
  user.setTotalGems((Long) entity.getProperty("total_gems"));
  user.setTotalMobsKilled((Long) entity.getProperty("total_mobs_killed"));
  return user;
}
项目:appengine-tck    文件:QueryTest.java   
@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"));
    }
}
项目:appengine-tck    文件:QueryTest.java   
@Test
public void testCompositeFilter() {
    Query query = new Query(kindName, rootKey);
    Filter filter = Query.CompositeFilterOperator.and(
        Query.FilterOperator.LESS_THAN_OR_EQUAL.of("intData", 40),
        Query.FilterOperator.GREATER_THAN.of("intData", 0));
    query.setFilter(filter);
    query.addSort("intData", Query.SortDirection.DESCENDING);
    List<Entity> es = service.prepare(query).asList(fo);
    assertEquals("check return count", 2, es.size());
    assertEquals("check query filter", filter, query.getFilter());
    assertEquals("check query key only", false, query.isKeysOnly());

    Query.CompositeFilter cf = (Query.CompositeFilter) query.getFilter();
    assertEquals(2, cf.getSubFilters().size());
    assertEquals(Query.CompositeFilterOperator.AND, cf.getOperator());
}
项目:solutions-griddler-sample-backend-java    文件:DeviceService.java   
/**
 * Gets a not null list of device entities by device id.
 *
 * @param deviceId the id of the device.
 */
protected List<DeviceEntity> getByDeviceId(String deviceId) {
  List<DeviceEntity> result = new ArrayList<DeviceEntity>();

  Filter deviceIdFilter =
      new FilterPredicate(DeviceEntity.DEVICEID_PROPERTY, FilterOperator.EQUAL, deviceId);

  Query query = new Query(DeviceEntity.KIND).setFilter(deviceIdFilter);
  PreparedQuery preparedQuery = dataStore.prepare(query);

  for (Entity entity : preparedQuery.asIterable()) {
    result.add(new DeviceEntity(entity));
  }

  return result;
}
项目:solutions-griddler-sample-backend-java    文件:PlayerService.java   
/**
 * Gets a list of players that a given user can play with. This implementation simply returns the
 * list of all players other than the current user.
 *
 * @param user user making the request.
 */
public List<Player> getPlayers(User user) {
  List<Player> results = new ArrayList<Player>();

  Filter activePlayersFilter =
      new FilterPredicate(PlayerEntity.ACTIVE_PROPERTY, FilterOperator.EQUAL, true);
  Query query = new Query(PlayerEntity.KIND).setFilter(activePlayersFilter);
  PreparedQuery preparedQuery = dataStore.prepare(query);

  for (Entity entity : preparedQuery.asIterable()) {
    PlayerEntity playerEntity = new PlayerEntity(entity);
    if (!playerEntity.getEmail().equalsIgnoreCase(user.getEmail())) {
      results.add(new Player(playerEntity.getId(), playerEntity.getNickname()));
    }
  }

  return results;
}
项目:contestManagement    文件:Main.java   
private static void updateRegistrations(Level level, Map<String, School> schools) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    for (School school : schools.values()) {
        Filter schoolNameFilter = new FilterPredicate("schoolName", FilterOperator.EQUAL, school.getName());
        Filter schoolLevelFilter = new FilterPredicate("schoolLevel", FilterOperator.EQUAL, level.toString());
        Filter regTypeFilter = new FilterPredicate("registrationType", FilterOperator.EQUAL, "coach");

        Query query = new Query("registration").setFilter(CompositeFilterOperator.and(schoolNameFilter, schoolLevelFilter, regTypeFilter));
        List<Entity> registrations = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());

        if (registrations.size() > 0) {
            Entity registration = registrations.get(0);
            for (Entry<Test, Integer> numTest : school.getNumTests().entrySet()) {
                registration.setProperty(numTest.getKey().toString(), numTest.getValue());
            }
            datastore.put(registration);
        }
    }
}
项目:spring-data-objectify    文件:ObjectifyRepositoryQuery.java   
protected Object doExecute(Object[] parameters) {
    Class<?> domainClass = queryMethod.getEntityInformation().getJavaType();
    int paramIndex = 0;

    PartTree tree = new PartTree(getQueryMethod().getName(), getQueryMethod().getEntityInformation().getJavaType());
    System.out.println(tree);

    List<Filter> orFilters = new ArrayList<Filter>();
    for (Iterator<OrPart> orPartIter = tree.iterator(); orPartIter.hasNext();) {
        OrPart orPart = orPartIter.next();

        List<Filter> andFilters = new ArrayList<Filter>();
        for (Iterator<Part> partIter = orPart.iterator(); partIter.hasNext();) {
            Part part = partIter.next();
            PropertyPath propertyPath  = part.getProperty();
            String propName = propertyPath.getSegment();
            Object propValue = parameters[paramIndex++];

            FilterOperator operator = getFilterOperation(part);
            Filter filter = new Query.FilterPredicate(propName, operator, propValue);
            andFilters.add(filter);
        }
        if (andFilters.size() == 1) {
            orFilters.add(andFilters.get(0));
        } else if (andFilters.size() >= 2){
            orFilters.add(CompositeFilterOperator.and(andFilters));
        }
    }

    com.googlecode.objectify.cmd.Query q = ofy().load().type(domainClass);
    if (orFilters.size() == 1) {
        q = q.filter(orFilters.get(0));
    } else if (orFilters.size() >= 2){
        q = q.filter(CompositeFilterOperator.or(orFilters));
    }
    return q.list();
}
项目:gae-webmonitor    文件:DataStoreService.java   
/**
 * Check whether a specific object is in the datastore
 * 
 * @param uri The URI of the object
 * @return true if present, false otherwise
 */
public boolean isObjectRegistered(String uri) {
    Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
    Query query = new Query(OBJECT).setFilter(uriFilter);
    Entity object = datastoreService.prepare(query).asSingleEntity();
    return (object != null);
}
项目:gae-webmonitor    文件:DataStoreService.java   
/**
 * Get the list of objects a user is subscribed to
 * 
 * @param email The user email address
 * @return The list of objects' URIs 
 */
public List<String> getObjectsSubscribed(String email) {
    Filter emailFilter = new FilterPredicate("email", FilterOperator.EQUAL, email);
    Query query = new Query(SUBSCRIPTION).setFilter(emailFilter);
    List<Entity> entity = datastoreService.prepare(query)
            .asList(FetchOptions.Builder.withDefaults());
    List<String> uri = new ArrayList<String>();
    for (Entity e : entity) {
        uri.add((String) e.getProperty("uri"));
    }
    return uri;
}
项目:gae-webmonitor    文件:DataStoreService.java   
/**
 * Get a list of subscribed users for a given object
 * 
 * @param uri The URI of the object
 * @return The list of subscribed users
 */
public List<String> getSubscribers(String uri) {
    Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
    Query query = new Query(SUBSCRIPTION).setFilter(uriFilter);
    List<Entity> entity = datastoreService.prepare(query).asList(
            FetchOptions.Builder.withDefaults());
    List<String> email = new ArrayList<String>();
    for (Entity e : entity) {
        email.add((String) e.getProperty("email"));
    }
    return email;
}
项目:gae-webmonitor    文件:DataStoreService.java   
/** 
 * Remove an object subscription
 * 
 * @param email The user email
 * @param uri The Web object URI
 */
public void removeSubscription(String email, String uri) {
    if (!isUserSubscribed(email, uri)) {
        throw new IllegalArgumentException("The user is not subscribed");
    }
    Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
    Filter emailFilter = new FilterPredicate("email", FilterOperator.EQUAL, email);
    Query query = new Query(SUBSCRIPTION)
            .setFilter(emailFilter)
            .setFilter(uriFilter);
    Entity subscription = datastoreService.prepare(query).asSingleEntity();
    datastoreService.delete(subscription.getKey());
}
项目:gae-webmonitor    文件:DataStoreService.java   
/**
 * Check whether a user is subscribed to a Web object
 * 
 * @param email The user email address
 * @param uri The object URI
 * 
 * @return true if the user is subscribed, false otherwise
 */
public boolean isUserSubscribed(String email, String uri) {
    Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
    Filter emailFilter = new FilterPredicate("email", FilterOperator.EQUAL, email);
    Query query = new Query(SUBSCRIPTION)
            .setFilter(emailFilter)
            .setFilter(uriFilter);
    Entity subscription = datastoreService.prepare(query).asSingleEntity();
    return (subscription != null);

}
项目:gae-webmonitor    文件:DataStoreService.java   
/**
 * Remove a user
 * 
 * @param email the user email address
 */
public void removeUser(String email) {
    if (!isUserRegistered(email)) {
        throw new IllegalArgumentException("User not registered");
    }
    Filter emailFilter = new FilterPredicate("email", FilterOperator.EQUAL, email);
    Query query = new Query(USER).setFilter(emailFilter);
    Entity user = datastoreService.prepare(query).asSingleEntity();
    datastoreService.delete(user.getKey());
}
项目:apollo-datastore    文件:SessionFactory.java   
public static ArrayList<Session> getSessionsByUserKey(DatastoreService datastore, Key userKey) {
    Filter userFilter = new FilterPredicate(DatastoreProperties.USER_KEY.getName(), FilterOperator.EQUAL, userKey);
    Query q = new Query(DatastoreProperties.KIND.getName());
    q.setFilter(userFilter);
    PreparedQuery pq = datastore.prepare(q);
    ArrayList<Session> sessions = new ArrayList<Session>();
    for(Entity result : pq.asIterable())
        sessions.add(new Session(result));
    return sessions;
}
项目:java-docs-samples    文件:IndexesTest.java   
@Test
public void propertyFilterExample_returnsMatchingEntities() throws Exception {
  // [START unindexed_properties_1]
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  Key acmeKey = KeyFactory.createKey("Company", "Acme");

  Entity tom = new Entity("Person", "Tom", acmeKey);
  tom.setProperty("name", "Tom");
  tom.setProperty("age", 32);
  datastore.put(tom);

  Entity lucy = new Entity("Person", "Lucy", acmeKey);
  lucy.setProperty("name", "Lucy");
  lucy.setUnindexedProperty("age", 29);
  datastore.put(lucy);

  Filter ageFilter = new FilterPredicate("age", FilterOperator.GREATER_THAN, 25);

  Query q = new Query("Person").setAncestor(acmeKey).setFilter(ageFilter);

  // Returns tom but not lucy, because her age is unindexed
  List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
  // [END unindexed_properties_1]

  assertThat(results).named("query results").containsExactly(tom);
}
项目:java-docs-samples    文件:MetadataKindsTest.java   
void printLowercaseKinds(DatastoreService ds, PrintWriter writer) {

    // Start with unrestricted kind query
    Query q = new Query(Entities.KIND_METADATA_KIND);

    List<Filter> subFils = new ArrayList();

    // Limit to lowercase initial letters
    subFils.add(
        new FilterPredicate(
            Entity.KEY_RESERVED_PROPERTY,
            FilterOperator.GREATER_THAN_OR_EQUAL,
            Entities.createKindKey("a")));

    String endChar = Character.toString((char) ('z' + 1)); // Character after 'z'

    subFils.add(
        new FilterPredicate(
            Entity.KEY_RESERVED_PROPERTY,
            FilterOperator.LESS_THAN,
            Entities.createKindKey(endChar)));

    q.setFilter(CompositeFilterOperator.and(subFils));

    // Print heading
    writer.println("Lowercase kinds:");

    // Print query results
    for (Entity e : ds.prepare(q).asIterable()) {
      writer.println("  " + e.getKey().getName());
    }
  }
项目:java-docs-samples    文件:StartupServletTest.java   
@Test
public void doGet_emptyDatastore_writesPresidents() throws Exception {
  servletUnderTest.doGet(mockRequest, mockResponse);

  Filter nameFilter = new FilterPredicate("name", FilterOperator.EQUAL, "George Washington");
  Query q = new Query("Person").setFilter(nameFilter);
  Entity result = datastore.prepare(q).asSingleEntity();
  assertThat(result.getProperty("name")).named("name").isEqualTo("George Washington");
}
项目:java-docs-samples    文件:MetadataNamespacesTest.java   
List<String> getNamespaces(DatastoreService ds, String start, String end) {

    // Start with unrestricted namespace query
    Query q = new Query(Entities.NAMESPACE_METADATA_KIND);
    List<Filter> subFilters = new ArrayList();
    // Limit to specified range, if any
    if (start != null) {
      subFilters.add(
          new FilterPredicate(
              Entity.KEY_RESERVED_PROPERTY,
              FilterOperator.GREATER_THAN_OR_EQUAL,
              Entities.createNamespaceKey(start)));
    }
    if (end != null) {
      subFilters.add(
          new FilterPredicate(
              Entity.KEY_RESERVED_PROPERTY,
              FilterOperator.LESS_THAN_OR_EQUAL,
              Entities.createNamespaceKey(end)));
    }

    q.setFilter(CompositeFilterOperator.and(subFilters));

    // Initialize result list
    List<String> results = new ArrayList<String>();

    // Build list of query results
    for (Entity e : ds.prepare(q).asIterable()) {
      results.add(Entities.getNamespaceFromNamespaceKey(e.getKey()));
    }

    // Return result list
    return results;
  }
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void keyFilterExample_returnsMatchingEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  Entity b = new Entity("Person", "b");
  Entity c = new Entity("Person", "c");
  Entity aa = new Entity("Person", "aa", b.getKey());
  Entity bb = new Entity("Person", "bb", b.getKey());
  Entity aaa = new Entity("Person", "aaa", bb.getKey());
  Entity bbb = new Entity("Person", "bbb", bb.getKey());
  datastore.put(ImmutableList.<Entity>of(a, b, c, aa, bb, aaa, bbb));

  // Act
  Key lastSeenKey = bb.getKey();
  // [START key_filter_example]
  Filter keyFilter =
      new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, lastSeenKey);
  Query q = new Query("Person").setFilter(keyFilter);
  // [END key_filter_example]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results)
      .named("query results")
      .containsExactly(
          aaa, // Ancestor path "b/bb/aaa" is greater than "b/bb".
          bbb, // Ancestor path "b/bb/bbb" is greater than "b/bb".
          c); // Key name identifier "c" is greater than b.
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void keyFilterExample_kindless_returnsMatchingEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Child", "a");
  Entity b = new Entity("Child", "b");
  Entity c = new Entity("Child", "c");
  Entity aa = new Entity("Child", "aa", b.getKey());
  Entity bb = new Entity("Child", "bb", b.getKey());
  Entity aaa = new Entity("Child", "aaa", bb.getKey());
  Entity bbb = new Entity("Child", "bbb", bb.getKey());
  Entity adult = new Entity("Adult", "a");
  Entity zooAnimal = new Entity("ZooAnimal", "a");
  datastore.put(ImmutableList.<Entity>of(a, b, c, aa, bb, aaa, bbb, adult, zooAnimal));

  // Act
  Key lastSeenKey = bb.getKey();
  // [START kindless_query_example]
  Filter keyFilter =
      new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, lastSeenKey);
  Query q = new Query().setFilter(keyFilter);
  // [END kindless_query_example]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results)
      .named("query results")
      .containsExactly(
          aaa, // Ancestor path "b/bb/aaa" is greater than "b/bb".
          bbb, // Ancestor path "b/bb/bbb" is greater than "b/bb".
          zooAnimal, // Kind "ZooAnimal" is greater than "Child"
          c); // Key name identifier "c" is greater than b.
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void ancestorQueryExample_kindlessKeyFilter_returnsMatchingEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Grandparent", "a");
  Entity b = new Entity("Grandparent", "b");
  Entity c = new Entity("Grandparent", "c");
  Entity aa = new Entity("Parent", "aa", a.getKey());
  Entity ba = new Entity("Parent", "ba", b.getKey());
  Entity bb = new Entity("Parent", "bb", b.getKey());
  Entity bc = new Entity("Parent", "bc", b.getKey());
  Entity cc = new Entity("Parent", "cc", c.getKey());
  Entity aaa = new Entity("Child", "aaa", aa.getKey());
  Entity bbb = new Entity("Child", "bbb", bb.getKey());
  datastore.put(ImmutableList.<Entity>of(a, b, c, aa, ba, bb, bc, cc, aaa, bbb));

  // Act
  Key ancestorKey = b.getKey();
  Key lastSeenKey = bb.getKey();
  // [START kindless_ancestor_key_query_example]
  Filter keyFilter =
      new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, lastSeenKey);
  Query q = new Query().setAncestor(ancestorKey).setFilter(keyFilter);
  // [END kindless_ancestor_key_query_example]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results).named("query results").containsExactly(bc, bbb);
}