Java Code Examples for com.google.appengine.api.datastore.DatastoreService#prepare()

The following examples show how to use com.google.appengine.api.datastore.DatastoreService#prepare() . 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: DatastoreSessionStore.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, SessionData> getAllSessions() {
  final String originalNamespace = NamespaceManager.get();
  NamespaceManager.set("");
  try {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery pq = ds.prepare(new Query(SESSION_ENTITY_TYPE));
    Map<String, SessionData> sessions = new HashMap<>();
    for (Entity entity : pq.asIterable()) {
      sessions.put(entity.getKey().getName(), createSessionFromEntity(entity));
    }
    return sessions;
  } finally {
    NamespaceManager.set(originalNamespace);
  }
}
 
Example 2
Source File: TestReport.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the {@code TestReport} with the given build type id ordered by build id in the descendant order.
 *
 * @param buildTypeId      the build type id.
 * @param limit            the optional fetch limit, by default {@link com.google.appengine.tck.site.endpoints.TestReport#DEFAULT_FETCH_LIMIT}.
 * @param reports          the reports entry point
 * @return the matching test reports list or an empty one if none.
 */
@SuppressWarnings("unchecked")
public static List<TestReport> findByBuildTypeIdOrderByBuildIdDesc(String buildTypeId, Optional<Integer> limit, Reports reports) {
    final MemcacheService memcacheService = reports.getMemcacheService();
    List<TestReport> results = (List<TestReport>) memcacheService.get(buildTypeId);
    if (results == null) {
        final Filter buildTypeFilter = new Query.FilterPredicate("buildTypeId", FilterOperator.EQUAL, buildTypeId);
        final Query query = new Query(TEST_REPORT).setFilter(buildTypeFilter).addSort("buildId", DESCENDING);

        final DatastoreService datastoreService = reports.getDatastoreService();
        final PreparedQuery preparedQuery = datastoreService.prepare(query);
        final List<Entity> entities = preparedQuery.asList(FetchOptions.Builder.withLimit(limit.or(DEFAULT_FETCH_LIMIT)));

        results = new ArrayList<>();
        for (Entity oneEntity : entities) {
            final TestReport report = from(oneEntity);
            results.add(report);
        }

        memcacheService.put(buildTypeId, results);
    }
    return results;
}
 
Example 3
Source File: PersistingTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void putStoresEntity() throws Exception {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Entity client = new Entity("Client");
    client.setProperty("username", "alesj");
    client.setProperty("password", "password");
    final Key key = ds.put(client);
    try {
        Query query = new Query("Client");
        query.setFilter(new Query.FilterPredicate("username", Query.FilterOperator.EQUAL, "alesj"));
        PreparedQuery pq = ds.prepare(query);
        Entity result = pq.asSingleEntity();
        Assert.assertNotNull(result);
        Assert.assertEquals(key, result.getKey());
        Assert.assertEquals("alesj", result.getProperty("username"));
        Assert.assertEquals("password", result.getProperty("password"));
    } finally {
        ds.delete(key);
    }
}
 
Example 4
Source File: TestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private static <T extends TempData> List<T> getAllTempData(Class<T> type, boolean unreadOnly) {
    try {
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        String kind = getKind(type);
        Query query = new Query(kind);
        if (unreadOnly) {
            query.setFilter(new Query.FilterPredicate(TEMP_DATA_READ_PROPERTY, Query.FilterOperator.EQUAL, false));
        } else {
            query.addSort("timestamp", Query.SortDirection.ASCENDING);
        }
        PreparedQuery pq = ds.prepare(query);
        Iterator<Entity> iter = pq.asIterator();
        List<T> result = new ArrayList<>();
        while (iter.hasNext()) {
            Entity entity = iter.next();
            T data = readTempData(type, entity, ds);
            result.add(data);
        }
        return result;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 5
Source File: TestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
public static <T extends TempData> T getLastTempData(Class<T> type) {
    try {
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        String kind = getKind(type);
        PreparedQuery pq = ds.prepare(new Query(kind).addSort("timestamp", Query.SortDirection.DESCENDING));
        Iterator<Entity> iter = pq.asIterator();
        if (iter.hasNext()) {
            Entity entity = iter.next();
            return readTempData(type, entity, ds);
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 6
Source File: GuestbookTestUtilities.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void cleanDatastore(DatastoreService ds, String book) {
  Query query =
      new Query("Greeting")
          .setAncestor(new KeyFactory.Builder("Guestbook", book).getKey())
          .setKeysOnly();
  PreparedQuery pq = ds.prepare(query);
  List<Entity> entities = pq.asList(FetchOptions.Builder.withDefaults());
  ArrayList<Key> keys = new ArrayList<>(entities.size());

  for (Entity e : entities) {
    keys.add(e.getKey());
  }
  ds.delete(keys);
}
 
Example 7
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 8
Source File: FetchMessagesServlet.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public final void doGet(final HttpServletRequest req,
                        final HttpServletResponse resp)
        throws IOException {
    // First retrieve messages from the memcache
    MemcacheService memcacheService = MemcacheServiceFactory
            .getMemcacheService();
    List<String> messages =
            (List<String>) memcacheService.get(Constants.MESSAGE_CACHE_KEY);
    if (messages == null) {
        // If no messages in the memcache, look for the datastore
        DatastoreService datastore =
                DatastoreServiceFactory.getDatastoreService();
        PreparedQuery query = datastore.prepare(
                new Query("PubsubMessage").addSort("receipt-time",
                        Query.SortDirection.DESCENDING));
        messages = new ArrayList<>();
        for (Entity entity : query.asIterable(
                FetchOptions.Builder.withLimit(MAX_COUNT))) {
            String message = (String) entity.getProperty("message");
            messages.add(message);
        }
        // Store them to the memcache for future use.
        memcacheService.put(Constants.MESSAGE_CACHE_KEY, messages);
    }
    ObjectMapper mapper = new ObjectMapper();
    resp.setContentType("application/json; charset=UTF-8");
    mapper.writeValue(resp.getWriter(), messages);
    resp.getWriter().close();
}
 
Example 9
Source File: NotificationCleanupServlet.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
private void doCleanup() {
  log.log(Level.INFO, "Starting a job to clean up processed notification records");

  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  Calendar cutoffTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  cutoffTime.add(Calendar.HOUR, -HOURS_TO_KEEP_RECORDS_OF_PROCESSED_NOTIFICATIONS);

  Query query = new Query(Worker.PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND)
    .setFilter(new FilterPredicate("processedAt", FilterOperator.LESS_THAN, cutoffTime.getTime()))
    .setKeysOnly();

  PreparedQuery preparedQuery = datastore.prepare(query);

  // Delete in batches
  List<Entity> entitiesToBeDeleted = null;
  do {
    entitiesToBeDeleted = preparedQuery.asList(FetchOptions.Builder.withLimit(5));

    List<Key> keys = new ArrayList<Key>();

    for (Entity entity : entitiesToBeDeleted) {
      keys.add(entity.getKey());
    }

    datastore.delete(keys);
  } while (entitiesToBeDeleted.size() > 0);

  log.log(Level.INFO, "Finished a job to clean up processed notification records");
}
 
Example 10
Source File: AppEngineCredentialStore.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Migrates to the new format using {@link DataStore} of {@link StoredCredential}.
 *
 * @param credentialDataStore credential data store
 * @since 1.16
 */
public final void migrateTo(DataStore<StoredCredential> credentialDataStore) throws IOException {
  DatastoreService service = DatastoreServiceFactory.getDatastoreService();
  PreparedQuery queryResult = service.prepare(new Query(KIND));
  for (Entity entity : queryResult.asIterable()) {
    StoredCredential storedCredential = new StoredCredential().setAccessToken(
        (String) entity.getProperty("accessToken"))
        .setRefreshToken((String) entity.getProperty("refreshToken"))
        .setExpirationTimeMilliseconds((Long) entity.getProperty("expirationTimeMillis"));
    credentialDataStore.set(entity.getKey().getName(), storedCredential);
  }
}
 
Example 11
Source File: NotificationCleanupServlet.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
private void doCleanup() {
  log.log(Level.INFO, "Starting a job to clean up processed notification records");

  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  Calendar cutoffTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  cutoffTime.add(Calendar.HOUR, -HOURS_TO_KEEP_RECORDS_OF_PROCESSED_NOTIFICATIONS);

  Query query = new Query(Worker.PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND)
    .setFilter(new FilterPredicate("processedAt", FilterOperator.LESS_THAN, cutoffTime.getTime()))
    .setKeysOnly();

  PreparedQuery preparedQuery = datastore.prepare(query);

  // Delete in batches
  List<Entity> entitiesToBeDeleted = null;
  do {
    entitiesToBeDeleted = preparedQuery.asList(FetchOptions.Builder.withLimit(5));

    List<Key> keys = new ArrayList<Key>();

    for (Entity entity : entitiesToBeDeleted) {
      keys.add(entity.getKey());
    }

    datastore.delete(keys);
  } while (entitiesToBeDeleted.size() > 0);

  log.log(Level.INFO, "Finished a job to clean up processed notification records");
}
 
Example 12
Source File: NotificationCleanupServlet.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 5 votes vote down vote up
private void doCleanup() {
  log.log(Level.INFO, "Starting a job to clean up processed notification records");
  
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  Calendar cutoffTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  cutoffTime.add(Calendar.HOUR, -HOURS_TO_KEEP_RECORDS_OF_PROCESSED_NOTIFICATIONS);
  
  Query query = new Query(PushNotificationWorker.PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND)
    .setFilter(new FilterPredicate("processedAt", FilterOperator.LESS_THAN, cutoffTime.getTime()))
    .setKeysOnly();
  
  PreparedQuery preparedQuery = datastore.prepare(query);

  // Delete in batches
  List<Entity> entitiesToBeDeleted = null;
  do {
    entitiesToBeDeleted = preparedQuery.asList(FetchOptions.Builder.withLimit(5));
    
    List<Key> keys = new ArrayList<Key>();
    
    for (Entity entity : entitiesToBeDeleted) {
      keys.add(entity.getKey());
    }
  
    datastore.delete(keys);
  } while (entitiesToBeDeleted.size() > 0);

  log.log(Level.INFO, "Finished a job to clean up processed notification records");
}