Java Code Examples for com.google.appengine.api.datastore.Cursor#toWebSafeString()

The following examples show how to use com.google.appengine.api.datastore.Cursor#toWebSafeString() . 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: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 2
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 3
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 4
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 5
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 6
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 7
Source File: OfferEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method lists all the entities inserted in datastore.
 * It uses HTTP GET method and paging support.
 *
 * @return A CollectionResponse class containing the list of all entities
 * persisted and a cursor to the next page.
 */
@SuppressWarnings({"unchecked", "unused"})
@ApiMethod(name = "listOffer")
public CollectionResponse<Offer> listOffer(
    @Nullable @Named("cursor") String cursorString, @Nullable @Named("limit") Integer limit) {

  EntityManager mgr = null;
  Cursor cursor = null;
  List<Offer> execute = null;

  try {
    mgr = getEntityManager();
    Query query = mgr.createQuery("select from Offer as Offer");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    if (limit != null) {
      query.setFirstResult(0);
      query.setMaxResults(limit);
    }

    execute = (List<Offer>) query.getResultList();
    cursor = JPACursorHelper.getCursor(execute);
    if (cursor != null) cursorString = cursor.toWebSafeString();

    // Tight loop for fetching all entities from datastore and accomodate
    // for lazy fetch.
    for (Offer obj : execute);
  } finally {
    mgr.close();
  }

  return CollectionResponse.<Offer>builder()
      .setItems(execute).setNextPageToken(cursorString).build();
}
 
Example 8
Source File: RecommendationEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method lists all the entities inserted in datastore.
 * It uses HTTP GET method and paging support.
 *
 * @return A CollectionResponse class containing the list of all entities
 * persisted and a cursor to the next page.
 */
@SuppressWarnings({"unchecked", "unused"})
@ApiMethod(name = "listRecommendation")
public CollectionResponse<Recommendation> listRecommendation(
    @Nullable @Named("cursor") String cursorString, @Nullable @Named("limit") Integer limit) {

  EntityManager mgr = null;
  Cursor cursor = null;
  List<Recommendation> execute = null;

  try {
    mgr = getEntityManager();
    Query query = mgr.createQuery("select from Recommendation as Recommendation");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    if (limit != null) {
      query.setFirstResult(0);
      query.setMaxResults(limit);
    }

    execute = (List<Recommendation>) query.getResultList();
    cursor = JPACursorHelper.getCursor(execute);
    if (cursor != null) cursorString = cursor.toWebSafeString();

    // Tight loop for fetching all entities from datastore and accomodate
    // for lazy fetch.
    for (Recommendation obj : execute);
  } finally {
    mgr.close();
  }

  return CollectionResponse.<Recommendation>builder()
      .setItems(execute).setNextPageToken(cursorString).build();
}
 
Example 9
Source File: CheckInEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method lists all the entities inserted in datastore.
 * It uses HTTP GET method and paging support.
 *
 * @return A CollectionResponse class containing the list of all entities
 * persisted and a cursor to the next page.
 */
@SuppressWarnings({"unchecked", "unused"})
@ApiMethod(name = "listCheckIn")
public CollectionResponse<CheckIn> listCheckIn(
    @Nullable @Named("cursor") String cursorString, @Nullable @Named("limit") Integer limit) {

  EntityManager mgr = null;
  Cursor cursor = null;
  List<CheckIn> execute = null;

  try {
    mgr = getEntityManager();
    Query query = mgr.createQuery("select from CheckIn as CheckIn");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    if (limit != null) {
      query.setFirstResult(0);
      query.setMaxResults(limit);
    }

    execute = (List<CheckIn>) query.getResultList();
    cursor = JPACursorHelper.getCursor(execute);
    if (cursor != null) cursorString = cursor.toWebSafeString();

    // Tight loop for fetching all entities from datastore and accomodate
    // for lazy fetch.
    for (CheckIn obj : execute);
  } finally {
    mgr.close();
  }

  return CollectionResponse.<CheckIn>builder()
      .setItems(execute).setNextPageToken(cursorString).build();
}
 
Example 10
Source File: DeviceInfoEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method lists all the entities inserted in datastore.
 * It uses HTTP GET method and paging support.
 *
 * @return A CollectionResponse class containing the list of all entities
 * persisted and a cursor to the next page.
 */
@SuppressWarnings({"unchecked", "unused"})
@ApiMethod(name = "listDeviceInfo")
public CollectionResponse<DeviceInfo> listDeviceInfo(
    @Nullable @Named("cursor") String cursorString, @Nullable @Named("limit") Integer limit) {

  EntityManager mgr = null;
  Cursor cursor = null;
  List<DeviceInfo> execute = null;

  try {
    mgr = getEntityManager();
    Query query = mgr.createQuery("select from DeviceInfo as DeviceInfo");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    if (limit != null) {
      query.setFirstResult(0);
      query.setMaxResults(limit);
    }

    execute = (List<DeviceInfo>) query.getResultList();
    cursor = JPACursorHelper.getCursor(execute);
    if (cursor != null) cursorString = cursor.toWebSafeString();

    // Tight loop for fetching all entities from datastore and accomodate
    // for lazy fetch.
    for (DeviceInfo obj : execute);
  } finally {
    mgr.close();
  }

  return CollectionResponse.<DeviceInfo>builder()
      .setItems(execute).setNextPageToken(cursorString).build();
}
 
Example 11
Source File: PlaceEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method lists all the entities inserted in datastore.
 * It uses HTTP GET method and paging support.
 *
 * @return A CollectionResponse class containing the list of all entities
 * persisted and a cursor to the next page.
 */
@SuppressWarnings({"unchecked", "unused"})
@ApiMethod(name = "listPlace")
public CollectionResponse<Place> listPlace(
    @Nullable @Named("cursor") String cursorString, @Nullable @Named("limit") Integer limit) {

  EntityManager mgr = null;
  Cursor cursor = null;
  List<Place> execute = null;

  try {
    mgr = getEntityManager();
    Query query = mgr.createQuery("select from Place as Place");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    if (limit != null) {
      query.setFirstResult(0);
      query.setMaxResults(limit);
    }

    execute = (List<Place>) query.getResultList();
    cursor = JPACursorHelper.getCursor(execute);
    if (cursor != null) cursorString = cursor.toWebSafeString();

    // Tight loop for fetching all entities from datastore and accomodate
    // for lazy fetch.
    for (Place obj : execute);
  } finally {
    mgr.close();
  }

  return CollectionResponse.<Place>builder()
      .setItems(execute).setNextPageToken(cursorString).build();
}
 
Example 12
Source File: LocalRawGcsService.java    From appengine-gcs-client with Apache License 2.0 4 votes vote down vote up
@Override
public ListItemBatch list(String bucket, String prefix, String delimiter,
    String marker, int maxResults, long timeoutMillis) throws IOException {
  ensureInitialized();
  Query query = makeQuery(bucket);
  int prefixLength;
  if (!Strings.isNullOrEmpty(prefix)) {
    Key keyPrefix = makeKey(bucket, prefix);
    query.setFilter(new FilterPredicate(KEY_RESERVED_PROPERTY, GREATER_THAN_OR_EQUAL, keyPrefix));
    prefixLength = prefix.length();
  } else {
    prefixLength = 0;
  }
  FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
  if (marker != null) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(marker));
  }
  List<ListItem> items = new ArrayList<>(maxResults);
  Set<String> prefixes = new HashSet<>();
  QueryResultIterator<Entity> dsResults =
      datastore.prepare(query).asQueryResultIterator(fetchOptions);
  while (items.size() < maxResults && dsResults.hasNext()) {
    Entity entity = dsResults.next();
    String name = entity.getKey().getName();
    if (prefixLength > 0 && !name.startsWith(prefix)) {
      break;
    }
    if (!Strings.isNullOrEmpty(delimiter)) {
      int delimiterIdx = name.indexOf(delimiter, prefixLength);
      if (delimiterIdx > 0) {
        name = name.substring(0, delimiterIdx + 1);
        if (prefixes.add(name)) {
          items.add(new ListItem.Builder().setName(name).setDirectory(true).build());
        }
        continue;
      }
    }
    GcsFilename filename = new GcsFilename(bucket, name);
    GcsFileMetadata metadata = createGcsFileMetadata(entity, filename);
    ListItem listItem = new ListItem.Builder()
        .setName(name)
        .setLength(metadata.getLength())
        .setLastModified(metadata.getLastModified())
        .build();
    items.add(listItem);
  }
  Cursor cursor = dsResults.getCursor();
  String nextMarker = null;
  if (items.size() == maxResults && cursor != null) {
    nextMarker = cursor.toWebSafeString();
  }
  return new ListItemBatch(items, nextMarker);
}
 
Example 13
Source File: MessageEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 4 votes vote down vote up
/**
 * This function returns a list of messages starting with the newest message
 * first and in descending order from there
 * 
 * @param cursorString 
 *          for paging, empty for the first request, subsequent requests can
 *          use the returned information from an earlier request to fill this
 *          parameter
 * @param limit
 *          number of results returned for this query
 * @return
 *          A collection of MessageData items
 */
@SuppressWarnings({ "unchecked", "unused" })
@ApiMethod(name = "listMessages")
public CollectionResponse<MessageData> listMessages(
    @Nullable @Named("cursor") String cursorString,
    @Nullable @Named("limit") Integer limit) {

  EntityManager mgr = null;  
  Cursor cursor = null;
  List<MessageData> execute = null;
  
  try {
    mgr = getEntityManager();
    // query for messages, newest message first
    Query query = mgr
        .createQuery("select from MessageData as MessageData order by timestamp desc");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    if (limit != null) {
      query.setFirstResult(0);
      query.setMaxResults(limit);
    }

    execute = (List<MessageData>) query.getResultList();
    cursor = JPACursorHelper.getCursor(execute);
    if (cursor != null)
      cursorString = cursor.toWebSafeString();

    // Tight loop for fetching all entities from datastore and accomodate
    // for lazy fetch.
    for (MessageData obj : execute) {
      ;
    }
  } finally {
    mgr.close();
  }

  return CollectionResponse.<MessageData> builder().setItems(execute)
      .setNextPageToken(cursorString).build();
}
 
Example 14
Source File: PushPreProcessingServlet.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 4 votes vote down vote up
private void preprocessBatchOfDevices(String alertMessage, String cursorString) {
  EntityManager mgr = null;
  Cursor cursor = null;

  try {
    mgr = getEntityManager();

    // Retrieve entities (and not just deviceToken property) in order to paginate using cursor
    Query query = mgr.createQuery("select from DeviceRegistration as DeviceRegistration");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    query.setMaxResults(BATCH_SIZE);

    @SuppressWarnings("unchecked")
    List<DeviceRegistration> deviceRegistrations = query.getResultList();
    cursor = JPACursorHelper.getCursor(deviceRegistrations);
    if (cursor != null) {
      cursorString = cursor.toWebSafeString();
    }

    List<String> deviceTokens = new ArrayList<String>();
    for (DeviceRegistration deviceRegistartion : deviceRegistrations) {
      deviceTokens.add(deviceRegistartion.getDeviceToken());
    }

    if (deviceTokens.isEmpty()) {
      // no more matching device tokens matching this query.
      return;
    }

    mgr.getTransaction().begin();

    try {
      PushNotificationUtility.enqueuePushAlert(alertMessage, deviceTokens);

      if (deviceRegistrations.size() == BATCH_SIZE) {
        PushNotificationUtility.continueEnqueueingPushAlertToAllDevices(
            alertMessage, cursorString);
      }

      mgr.getTransaction().commit();
    } catch (RuntimeException e) {
      if (mgr.getTransaction().isActive()) {
        mgr.getTransaction().rollback();
      }
      throw e;
    }

  } finally {
    mgr.close();
  }
}