本文整理匯總了Java中com.google.appengine.api.datastore.FetchOptions.startCursor方法的典型用法代碼示例。如果您正苦於以下問題:Java FetchOptions.startCursor方法的具體用法?Java FetchOptions.startCursor怎麽用?Java FetchOptions.startCursor使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.google.appengine.api.datastore.FetchOptions
的用法示例。
在下文中一共展示了FetchOptions.startCursor方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: listBooks
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的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);
}
}
示例2: listBooksByUser
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的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);
}
}
示例3: countEntities
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的package包/類
/**
* Counts the entities returned by the specified query.
* @param ds reference to the datastore service
* @param query query whose results to count
* @return the number of entities returned by the query
*/
public static int countEntities( final DatastoreService ds, final com.google.appengine.api.datastore.Query q ) {
q.setKeysOnly();
final int batchSize = 1000;
final FetchOptions fetchOptions = FetchOptions.Builder.withLimit( batchSize );
Cursor cursor = null;
int count = 0;
while ( true ) {
if ( cursor != null )
fetchOptions.startCursor( cursor );
final QueryResultList< Entity > resultList = ds.prepare( q ).asQueryResultList( fetchOptions );
count += resultList.size();
if ( resultList.size() < batchSize )
return count;
cursor = resultList.getCursor();
}
}
示例4: checkPage
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的package包/類
private Cursor checkPage(Query query, Cursor stCursor, Cursor endCursor, int limit, int exptRet,
String chkSt, String chkEnd) {
FetchOptions fetchOption = FetchOptions.Builder.withLimit(limit);
if (stCursor != null) {
fetchOption = fetchOption.startCursor(stCursor);
}
if (endCursor != null) {
fetchOption = fetchOption.endCursor(endCursor);
}
QueryResultList<Entity> nextBatch = service.prepare(query)
.asQueryResultList(fetchOption);
assertEquals(exptRet, nextBatch.size());
if (chkSt != null) {
assertEquals(chkSt, nextBatch.get(0).getProperty("name"));
}
if (chkEnd != null) {
assertEquals(chkEnd, nextBatch.get(nextBatch.size() - 1).getProperty("name"));
}
return nextBatch.getCursor();
}
示例5: queryRootPipelines
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的package包/類
@Override
public Pair<? extends Iterable<JobRecord>, String> queryRootPipelines(String classFilter,
String cursor, final int limit) {
Query query = new Query(JobRecord.DATA_STORE_KIND);
Filter filter = classFilter == null || classFilter.isEmpty() ? new FilterPredicate(
ROOT_JOB_DISPLAY_NAME, GREATER_THAN, null)
: new FilterPredicate(ROOT_JOB_DISPLAY_NAME, EQUAL, classFilter);
query.setFilter(filter);
final PreparedQuery preparedQuery = dataStore.prepare(query);
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
if (limit > 0) {
fetchOptions.limit(limit + 1);
}
if (cursor != null) {
fetchOptions.startCursor(Cursor.fromWebSafeString(cursor));
}
return tryFiveTimes(
new Operation<Pair<? extends Iterable<JobRecord>, String>>("queryRootPipelines") {
@Override
public Pair<? extends Iterable<JobRecord>, String> call() {
QueryResultIterator<Entity> entities =
preparedQuery.asQueryResultIterable(fetchOptions).iterator();
Cursor dsCursor = null;
List<JobRecord> roots = new LinkedList<>();
while (entities.hasNext()) {
if (limit > 0 && roots.size() >= limit) {
dsCursor = entities.getCursor();
break;
}
JobRecord jobRecord = new JobRecord(entities.next());
roots.add(jobRecord);
}
return Pair.of(roots, dsCursor == null ? null : dsCursor.toWebSafeString());
}
});
}
示例6: deleteAllContinuously
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的package包/類
/**
* Deletes all device subscription entities continuously using task push queue.
*
* @param time Threshold time before which entities created will be deleted. If time is null,
* current time is used and set as Threshold time.
* @param cursor Query cursor indicates last query result set position
*/
protected void deleteAllContinuously(Date time, String cursor) {
if (time == null) {
time = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
}
Query.FilterPredicate timeFilter = new Query.FilterPredicate(PROPERTY_TIMESTAMP,
FilterOperator.LESS_THAN_OR_EQUAL, time);
QueryResultIterable<Entity> entities;
List<Key> keys = new ArrayList<Key> ();
List<String> subIds = new ArrayList<String> ();
Query queryAll;
queryAll = new Query(DeviceSubscription.SUBSCRIPTION_KIND).setFilter(timeFilter);
FetchOptions options = FetchOptions.Builder.withLimit(BATCH_DELETE_SIZE);
if (!StringUtility.isNullOrEmpty(cursor)) {
options.startCursor(Cursor.fromWebSafeString(cursor));
}
entities = this.datastoreService.prepare(queryAll).asQueryResultIterable(options);
if (entities != null && entities.iterator() != null) {
for (Entity entity : entities) {
keys.add(entity.getKey());
String[] ids = new Gson().fromJson((String) entity.getProperty(PROPERTY_SUBSCRIPTION_IDS),
String[].class);
subIds.addAll(Arrays.asList(ids));
}
}
if (keys.size() > 0) {
deleteInBatch(keys);
enqueueDeleteDeviceSubscription(time, entities.iterator().getCursor().toWebSafeString());
}
if (subIds.size() > 0) {
deletePsiSubscriptions(subIds);
}
}
示例7: processEntities
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的package包/類
/**
* Processes the entities meeting the criteria defined by the query filter.
* @return the string representation of the updated count
*/
public String processEntities() {
if ( maxUpdates <= 0 )
return getProcessedCountString();
if ( batchSize == null )
batchSize = 500;
if ( maxUpdates < batchSize )
batchSize = maxUpdates;
final DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
final FetchOptions fetchOptions = FetchOptions.Builder.withLimit( batchSize );
Cursor cursor = null;
while ( true ) {
if ( cursor != null )
fetchOptions.startCursor( cursor );
final QueryResultList< Entity > resultList = ds.prepare( query ).asQueryResultList( fetchOptions );
for ( final Entity e : resultList ) {
if ( entityProcessor != null )
entityProcessor.processEntity( e );
if ( makePropertiesUnindexed != null )
for ( final String propertyName : makePropertiesUnindexed )
e.setUnindexedProperty( propertyName, e.getProperty( propertyName ) );
if ( newVersionToSet != null )
e.setProperty( "v", newVersionToSet );
if ( autoSave )
ds.put( e );
processedCount++;
}
if ( resultList.size() < batchSize || processedCount >= maxUpdates )
return getProcessedCountString();
cursor = resultList.getCursor();
}
}
示例8: doGet
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的package包/類
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
FetchOptions fetchOptions = FetchOptions.Builder.withLimit(PAGE_SIZE);
// If this servlet is passed a cursor parameter, let's use it.
String startCursor = req.getParameter("cursor");
if (startCursor != null) {
fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor));
}
Query q = new Query("Person").addSort("name", SortDirection.ASCENDING);
PreparedQuery pq = datastore.prepare(q);
QueryResultList<Entity> results;
try {
results = pq.asQueryResultList(fetchOptions);
} catch (IllegalArgumentException e) {
// IllegalArgumentException happens when an invalid cursor is used.
// A user could have manually entered a bad cursor in the URL or there
// may have been an internal implementation detail change in App Engine.
// Redirect to the page without the cursor parameter to show something
// rather than an error.
resp.sendRedirect("/people");
return;
}
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
PrintWriter w = resp.getWriter();
w.println("<!DOCTYPE html>");
w.println("<meta charset=\"utf-8\">");
w.println("<title>Cloud Datastore Cursor Sample</title>");
w.println("<ul>");
for (Entity entity : results) {
w.println("<li>" + entity.getProperty("name") + "</li>");
}
w.println("</ul>");
String cursorString = results.getCursor().toWebSafeString();
// This servlet lives at '/people'.
w.println("<a href='/people?cursor=" + cursorString + "'>Next page</a>");
}
示例9: findAll
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的package包/類
/**
* 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.
* @throws UnauthorizedException
*/
@ApiMethod(name = "findAll", scopes = { Config.EMAIL_SCOPE }, clientIds = { Config.CHROME_CLIENT_ID, Config.WEB_CLIENT_ID,
Config.API_EXPLORER_CLIENT_ID })
public CollectionResponse<ServiceResponse> findAll(@Named("_name") String _name, @Nullable @Named("cursor") String cursorString,
@Nullable @Named("limit") Integer limit, User user) throws UnauthorizedException {
if (user == null) {
throw new UnauthorizedException(
"UnauthorizedException # User is Null.");
}
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
if (limit == null) {
limit = 10;
}
FetchOptions fetchOptions = FetchOptions.Builder.withLimit(limit);
if (cursorString != null) {
fetchOptions.startCursor(Cursor.fromWebSafeString(cursorString));
}
Query q = new Query(_name);
q.addSort("_updatedAt", SortDirection.DESCENDING);
PreparedQuery pq = datastore.prepare(q);
QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
List<ServiceResponse> responses = new ArrayList<ServiceResponse>();
ServiceResponse res = null;
for (Entity entity : results) {
res = new ServiceResponse();
//TODO add properties from entity to service response
res.set_id(entity.getKey().getId());
res.set_createdAt((Date) entity.getProperty(_createdAt));
res.set_createdBy((String) entity.getProperty(_createdBy));
res.set_upatedAt((Date) entity.getProperty(_updatedAt));
res.set_updatedBy((String) entity.getProperty(_updatedBy));
res.set_status((String) entity.getProperty(_status));
Text dataText = (Text)entity.getProperty(data);
res.setData(dataText.getValue());
responses.add(res);
}
cursorString = results.getCursor().toWebSafeString();
return CollectionResponse.<ServiceResponse> builder().setItems(responses).setNextPageToken(cursorString).build();
}
示例10: list
import com.google.appengine.api.datastore.FetchOptions; //導入方法依賴的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);
}