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

项目: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));
}
项目:walkaround    文件:UdwDirectory.java   
public List<ConvUdwMapping> getAllUdwIds(SlobId convObjectId)
    throws PermanentFailure, RetryableFailure {
  Query q = new Query(ENTITY_KIND)
    .setFilter(FilterOperator.GREATER_THAN_OR_EQUAL.of(Entity.KEY_RESERVED_PROPERTY,
        directory.makeKey(new Key(convObjectId, FIRST))))
    .addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);

  List<ConvUdwMapping> entries = Lists.newArrayList();

  CheckedIterator it = datastore.prepareNontransactionalQuery(q)
      .asIterator(FetchOptions.Builder.withDefaults());
  while (it.hasNext()) {
    ConvUdwMapping entry = directory.parse(it.next());
    if (!entry.getKey().getConvObjectId().equals(convObjectId)) {
      break;
    }
    entries.add(entry);
  }
  log.info("Found " + entries.size() + " user data wavelets for " + convObjectId);
  return entries;
}
项目:walkaround    文件:MutationLog.java   
private CheckedIterator getDeltaEntityIterator(long startVersion, @Nullable Long endVersion,
    FetchOptions fetchOptions, boolean forward, boolean keysOnly)
    throws PermanentFailure, RetryableFailure {
  checkRange(startVersion, endVersion);
  if (endVersion != null && startVersion == endVersion) {
    return CheckedIterator.EMPTY;
  }
  Query.Filter filter = FilterOperator.GREATER_THAN_OR_EQUAL.of(Entity.KEY_RESERVED_PROPERTY,
      makeDeltaKey(objectId, startVersion));
  if (endVersion != null) {
    filter = Query.CompositeFilterOperator.and(filter,
        FilterOperator.LESS_THAN.of(Entity.KEY_RESERVED_PROPERTY,
            makeDeltaKey(objectId, endVersion)));
  }
  Query q = new Query(deltaEntityKind)
      .setAncestor(makeRootEntityKey(objectId))
      .setFilter(filter)
      .addSort(Entity.KEY_RESERVED_PROPERTY,
          forward ? SortDirection.ASCENDING : SortDirection.DESCENDING);
  if (keysOnly) {
    q.setKeysOnly();
  }
  return tx.prepare(q).asIterator(fetchOptions);
}
项目:walkaround    文件:MutationLog.java   
@Nullable private SnapshotEntry getSnapshotEntryAtOrBefore(@Nullable Long atOrBeforeVersion)
    throws RetryableFailure, PermanentFailure {
  Query q = new Query(snapshotEntityKind)
      .setAncestor(makeRootEntityKey(objectId))
      .addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.DESCENDING);
  if (atOrBeforeVersion != null) {
    q.setFilter(FilterOperator.LESS_THAN_OR_EQUAL.of(Entity.KEY_RESERVED_PROPERTY,
        makeSnapshotKey(objectId, atOrBeforeVersion)));
  }
  Entity e = tx.prepare(q).getFirstResult();
  log.info("query " + q + " returned first result " + e);
  if (e == null) {
    return null;
  } else {
    snapshotPropertyMover.postGet(e);
    return parseSnapshot(e);
  }
}
项目:amazon-price-tracker    文件:SharedlistServlet.java   
public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    resp.setContentType("text/html");
    resp.getWriter().println("<html><body>");

    DatastoreService datastore = DatastoreServiceFactory
            .getDatastoreService();
    Query query = new Query("SharedList");
    query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);
    List<Entity> results = datastore.prepare(query).asList(
            FetchOptions.Builder.withDefaults());
    for (Entity entity : results) {
        String email = (String) entity.getProperty("email");
        String productID = (String) entity.getKey().getName();
        String productName = (String) entity.getProperty("productName");
        Date sharedDate = (Date) entity.getProperty("sharedDate");

        resp.getWriter().println(
                email + " shared <a href=\"http://www.amazon.com/dp/"
                        + productID + "\" target=\"_blank\">" + "<b>"
                        + productName + "</b></a>!<br>");
    }

    resp.getWriter().println("</body></html>");
}
项目:amazon-price-tracker    文件:Sharedlist.java   
@GET
@Produces(MediaType.TEXT_XML)
public List<SharedProduct> getEntitiesBrowser() {
    List<SharedProduct> list = new ArrayList<SharedProduct>();
    DatastoreService datastore = DatastoreServiceFactory
            .getDatastoreService();
    Query query = new Query("SharedList");
    query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);
    List<Entity> results = datastore.prepare(query).asList(
            FetchOptions.Builder.withDefaults());
    for (Entity entity : results) {
        String email = (String) entity.getProperty("email");
        String productID = (String) entity.getKey().getName();
        String productName = (String) entity.getProperty("productName");
        Date sharedDate = (Date) entity.getProperty("sharedDate");

        list.add(new SharedProduct(email, productID, productName,
                sharedDate));
    }

    return list;
}
项目:amazon-price-tracker    文件:Sharedlist.java   
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public List<SharedProduct> getEntities() {
    List<SharedProduct> list = new ArrayList<SharedProduct>();
    DatastoreService datastore = DatastoreServiceFactory
            .getDatastoreService();
    Query query = new Query("SharedList");
    query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);
    List<Entity> results = datastore.prepare(query).asList(
            FetchOptions.Builder.withDefaults());
    for (Entity entity : results) {
        String email = (String) entity.getProperty("email");
        String productID = (String) entity.getKey().getName();
        String productName = (String) entity.getProperty("productName");
        Date sharedDate = (Date) entity.getProperty("sharedDate");

        list.add(new SharedProduct(email, productID, productName,
                sharedDate));
    }

    return list;
}
项目:getting-started-java    文件:DatastoreDao.java   
@Override
public Result<Book> listBooks(String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      .addSort(Book.TITLE, SortDirection.ASCENDING); // Use default Index "title"
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
项目:getting-started-java    文件:DatastoreDao.java   
@Override
public Result<Book> listBooksByUser(String userId, String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      // Only for this user
      .setFilter(new Query.FilterPredicate(
          Book.CREATED_BY_ID, Query.FilterOperator.EQUAL, userId))
      // a custom datastore index is required since you are filtering by one property
      // but ordering by another
      .addSort(Book.TITLE, SortDirection.ASCENDING);
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
项目:getting-started-java    文件:DatastoreDao.java   
@Override
public Result<Book> listBooks(String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      .addSort(Book.TITLE, SortDirection.ASCENDING); // Use default Index "title"
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
项目:getting-started-java    文件:DatastoreDao.java   
@Override
public Result<Book> listBooks(String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      .addSort(Book.TITLE, SortDirection.ASCENDING); // Use default Index "title"
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
项目:getting-started-java    文件:DatastoreDao.java   
@Override
public Result<Book> listBooks(String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      .addSort(Book.TITLE, SortDirection.ASCENDING); // Use default Index "title"
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
项目:getting-started-java    文件:DatastoreDao.java   
@Override
public Result<Book> listBooksByUser(String userId, String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      // Only for this user
      .setFilter(new Query.FilterPredicate(
          Book.CREATED_BY_ID, Query.FilterOperator.EQUAL, userId))
      // a custom datastore index is required since you are filtering by one property
      // but ordering by another
      .addSort(Book.TITLE, SortDirection.ASCENDING);
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
项目: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   
/**
 * 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    文件:MetadataPropertiesTest.java   
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());
    }
  }
项目: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    文件:MetadataPropertiesTest.java   
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());
    }
  }
项目: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.
}
项目:realtime-server-appengine    文件:MutationLog.java   
private CheckedIterator getDeltaEntityIterator(long startVersion, @Nullable Long endVersion,
    FetchOptions fetchOptions, boolean forward, boolean keysOnly) throws PermanentFailure,
    RetryableFailure {
  checkRange(startVersion, endVersion);
  if (endVersion != null && startVersion == endVersion) {
    return CheckedIterator.EMPTY;
  }
  Query.Filter filter =
      FilterOperator.GREATER_THAN_OR_EQUAL.of(Entity.KEY_RESERVED_PROPERTY, makeDeltaKey(
          objectId, startVersion));
  if (endVersion != null) {
    filter =
        Query.CompositeFilterOperator.and(filter, FilterOperator.LESS_THAN.of(
            Entity.KEY_RESERVED_PROPERTY, makeDeltaKey(objectId, endVersion)));
  }
  Query q =
      new Query(objectId.getKind() + DELTA_ENTITY_KIND).setAncestor(makeRootEntityKey(objectId))
          .setFilter(filter).addSort(Entity.KEY_RESERVED_PROPERTY,
              forward ? SortDirection.ASCENDING : SortDirection.DESCENDING);
  if (keysOnly) {
    q.setKeysOnly();
  }
  return tx.prepare(q).asIterator(fetchOptions);
}
项目:realtime-server-appengine    文件:MutationLog.java   
@Nullable
private SnapshotEntry getSnapshotEntryAtOrBefore(@Nullable Long atOrBeforeVersion)
    throws RetryableFailure, PermanentFailure {
  Query q =
      new Query(objectId.getKind() + SNAPSHOT_ENTITY_KIND).setAncestor(
          makeRootEntityKey(objectId)).addSort(Entity.KEY_RESERVED_PROPERTY,
          SortDirection.DESCENDING);
  if (atOrBeforeVersion != null) {
    q.setFilter(FilterOperator.LESS_THAN_OR_EQUAL.of(Entity.KEY_RESERVED_PROPERTY,
        makeSnapshotKey(objectId, atOrBeforeVersion)));
  }
  Entity e = tx.prepare(q).getFirstResult();
  log.info("query " + q + " returned first result " + e);
  if (e == null) {
    return null;
  } else {
    snapshotPropertyMover.postGet(e);
    return parseSnapshot(e);
  }
}
项目:LeaderboardServer    文件:ScoreDAO.java   
/**
 * Method to retrieve the global high scores 
 * @return
 */
public List<Entity> getGlobalHighScores(){
    log.info("Retrieving global high scores");
    //create the query to read the records sorted by score
    Query q = new Query(Constants.RECORD).addSort(Constants.SCORE, SortDirection.DESCENDING);
    PreparedQuery pq = datastore.prepare(q);
    //retrieve and return the list of records   
    return pq.asList(FetchOptions.Builder.withLimit(100));
}
项目:amazon-price-tracker    文件:Wishlist.java   
@GET
@Produces(MediaType.TEXT_XML)
public List<WishlistProduct> getEntitiesBrowser() {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if (user == null) {
        System.out.println("Login first");
        return null;
    }

    List<WishlistProduct> list = new ArrayList<WishlistProduct>();
    DatastoreService datastore = DatastoreServiceFactory
            .getDatastoreService();
    Query query = new Query(user.getEmail());
    query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);
    List<Entity> results = datastore.prepare(query).asList(
            FetchOptions.Builder.withDefaults());
    for (Entity entity : results) {
        String productID = (String) entity.getKey().getName();
        String productName = (String) entity.getProperty("productName");
        double currentPrice = (double) entity.getProperty("currentPrice");
        double lowestPrice = (double) entity.getProperty("lowestPrice");
        Date lowestDate = (Date) entity.getProperty("lowestDate");
        list.add(new WishlistProduct(productID, productName, currentPrice,
                lowestPrice, lowestDate));
    }

    return list;
}
项目:amazon-price-tracker    文件:Wishlist.java   
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public List<WishlistProduct> getEntities() {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if (user == null) {
        System.out.println("Login first");
        return null;
    }

    List<WishlistProduct> list = new ArrayList<WishlistProduct>();
    DatastoreService datastore = DatastoreServiceFactory
            .getDatastoreService();
    Query query = new Query(user.getEmail());
    query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);
    List<Entity> results = datastore.prepare(query).asList(
            FetchOptions.Builder.withDefaults());
    for (Entity entity : results) {
        String productID = (String) entity.getKey().getName();
        String productName = (String) entity.getProperty("productName");
        double currentPrice = (double) entity.getProperty("currentPrice");
        double lowestPrice = (double) entity.getProperty("lowestPrice");
        Date lowestDate = (Date) entity.getProperty("lowestDate");
        list.add(new WishlistProduct(productID, productName, currentPrice,
                lowestPrice, lowestDate));
    }

    return list;
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void sortOrderExample_returnsSortedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("lastName", "Alpha");
  a.setProperty("height", 100);
  Entity b = new Entity("Person", "b");
  b.setProperty("lastName", "Bravo");
  b.setProperty("height", 200);
  Entity c = new Entity("Person", "c");
  c.setProperty("lastName", "Charlie");
  c.setProperty("height", 300);
  datastore.put(ImmutableList.<Entity>of(a, b, c));

  // Act
  // [START sort_order_example]
  // Order alphabetically by last name:
  Query q1 = new Query("Person").addSort("lastName", SortDirection.ASCENDING);

  // Order by height, tallest to shortest:
  Query q2 = new Query("Person").addSort("height", SortDirection.DESCENDING);
  // [END sort_order_example]

  // Assert
  List<Entity> lastNameResults =
      datastore.prepare(q1.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(lastNameResults).named("last name query results").containsExactly(a, b, c).inOrder();
  List<Entity> heightResults =
      datastore.prepare(q2.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(heightResults).named("height query results").containsExactly(c, b, a).inOrder();
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void sortOrderExample_multipleSortOrders_returnsSortedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("lastName", "Alpha");
  a.setProperty("height", 100);
  Entity b1 = new Entity("Person", "b1");
  b1.setProperty("lastName", "Bravo");
  b1.setProperty("height", 150);
  Entity b2 = new Entity("Person", "b2");
  b2.setProperty("lastName", "Bravo");
  b2.setProperty("height", 200);
  Entity c = new Entity("Person", "c");
  c.setProperty("lastName", "Charlie");
  c.setProperty("height", 300);
  datastore.put(ImmutableList.<Entity>of(a, b1, b2, c));

  // Act
  // [START multiple_sort_orders_example]
  Query q =
      new Query("Person")
          .addSort("lastName", SortDirection.ASCENDING)
          .addSort("height", SortDirection.DESCENDING);
  // [END multiple_sort_orders_example]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results).named("query results").containsExactly(a, b2, b1, c).inOrder();
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void queryRestrictions_inequalitySortedFirst_returnsMatchedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("birthYear", 1930);
  a.setProperty("lastName", "Someone");
  Entity b = new Entity("Person", "b");
  b.setProperty("birthYear", 1990);
  b.setProperty("lastName", "Bravo");
  Entity c = new Entity("Person", "c");
  c.setProperty("birthYear", 1960);
  c.setProperty("lastName", "Charlie");
  Entity d = new Entity("Person", "d");
  d.setProperty("birthYear", 1960);
  d.setProperty("lastName", "Delta");
  datastore.put(ImmutableList.<Entity>of(a, b, c, d));
  long minBirthYear = 1940;

  // [START inequality_filters_sort_orders_valid_example]
  Filter birthYearMinFilter =
      new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);

  Query q =
      new Query("Person")
          .setFilter(birthYearMinFilter)
          .addSort("birthYear", SortDirection.ASCENDING)
          .addSort("lastName", SortDirection.ASCENDING);
  // [END inequality_filters_sort_orders_valid_example]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results).named("query results").containsExactly(c, d, b).inOrder();
}
项目:java-docs-samples    文件:QueriesTest.java   
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));
}
项目:java-docs-samples    文件:ListPeopleServletTest.java   
private String getFirstCursor() {
  Query q = new Query("Person").addSort("name", SortDirection.ASCENDING);
  PreparedQuery pq = datastore.prepare(q);
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(ListPeopleServlet.PAGE_SIZE);
  QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
  return results.getCursor().toWebSafeString();
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void sortOrderExample_returnsSortedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("lastName", "Alpha");
  a.setProperty("height", 100);
  Entity b = new Entity("Person", "b");
  b.setProperty("lastName", "Bravo");
  b.setProperty("height", 200);
  Entity c = new Entity("Person", "c");
  c.setProperty("lastName", "Charlie");
  c.setProperty("height", 300);
  datastore.put(ImmutableList.<Entity>of(a, b, c));

  // Act
  // [START sort_order_example]
  // Order alphabetically by last name:
  Query q1 = new Query("Person").addSort("lastName", SortDirection.ASCENDING);

  // Order by height, tallest to shortest:
  Query q2 = new Query("Person").addSort("height", SortDirection.DESCENDING);
  // [END sort_order_example]

  // Assert
  List<Entity> lastNameResults =
      datastore.prepare(q1.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(lastNameResults).named("last name query results").containsExactly(a, b, c).inOrder();
  List<Entity> heightResults =
      datastore.prepare(q2.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(heightResults).named("height query results").containsExactly(c, b, a).inOrder();
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void sortOrderExample_multipleSortOrders_returnsSortedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("lastName", "Alpha");
  a.setProperty("height", 100);
  Entity b1 = new Entity("Person", "b1");
  b1.setProperty("lastName", "Bravo");
  b1.setProperty("height", 150);
  Entity b2 = new Entity("Person", "b2");
  b2.setProperty("lastName", "Bravo");
  b2.setProperty("height", 200);
  Entity c = new Entity("Person", "c");
  c.setProperty("lastName", "Charlie");
  c.setProperty("height", 300);
  datastore.put(ImmutableList.<Entity>of(a, b1, b2, c));

  // Act
  // [START multiple_sort_orders_example]
  Query q =
      new Query("Person")
          .addSort("lastName", SortDirection.ASCENDING)
          .addSort("height", SortDirection.DESCENDING);
  // [END multiple_sort_orders_example]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results).named("query results").containsExactly(a, b2, b1, c).inOrder();
}
项目:java-docs-samples    文件:QueriesTest.java   
@Test
public void queryRestrictions_inequalitySortedFirst_returnsMatchedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("birthYear", 1930);
  a.setProperty("lastName", "Someone");
  Entity b = new Entity("Person", "b");
  b.setProperty("birthYear", 1990);
  b.setProperty("lastName", "Bravo");
  Entity c = new Entity("Person", "c");
  c.setProperty("birthYear", 1960);
  c.setProperty("lastName", "Charlie");
  Entity d = new Entity("Person", "d");
  d.setProperty("birthYear", 1960);
  d.setProperty("lastName", "Delta");
  datastore.put(ImmutableList.<Entity>of(a, b, c, d));
  long minBirthYear = 1940;

  // [START inequality_filters_sort_orders_valid_example]
  Filter birthYearMinFilter =
      new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);

  Query q =
      new Query("Person")
          .setFilter(birthYearMinFilter)
          .addSort("birthYear", SortDirection.ASCENDING)
          .addSort("lastName", SortDirection.ASCENDING);
  // [END inequality_filters_sort_orders_valid_example]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertThat(results).named("query results").containsExactly(c, d, b).inOrder();
}
项目:java-docs-samples    文件:QueriesTest.java   
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));
}
项目:java-docs-samples    文件:ListPeopleServletTest.java   
private String getFirstCursor() {
  Query q = new Query("Person").addSort("name", SortDirection.ASCENDING);
  PreparedQuery pq = datastore.prepare(q);
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(ListPeopleServlet.PAGE_SIZE);
  QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
  return results.getCursor().toWebSafeString();
}