Java 类com.google.appengine.api.datastore.Query 实例源码
项目:spring-data-snowdrop
文件:FilterCriteriaConverter.java
private Query.FilterOperator convert(Condition condition) {
OperationKey key = condition.getKey();
switch (key) {
case EQUALS:
return condition.isNegating() ? Query.FilterOperator.NOT_EQUAL : Query.FilterOperator.EQUAL;
case IN:
return Query.FilterOperator.IN;
case GREATER:
return Query.FilterOperator.GREATER_THAN;
case GREATER_EQUAL:
return Query.FilterOperator.GREATER_THAN_OR_EQUAL;
case LESS:
return Query.FilterOperator.LESS_THAN;
case LESS_EQUAL:
return Query.FilterOperator.LESS_THAN_OR_EQUAL;
default:
throw new IllegalArgumentException("Unsupported operator " + condition.getKey());
}
}
项目: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);
}
}
项目: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.
}
项目: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
文件:DatastoreSessionFilter.java
protected void deleteSessionWithValue(String varName, String varValue) {
Transaction transaction = datastore.beginTransaction();
try {
Query query = new Query(SESSION_KIND)
.setFilter(new FilterPredicate(varName, FilterOperator.EQUAL, varValue));
Iterator<Entity> results = datastore.prepare(transaction, query).asIterator();
while (results.hasNext()) {
Entity stateEntity = results.next();
datastore.delete(transaction, stateEntity.getKey());
}
transaction.commit();
} finally {
if (transaction.isActive()) {
transaction.rollback();
}
}
}
项目: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);
}
}
项目:java-docs-samples
文件:QueriesTest.java
@Test
public void propertyFilterExample_returnsMatchingEntities() throws Exception {
// Arrange
Entity p1 = new Entity("Person");
p1.setProperty("height", 120);
Entity p2 = new Entity("Person");
p2.setProperty("height", 180);
Entity p3 = new Entity("Person");
p3.setProperty("height", 160);
datastore.put(ImmutableList.<Entity>of(p1, p2, p3));
// Act
long minHeight = 160;
// [START property_filter_example]
Filter propertyFilter =
new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);
Query q = new Query("Person").setFilter(propertyFilter);
// [END property_filter_example]
// Assert
List<Entity> results =
datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
assertThat(results).named("query results").containsExactly(p2, p3);
}
项目:gae-webmonitor
文件:DataStoreService.java
/**
* Remove an object from the datastore
*
* @param uri The URI
*/
public void removeObject(String uri) {
if (!isObjectRegistered(uri)) {
return;
}
// Remove all WebObjectInstance entries associated
Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
Query instanceQuery = new Query(OBJECT_INSTANCE)
.setFilter(uriFilter)
.addSort("timestamp", SortDirection.DESCENDING);
List<Entity> instances = datastoreService
.prepare(instanceQuery)
.asList(FetchOptions.Builder.withDefaults());
List<Key> keys = new ArrayList<Key>();
for (Entity e : instances) {
keys.add(e.getKey());
}
datastoreService.delete(keys);
// Remove actual WebObject entry
Query objectQuery = new Query(OBJECT).setFilter(uriFilter);
Entity object = datastoreService.prepare(objectQuery).asSingleEntity();
datastoreService.delete(object.getKey());
}
项目:gae-webmonitor
文件:DataStoreService.java
/**
* Update the timestamp of an object instance
*
* @param uri The URI of the Web object instance
* @param oldTimestamp The old timestamp
* @param newTimestamp The new timestamp
*/
public void updateObjectInstanceTimestamp(String uri, Date oldTimestamp,
Date newTimestamp) {
Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
Filter timestampFilter = new FilterPredicate("timestamp", FilterOperator.EQUAL, oldTimestamp);
Query query = new Query(OBJECT_INSTANCE)
.setFilter(uriFilter)
.setFilter(timestampFilter);
Entity instance = datastoreService.prepare(query).asSingleEntity();
if (instance == null) {
throw new IllegalArgumentException(
"No record with matching URI and timestamp was found");
}
instance.setProperty("timestamp", newTimestamp);
datastoreService.put(instance);
}
项目:gae-webmonitor
文件:DataStoreService.java
/**
* Get all instances of an object present in the data store
*
* @param uri The URI of the Web object
* @return The list of Web instances
*/
public List<WebObjectInstance> getAllObjectInstances(String uri) {
Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
Query query = new Query(OBJECT_INSTANCE)
.setFilter(uriFilter)
.addSort("timestamp", SortDirection.DESCENDING);
List<Entity> instances = datastoreService.prepare(query)
.asList(FetchOptions.Builder.withDefaults());
List<WebObjectInstance> instanceList = new ArrayList<WebObjectInstance>();
for (Entity e : instances) {
String content = ((Text) e.getProperty("content")).getValue();
String contentType = (String) e.getProperty("contentType");
int statusCode = ((Integer) e.getProperty("statusCode")).intValue();
Date timestamp = (Date) e.getProperty("timestamp");
instanceList.add(new WebObjectInstance(uri, content, contentType,
timestamp, statusCode));
}
return instanceList;
}
项目:gae-webmonitor
文件:DataStoreService.java
/**
* Get the most recent instance of a web object available
*
* @param uri The URI of the Web object
* @return The instance of the Web object
*/
public WebObjectInstance getMostRecentObjectInstance(String uri) {
Filter uriFilter = new FilterPredicate("uri", FilterOperator.EQUAL, uri);
Query query = new Query(OBJECT_INSTANCE)
.setFilter(uriFilter)
.addSort("timestamp", SortDirection.DESCENDING);
List<Entity> instances = datastoreService.prepare(query).asList(
FetchOptions.Builder.withDefaults());
if (instances == null || instances.isEmpty()) {
return null;
}
Entity mostRecentInstance = instances.get(0);
String content = ((Text) mostRecentInstance.getProperty("content"))
.getValue();
String contentType = (String) mostRecentInstance
.getProperty("contentType");
Date timestamp = (Date) mostRecentInstance.getProperty("timestamp");
int statusCode = ((Long) mostRecentInstance.getProperty("statusCode"))
.intValue();
return new WebObjectInstance(uri, content, contentType, timestamp,
statusCode);
}
项目:java-docs-samples
文件:QueriesTest.java
@Test
public void queryRestrictions_compositeFilter_isInvalid() throws Exception {
long minBirthYear = 1940;
long maxHeight = 200;
// [START inequality_filters_one_property_invalid_example]
Filter birthYearMinFilter =
new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);
Filter heightMaxFilter =
new FilterPredicate("height", FilterOperator.LESS_THAN_OR_EQUAL, maxHeight);
Filter invalidFilter = CompositeFilterOperator.and(birthYearMinFilter, heightMaxFilter);
Query q = new Query("Person").setFilter(invalidFilter);
// [END inequality_filters_one_property_invalid_example]
// Note: The local devserver behavior is different than the production
// version of Cloud Datastore, so there aren't any assertions we can make
// in this test. The query appears to work with the local test runner,
// but will fail in production.
}
项目:java-docs-samples
文件:ReadPolicyTest.java
@Test
public void readPolicy_strong_returnsAllResults() {
double deadline = 5.0;
ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.STRONG);
DatastoreServiceConfig datastoreConfig =
DatastoreServiceConfig.Builder.withReadPolicy(policy).deadline(deadline);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(datastoreConfig);
Entity parent = new Entity("Person", "a");
Entity child = new Entity("Person", "b", parent.getKey());
datastore.put(ImmutableList.<Entity>of(parent, child));
Query q = new Query("Person").setAncestor(parent.getKey());
List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
assertThat(results).named("query results").hasSize(2);
}
项目:sc2gears
文件:CachingService.java
/**
* Returns the Account key associated with the specified authorization key.
* @param pm reference to the persistence manager
* @param authorizationKey authorization key to return the account key for
* @return the Account key associated with the specified authorization key; or <code>null</code> if the authorization key is invalid
*/
public static Key getAccountKeyByAuthKey( final PersistenceManager pm, final String authorizationKey ) {
final String memcacheKey = CACHE_KEY_AUTH_KEY_ACCOUNT_KEY_PREFIX + authorizationKey;
final String accountKeyString = (String) memcacheService.get( memcacheKey );
if ( accountKeyString != null )
return KeyFactory.stringToKey( accountKeyString );
final Query q = new Query( Account.class.getSimpleName() );
q.setFilter( new FilterPredicate( "authorizationKey", FilterOperator.EQUAL, authorizationKey ) );
q.setKeysOnly();
final List< Entity > entityList = DatastoreServiceFactory.getDatastoreService().prepare( q ).asList( FetchOptions.Builder.withDefaults() );
if ( entityList.isEmpty() )
return null;
final Key accountKey = entityList.get( 0 ).getKey();
try {
memcacheService.put( memcacheKey, KeyFactory.keyToString( accountKey ) );
}
catch ( final MemcacheServiceException mse ) {
LOGGER.log( Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse );
// Ignore memcache errors, do not prevent serving user request
}
return accountKey;
}
项目:java-docs-samples
文件:IndexesServlet.java
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
// [START exploding_index_example_1]
Query q =
new Query("Widget")
.setFilter(
CompositeFilterOperator.and(
new FilterPredicate("x", FilterOperator.EQUAL, 1),
new FilterPredicate("y", FilterOperator.EQUAL, 2)))
.addSort("date", Query.SortDirection.ASCENDING);
// [END exploding_index_example_1]
List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
PrintWriter out = resp.getWriter();
out.printf("Got %d widgets.\n", results.size());
}
项目:java-docs-samples
文件:QueriesTest.java
@Test
public void queryRestrictions_surprisingMultipleValuesAllMustMatch_returnsNoEntities()
throws Exception {
Entity a = new Entity("Widget", "a");
List<Long> xs = Arrays.asList(1L, 2L);
a.setProperty("x", xs);
datastore.put(a);
// [START surprising_behavior_example_1]
Query q =
new Query("Widget")
.setFilter(
CompositeFilterOperator.and(
new FilterPredicate("x", FilterOperator.GREATER_THAN, 1),
new FilterPredicate("x", FilterOperator.LESS_THAN, 2)));
// [END surprising_behavior_example_1]
// Entity "a" will not match because no individual value matches all filters.
// See the documentation for more details:
// https://cloud.google.com/appengine/docs/java/datastore/query-restrictions
// #properties_with_multiple_values_can_behave_in_surprising_ways
List<Entity> results =
datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
assertThat(results).named("query results").isEmpty();
}
项目:java-docs-samples
文件:ReadPolicyTest.java
@Test
public void readPolicy_strong_returnsAllResults() {
double deadline = 5.0;
ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.STRONG);
DatastoreServiceConfig datastoreConfig =
DatastoreServiceConfig.Builder.withReadPolicy(policy).deadline(deadline);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(datastoreConfig);
Entity parent = new Entity("Person", "a");
Entity child = new Entity("Person", "b", parent.getKey());
datastore.put(ImmutableList.<Entity>of(parent, child));
Query q = new Query("Person").setAncestor(parent.getKey());
List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
assertThat(results).named("query results").hasSize(2);
}
项目:java-docs-samples
文件:ProjectionTest.java
@Test
public void projectionQuery_grouping_filtersDuplicates() {
putTestData("some duplicate", 0L);
putTestData("some duplicate", 0L);
putTestData("too big", 1L);
// [START grouping]
Query q = new Query("TestKind");
q.addProjection(new PropertyProjection("A", String.class));
q.addProjection(new PropertyProjection("B", Long.class));
q.setDistinct(true);
q.setFilter(Query.FilterOperator.LESS_THAN.of("B", 1L));
q.addSort("B", Query.SortDirection.DESCENDING);
q.addSort("A");
// [END grouping]
List<Entity> entities =
datastore.prepare(q).asList(FetchOptions.Builder.withLimit(5));
assertThat(entities).hasSize(1);
Entity entity = entities.get(0);
assertThat((String) entity.getProperty("A")).named("entity.A").isEqualTo("some duplicate");
assertThat((long) entity.getProperty("B")).named("entity.B").isEqualTo(0L);
}
项目: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 propertyFilterExample_returnsMatchingEntities() throws Exception {
// Arrange
Entity p1 = new Entity("Person");
p1.setProperty("height", 120);
Entity p2 = new Entity("Person");
p2.setProperty("height", 180);
Entity p3 = new Entity("Person");
p3.setProperty("height", 160);
datastore.put(ImmutableList.<Entity>of(p1, p2, p3));
// Act
long minHeight = 160;
// [START property_filter_example]
Filter propertyFilter =
new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);
Query q = new Query("Person").setFilter(propertyFilter);
// [END property_filter_example]
// Assert
List<Entity> results =
datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
assertThat(results).named("query results").containsExactly(p2, p3);
}
项目:java-docs-samples
文件:QueriesTest.java
@Test
public void ancestorFilterExample_returnsMatchingEntities() throws Exception {
Entity a = new Entity("Person", "a");
Entity b = new Entity("Person", "b");
Entity aa = new Entity("Person", "aa", a.getKey());
Entity ab = new Entity("Person", "ab", a.getKey());
Entity bb = new Entity("Person", "bb", b.getKey());
datastore.put(ImmutableList.<Entity>of(a, b, aa, ab, bb));
Key ancestorKey = a.getKey();
// [START ancestor_filter_example]
Query q = new Query("Person").setAncestor(ancestorKey);
// [END ancestor_filter_example]
// Assert
List<Entity> results =
datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
assertThat(results).named("query results").containsExactly(a, aa, ab);
}
项目:java-docs-samples
文件:QueriesTest.java
@Test
public void keysOnlyExample_returnsMatchingEntities() throws Exception {
// Arrange
Entity a = new Entity("Person", "a");
Entity b = new Entity("Building", "b");
Entity c = new Entity("Person", "c");
datastore.put(ImmutableList.<Entity>of(a, b, c));
// [START keys_only_example]
Query q = new Query("Person").setKeysOnly();
// [END keys_only_example]
// Assert
List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
assertThat(results).named("query results").containsExactly(a, c);
}
项目:java-docs-samples
文件:QueriesTest.java
@Test
public void queryInterface_singleFilter_returnsMatchedEntities() throws Exception {
// Arrange
Entity a = new Entity("Person", "a");
a.setProperty("height", 100);
Entity b = new Entity("Person", "b");
b.setProperty("height", 150);
Entity c = new Entity("Person", "c");
c.setProperty("height", 300);
datastore.put(ImmutableList.<Entity>of(a, b, c));
// Act
long minHeight = 150;
// [START interface_2]
Filter heightMinFilter =
new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);
Query q = new Query("Person").setFilter(heightMinFilter);
// [END interface_2]
// Assert
List<Entity> results =
datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
assertThat(results).named("query results").containsExactly(b, c);
}
项目:java-docs-samples
文件:QueriesTest.java
@Test
public void queryRestrictions_compositeFilter_isInvalid() throws Exception {
long minBirthYear = 1940;
long maxHeight = 200;
// [START inequality_filters_one_property_invalid_example]
Filter birthYearMinFilter =
new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);
Filter heightMaxFilter =
new FilterPredicate("height", FilterOperator.LESS_THAN_OR_EQUAL, maxHeight);
Filter invalidFilter = CompositeFilterOperator.and(birthYearMinFilter, heightMaxFilter);
Query q = new Query("Person").setFilter(invalidFilter);
// [END inequality_filters_one_property_invalid_example]
// Note: The local devserver behavior is different than the production
// version of Cloud Datastore, so there aren't any assertions we can make
// in this test. The query appears to work with the local test runner,
// but will fail in production.
}
项目:java-docs-samples
文件:MetadataPropertiesTest.java
Collection<String> representationsOfProperty(DatastoreService ds, String kind, String property) {
// Start with unrestricted non-keys-only property query
Query q = new Query(Entities.PROPERTY_METADATA_KIND);
// Limit to specified kind and property
q.setFilter(
new FilterPredicate(
"__key__", Query.FilterOperator.EQUAL, Entities.createPropertyKey(kind, property)));
// Get query result
Entity propInfo = ds.prepare(q).asSingleEntity();
// Return collection of property representations
return (Collection<String>) propInfo.getProperty("property_representation");
}
项目:java-docs-samples
文件:QueriesTest.java
@Test
public void queryRestrictions_sortWrongOrderOnInequality_isInvalid() throws Exception {
long minBirthYear = 1940;
// [START inequality_filters_sort_orders_invalid_example_2]
Filter birthYearMinFilter =
new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);
// Not valid. Sort on birthYear needs to be first.
Query q =
new Query("Person")
.setFilter(birthYearMinFilter)
.addSort("lastName", SortDirection.ASCENDING)
.addSort("birthYear", SortDirection.ASCENDING);
// [END inequality_filters_sort_orders_invalid_example_2]
// Note: The local devserver behavior is different than the production
// version of Cloud Datastore, so there aren't any assertions we can make
// in this test. The query appears to work with the local test runner,
// but will fail in production.
}
项目:java-docs-samples
文件:QueriesTest.java
@Test
public void ancestorFilterExample_returnsMatchingEntities() throws Exception {
Entity a = new Entity("Person", "a");
Entity b = new Entity("Person", "b");
Entity aa = new Entity("Person", "aa", a.getKey());
Entity ab = new Entity("Person", "ab", a.getKey());
Entity bb = new Entity("Person", "bb", b.getKey());
datastore.put(ImmutableList.<Entity>of(a, b, aa, ab, bb));
Key ancestorKey = a.getKey();
// [START ancestor_filter_example]
Query q = new Query("Person").setAncestor(ancestorKey);
// [END ancestor_filter_example]
// Assert
List<Entity> results =
datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
assertThat(results).named("query results").containsExactly(a, aa, ab);
}
项目:java-docs-samples
文件:IndexesServlet.java
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
// [START exploding_index_example_1]
Query q =
new Query("Widget")
.setFilter(
CompositeFilterOperator.and(
new FilterPredicate("x", FilterOperator.EQUAL, 1),
new FilterPredicate("y", FilterOperator.EQUAL, 2)))
.addSort("date", Query.SortDirection.ASCENDING);
// [END exploding_index_example_1]
List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
PrintWriter out = resp.getWriter();
out.printf("Got %d widgets.\n", results.size());
}