当前位置: 首页>>代码示例>>Java>>正文


Java QueryResultIterator.getCursor方法代码示例

本文整理汇总了Java中com.google.appengine.api.datastore.QueryResultIterator.getCursor方法的典型用法代码示例。如果您正苦于以下问题:Java QueryResultIterator.getCursor方法的具体用法?Java QueryResultIterator.getCursor怎么用?Java QueryResultIterator.getCursor使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.appengine.api.datastore.QueryResultIterator的用法示例。


在下文中一共展示了QueryResultIterator.getCursor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: listBooks

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
@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);
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:getting-started-java,代码行数:21,代码来源:DatastoreDao.java

示例2: listBooksByUser

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
@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);
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:getting-started-java,代码行数:26,代码来源:DatastoreDao.java

示例3: testCursor

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
@Test
public void testCursor() throws Exception {
    Entity parent = createTestEntityWithUniqueMethodNameKey("Person", "testKeysOnly");
    Key key = parent.getKey();

    Entity john = createEntity("Person", key)
        .withProperty("name", "John")
        .withProperty("surname", "Doe")
        .store();

    Query query = new Query("Person")
        .setAncestor(key)
        .setKeysOnly();

    PreparedQuery preparedQuery = service.prepare(query);
    QueryResultIterator<Entity> iter = preparedQuery.asQueryResultIterator();
    Assert.assertNotNull(iter.next());
    Cursor cursor = iter.getCursor();

    iter = service.prepare(query).asQueryResultIterator(FetchOptions.Builder.withStartCursor(cursor));
    Assert.assertFalse(iter.hasNext());
}
 
开发者ID:GoogleCloudPlatform,项目名称:appengine-tck,代码行数:23,代码来源:QueryResultTest.java

示例4: listQuote

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
@ApiMethod(name = "listUsers")
public CollectionResponse<Users> listQuote(@Nullable @com.google.api.server.spi.config.Named("cursor") String cursorString,
                                           @Nullable @com.google.api.server.spi.config.Named("count") Integer count) {

    Query<Users> query = ofy().load().type(Users.class);
    if (count != null) query.limit(count);
    if (cursorString != null && cursorString != "") {
        query = query.startAt(Cursor.fromWebSafeString(cursorString));
    }
    List<Users> records = new ArrayList<Users>();
    QueryResultIterator<Users> iterator = query.iterator();
    int num = 0;
    while (iterator.hasNext()) {
        records.add(iterator.next());
        if (count != null) {
            num++;
            if (num == count) break;
        }
    }
    //Find the next cursor
    if (cursorString != null && cursorString != "") {
        Cursor cursor = iterator.getCursor();
        if (cursor != null) {
            cursorString = cursor.toWebSafeString();
        }
    }
    return CollectionResponse.<Users>builder().setItems(records).setNextPageToken(cursorString).build();
}
 
开发者ID:LavanyaGanganna,项目名称:Capstoneproject1,代码行数:29,代码来源:MyEndpoint.java

示例5: merge

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
private String merge(String cursorString) {
    Query<UserAnswer> query = ofy().load().type(UserAnswer.class).limit(1000);
    List<UserAnswer> toSaveList = new ArrayList<UserAnswer>(); 

    if (cursorString != null) {
        query = query.startAt(Cursor.fromWebSafeString(cursorString));
    }

    boolean cont = false;
    QueryResultIterator<UserAnswer> iterator = query.iterator();

    while (iterator.hasNext()) {
        UserAnswer userAnswer = iterator.next();
        Map<String, String> answers = userAnswer.getAnswers();
        if(answers != null) {
            String answer = answers.get("householdIncome");
            if("$100,000-$149,999".equals(answer) || "$150,000-$199,999".equals(answer) ||
                    "$200,000-$249,999".equals(answer) || "$300,000 or more".equals(answer)) {
                answers.put("householdIncome", "$100,000 or more");
                toSaveList.add(userAnswer);
            }
        }
        cont = true;
    }

    if(toSaveList.size() > 0) {
        ofy().save().entities(toSaveList).now();
        logger.info(String.format("Merged %d answers", toSaveList.size()));
    }
    
    if(cont) {
        Cursor cursor = iterator.getCursor();
        return cursor.toWebSafeString();
    } else {
        return null;
    }
}
 
开发者ID:ipeirotis,项目名称:mturk-surveys,代码行数:38,代码来源:MergeAnswersServlet.java

示例6: approve

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
private String approve(String cursorString) {
    Query<UserAnswer> query = ofy().load().type(UserAnswer.class).limit(30);

    if (cursorString != null) {
        query = query.startAt(Cursor.fromWebSafeString(cursorString));
    }

    boolean cont = false;
    QueryResultIterator<UserAnswer> iterator = query.iterator();

    while (iterator.hasNext()) {
        UserAnswer userAnswer = iterator.next();
        try {
            List<Assignment> assignments = getAssignmentsForHITService.getAssignments(true, userAnswer.getHitId());
            for(Assignment assignment: assignments) {
                approveAssignmentService.approveAssignment(true, assignment.getAssignmentId());
            }
        } catch (MturkException e) {
            logger.log(Level.WARNING, e.getMessage());
        }
        cont = true;
    }

    if(cont) {
        Cursor cursor = iterator.getCursor();
        return cursor.toWebSafeString();
    } else {
        return null;
    }
}
 
开发者ID:ipeirotis,项目名称:mturk-surveys,代码行数:31,代码来源:ApproveAssignmentsServlet.java

示例7: dispose

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
private String dispose(String cursorString) {
    Calendar endCal = Calendar.getInstance();
    endCal.setTime(new Date());
    endCal.set(Calendar.HOUR_OF_DAY, 0);
    endCal.set(Calendar.MINUTE, 0);
    endCal.set(Calendar.SECOND, 0);
    
    Calendar startCal = Calendar.getInstance();
    startCal.setTime(endCal.getTime());
    startCal.add(Calendar.DAY_OF_MONTH, -1);

    Query<UserAnswer> query = ofy().load().type(UserAnswer.class)
            .filter("date >=", startCal.getTime()).filter("date <", endCal.getTime()).limit(30);

    if (cursorString != null) {
        query = query.startAt(Cursor.fromWebSafeString(cursorString));
    }

    boolean cont = false;
    QueryResultIterator<UserAnswer> iterator = query.iterator();

    while (iterator.hasNext()) {
        UserAnswer userAnswer = iterator.next();
        try {
            disposeHITService.disposeHIT(true, userAnswer.getHitId());
            logger.log(Level.INFO, String.format("Disposed HIT %s", userAnswer.getHitId()));
        } catch (MturkException e) {
            logger.log(Level.WARNING, e.getMessage());
        }
        cont = true;
    }

    if(cont) {
        Cursor cursor = iterator.getCursor();
        return cursor.toWebSafeString();
    } else {
        return null;
    }
}
 
开发者ID:ipeirotis,项目名称:mturk-surveys,代码行数:40,代码来源:DisposeHITsServlet.java

示例8: list

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
public CollectionResponse<UserAnswer> list(String cursorString, Integer limit) throws NoSuchAlgorithmException {
    List<UserAnswer> result = new ArrayList<UserAnswer>();
    Query<UserAnswer> query = ofy().load().type(UserAnswer.class)
            .filter("surveyId", DEMOGRAPHICS_SURVEY_ID).order("-date");

    if(cursorString != null) {
        query = query.startAt(Cursor.fromWebSafeString(cursorString));
    }

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

    boolean cont = false;
    QueryResultIterator<UserAnswer> iterator = query.iterator();

    while (iterator.hasNext()) {
        UserAnswer userAnswer = iterator.next();
        String workerId = userAnswer.getWorkerId();
        if(workerId != null) {
            userAnswer.setWorkerId(MD5.crypt(workerId));
        }
        userAnswer.setIp(null);
        result.add(userAnswer);
        cont = true;
    }

    if(cont) {
        Cursor cursor = iterator.getCursor();
        return CollectionResponse.<UserAnswer> builder().setItems(result).setNextPageToken(cursor.toWebSafeString()).build();
    } else {
        return CollectionResponse.<UserAnswer> builder().setItems(result).build();
    }
}
 
开发者ID:ipeirotis,项目名称:mturk-surveys,代码行数:35,代码来源:UserAnswerService.java

示例9: testReverse

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
@Test
public void testReverse() {
    Query query = new Query(kindName, rootKey);
    query.addSort(Entity.KEY_RESERVED_PROPERTY);
    QueryResultIterator<Entity> iter = service.prepare(query).asQueryResultIterator();
    Entity e1 = iter.next();
    Entity e2 = iter.next();
    Cursor cursor = iter.getCursor();
    //reverse
    query = query.reverse();
    cursor = cursor.reverse();
    iter = service.prepare(query).asQueryResultIterator(FetchOptions.Builder.withStartCursor(cursor));
    Assert.assertEquals(e2, iter.next());
    Assert.assertEquals(e1, iter.next());
}
 
开发者ID:GoogleCloudPlatform,项目名称:appengine-tck,代码行数:16,代码来源:CursorTest.java

示例10: execute

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
public Result<T> execute() {
  QueryResultIterator<T> queryIter = getOfyQuery().iterator();
  List<T> searchResults = Lists.newArrayList(Iterators.limit(queryIter, limit));
  Cursor nextCursor = queryIter.getCursor();
  PagingInfo pagingInfo =
      (uriInfo == null) ?
          null :
          PagingInfo.create(nextCursor, limit, queryIter.hasNext(), uriInfo);
  return new Result<T>(searchResults, nextCursor, pagingInfo, this);
}
 
开发者ID:karma-exchange-org,项目名称:karma-exchange,代码行数:11,代码来源:PaginatedQuery.java

示例11: run

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
@Override
public void run()
{
  long startTime = System.currentTimeMillis();
  Query<T> query = getQuery();
  if( query == null )
  {
    return;
  }
  if( m_cursor != null )
  {
    query.startCursor( m_cursor );
  }
  else if( m_offset != 0 )
  {
    query.offset( m_offset );
  }
  QueryResultIterator<Key<T>> iterator = query.fetchKeys().iterator();
  while( iterator.hasNext() )
  {
    try
    {
      processKey( iterator.next() );
    } catch( Exception e )
    {
      log.error( e );
    } catch( Throwable th )
    {
      log.error( th.getMessage() );
    }
    m_offset++;

    if( System.currentTimeMillis() - startTime > LIMIT_MILLIS )
    {
      // synchro isn't finished: add task
      m_cursor = iterator.getCursor();
      if( iterator.hasNext() )
      {
        if( m_cursor == null )
        {
          log.warning( "Query isn't finished but can't be resumed with cursor: " + query );
        }
        QueueFactory.getQueue( "longDBTask" ).add(
            TaskOptions.Builder.withPayload( this ).header( "X-AppEngine-FailFast", "true" ) );
        return;
      }
      // ok we finished just in time :)
      break;
    }
  }
  m_cursor = null;

  finish();
}
 
开发者ID:kroc702,项目名称:fullmetalgalaxy,代码行数:55,代码来源:LongDBTask.java

示例12: run

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
/**
 * This method is called as many time needed for one synchronization session.
 */
@Override
public void run()
{
  long startTime = System.currentTimeMillis();
  Query<EbGamePreview> query = FmgDataStore.dao().query( EbGamePreview.class );

  query.filter( "m_history", false );
  query.filter( "m_status", GameStatus.Running );
  if( m_cursor != null )
  {
    query.startCursor( m_cursor );
  }

  QueryResultIterator<Key<EbGamePreview>> iterator = query.fetchKeys().iterator();
  while( iterator.hasNext() )
  {
    FmgDataStore ds = new FmgDataStore( false );
    Game game = ds.getGame( iterator.next() );
    ModelFmpUpdate modelUpdate = new ModelFmpUpdate( game );
    ArrayList<AnEvent> eventAdded = new ArrayList<AnEvent>();
    try
    {
      eventAdded = GameWorkflow.checkUpdate2Unblock( game );
      eventAdded.addAll( GameWorkflow.checkUpdate( game ) );
    } catch( RpcFmpException e )
    {
      log.error( e );
    }

    if( !eventAdded.isEmpty() || game.getStatus() == GameStatus.History )
    {
      // something changed in this game: save it

      // do we need to send an email ?
      modelUpdate.getGameEvents().addAll( eventAdded );
      GameNotification.sendMail( game, modelUpdate );

      // and save game
      ds.put( game );
      ds.close();
    }

    if( System.currentTimeMillis() - startTime > LIMIT_MILLIS )
    {
      Cursor cursor = iterator.getCursor();
      // synchro isn't finished: add task
      QueueFactory.getDefaultQueue().add(
          TaskOptions.Builder.withPayload( new GameUpdateCommand( cursor ) ).header(
              "X-AppEngine-FailFast", "true" ) );
      break;
    }
  }

  // after job is finished, delete too old aborted game
  if( !iterator.hasNext() )
  {
    QueueFactory.getDefaultQueue().add(
        TaskOptions.Builder.withPayload( new DeleteOldAbortedGameCommand() ).header(
            "X-AppEngine-FailFast", "true" ) );

  }
}
 
开发者ID:kroc702,项目名称:fullmetalgalaxy,代码行数:66,代码来源:GameUpdate.java

示例13: list

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
@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);
}
 
开发者ID:GoogleCloudPlatform,项目名称:appengine-gcs-client,代码行数:54,代码来源:LocalRawGcsService.java

示例14: getRawPointsByTrail

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
/**
 * This method returns the array of points of a trail
 * @author JJMS ([email protected])
 * @since 16 / feb / 2016
 * @version 1.0.0.0
 * @param parameter
 *            The id the id of the trail to search for.
 * @return The arrayList of points of the trail
 * @throws TrailNotFoundException
 *             If the trail is not found
 */
public TrailPointsResult getRawPointsByTrail(TrailPointsRequestParameter parameter) throws TrailNotFoundException{

	logger.debug("Getting raw points for trail " + parameter);

	TrailPointsResult result = new TrailPointsResult();
	ArrayList<TrailPointWrapper> points = new ArrayList<TrailPointWrapper>();
	Query<RawTrailPoint> query = OfyService.ofy().load().type(RawTrailPoint.class)
		.filter("trailId", parameter.getTrailId())
		.order("pointData.timeStamp");
	
	query = CursorHelper.processCursor(query, parameter);


	QueryResultIterator<RawTrailPoint> pointsIterator = query.iterator();

	while(pointsIterator.hasNext()){
		RawTrailPoint point = pointsIterator.next();
		points.add(new TrailPointWrapper(point.getPointData().getLocation(),
			TimeStampUtils.dateToTimestamp(point.getPointData().getTimeStamp())));
	}

	Cursor cursor = pointsIterator.getCursor();

	result.setPoints(points);
	result.setCursor(cursor.toWebSafeString());

	logger.debug("Raw points of the trail: " + result);

	return result;
}
 
开发者ID:LabPLC,项目名称:MapatonAPI,代码行数:42,代码来源:TrailsHandler.java

示例15: getSnappedPointsByTrail

import com.google.appengine.api.datastore.QueryResultIterator; //导入方法依赖的package包/类
/**
 * This method returns the snapped points for trail.
 * @author Juanjo ([email protected]) 
 * @since 16 / feb / 2016
 * @param parameter The object contaiing all the parameters for the request.
 * @return The list of points
 * @throws TrailNotFoundException 
 */
public static TrailPointsResult getSnappedPointsByTrail(TrailPointsRequestParameter parameter) throws TrailNotFoundException{
	
	logger.debug("Getting snapped points for trail " + parameter);

	TrailPointsResult result = new TrailPointsResult();
	ArrayList<TrailPointWrapper> points = new ArrayList<TrailPointWrapper>();
	
	Query<SnappedTrailPoint> query = OfyService.ofy().load().type(SnappedTrailPoint.class)
		.filter("trailId", parameter.getTrailId())
		.order("position");
	
	

	query = CursorHelper.processCursor(query, parameter);
	
	QueryResultIterator<SnappedTrailPoint> pointsIterator = query.iterator();

	while(pointsIterator.hasNext()){
		SnappedTrailPoint point = pointsIterator.next();
		points.add(new TrailPointWrapper(point.getLocation(), point.getPosition()));
	}

	Cursor cursor = pointsIterator.getCursor();

	result.setPoints(points);
	result.setCursor(cursor.toWebSafeString());

	logger.debug("Number of Snapped points "+points.size());
	logger.debug("Snapped points of the trail: " + result);

	return result;
}
 
开发者ID:LabPLC,项目名称:MapatonAPI,代码行数:41,代码来源:TrailsHandler.java


注:本文中的com.google.appengine.api.datastore.QueryResultIterator.getCursor方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。