com.google.appengine.api.datastore.DatastoreService

Here are the examples of the java api class com.google.appengine.api.datastore.DatastoreService taken from open source projects.

1. GaeDatastoreUserRegistry#registerUser()

View license
public void registerUser(GaeUser newUser) {
    logger.debug("Attempting to create new user " + newUser);
    Key key = KeyFactory.createKey(USER_TYPE, newUser.getUserId());
    Entity user = new Entity(key);
    user.setProperty(USER_EMAIL, newUser.getEmail());
    user.setProperty(USER_NICKNAME, newUser.getNickname());
    user.setProperty(USER_FORENAME, newUser.getForename());
    user.setProperty(USER_SURNAME, newUser.getSurname());
    user.setUnindexedProperty(USER_ENABLED, newUser.isEnabled());
    Collection<AppRole> roles = newUser.getAuthorities();
    long binaryAuthorities = 0;
    for (AppRole r : roles) {
        binaryAuthorities |= 1 << r.getBit();
    }
    user.setUnindexedProperty(USER_AUTHORITIES, binaryAuthorities);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(user);
}

2. ValueTranslationTests#stringToNumber()

View license
/**
	 * Strings can be converted to numbers
	 */
@Test
public void stringToNumber() throws Exception {
    fact().register(HasNumber.class);
    DatastoreService ds = ds();
    Entity ent = new Entity(Key.getKind(HasNumber.class));
    // setting a string
    ent.setProperty("number", "2");
    ds.put(null, ent);
    Key<HasNumber> key = Key.create(ent.getKey());
    HasNumber fetched = ofy().load().key(key).now();
    // should be a number
    assert fetched.number == 2;
}

3. DatastoreEntityTests#testEmptyCollectionInEntity()

Project: objectify
Source File: DatastoreEntityTests.java
View license
/**
	 * What happens when you put empty collections in an Entity?
	 */
@Test
public void testEmptyCollectionInEntity() throws Exception {
    Entity ent = new Entity("Test");
    List<Object> empty = new ArrayList<>();
    ent.setProperty("empty", empty);
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    ds.put(ent);
    Entity fetched = ds.get(ent.getKey());
    System.out.println(fetched);
    Object whatIsIt = fetched.getProperty("empty");
    assert whatIsIt == null;
}

4. DatastoreEntityTests#testCollectionContainingNullInEntity()

Project: objectify
Source File: DatastoreEntityTests.java
View license
/**
	 * What happens when you put a single null in a collection in an Entity?
	 */
@SuppressWarnings("unchecked")
@Test
public void testCollectionContainingNullInEntity() throws Exception {
    Entity ent = new Entity("Test");
    List<Object> hasNull = new ArrayList<>();
    hasNull.add(null);
    ent.setProperty("hasNull", hasNull);
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    ds.put(ent);
    Entity fetched = ds.get(ent.getKey());
    System.out.println(fetched);
    Collection<Object> whatIsIt = (Collection<Object>) fetched.getProperty("hasNull");
    assert whatIsIt != null;
    assert whatIsIt.size() == 1;
    assert whatIsIt.iterator().next() == null;
}

5. MyEndpoint#getTasks()

View license
@ApiMethod(name = "getTasks")
public List<TaskBean> getTasks() {
    DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
    Key taskBeanParentKey = KeyFactory.createKey("TaskBeanParent", "todo.txt");
    Query query = new Query(taskBeanParentKey);
    List<Entity> results = datastoreService.prepare(query).asList(FetchOptions.Builder.withDefaults());
    ArrayList<TaskBean> taskBeans = new ArrayList<TaskBean>();
    for (Entity result : results) {
        TaskBean taskBean = new TaskBean();
        taskBean.setId(result.getKey().getId());
        taskBean.setData((String) result.getProperty("data"));
        taskBeans.add(taskBean);
    }
    return taskBeans;
}

6. MyEndpoint#clearTasks()

View license
@ApiMethod(name = "clearTasks")
public void clearTasks() {
    DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
    Transaction txn = datastoreService.beginTransaction();
    try {
        Key taskBeanParentKey = KeyFactory.createKey("TaskBeanParent", "todo.txt");
        Query query = new Query(taskBeanParentKey);
        List<Entity> results = datastoreService.prepare(query).asList(FetchOptions.Builder.withDefaults());
        for (Entity result : results) {
            datastoreService.delete(result.getKey());
        }
        txn.commit();
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}

7. MyEndpoint#storeTask()

View license
@ApiMethod(name = "storeTask")
public void storeTask(TaskBean taskBean) {
    DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
    Transaction txn = datastoreService.beginTransaction();
    try {
        Key taskBeanParentKey = KeyFactory.createKey("TaskBeanParent", "todo.txt");
        Entity taskEntity = new Entity("TaskBean", taskBean.getId(), taskBeanParentKey);
        taskEntity.setProperty("data", taskBean.getData());
        datastoreService.put(taskEntity);
        txn.commit();
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}

8. AppEngineCredentialStore#load()

View license
@Override
public boolean load(String userId, Credential credential) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key key = KeyFactory.createKey(KIND, userId);
    try {
        Entity entity = datastore.get(key);
        credential.setAccessToken((String) entity.getProperty("accessToken"));
        credential.setRefreshToken((String) entity.getProperty("refreshToken"));
        credential.setExpirationTimeMilliseconds((Long) entity.getProperty("expirationTimeMillis"));
        return true;
    } catch (EntityNotFoundException exception) {
        return false;
    }
}

9. ApiKeyInitializer#contextInitialized()

Project: iosched
Source File: ApiKeyInitializer.java
View license
@Override
public void contextInitialized(ServletContextEvent event) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
    Entity entity;
    try {
        entity = datastore.get(key);
    } catch (EntityNotFoundException e) {
        entity = new Entity(key);
        entity.setProperty(ACCESS_KEY_FIELD, API_KEY);
        datastore.put(entity);
        mLogger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!");
    }
    String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
    event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey);
}

10. ApiKeyInitializer#getKey()

Project: iosched
Source File: ApiKeyInitializer.java
View license
/**
     * Gets the access key.
     */
protected String getKey() {
    com.google.appengine.api.datastore.DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
    String apiKey = "";
    try {
        Entity entity = datastore.get(key);
        apiKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
    } catch (EntityNotFoundException e) {
        mLogger.severe("Exception will retrieving the API Key" + e.toString());
    }
    return apiKey;
}

11. EvilMemcacheBugTests#testEntityKeys()

Project: objectify
Source File: EvilMemcacheBugTests.java
View license
/** */
@Test
public void testEntityKeys() throws Exception {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    com.google.appengine.api.datastore.Key parentKeyA = KeyFactory.createKey("SimpleParent", "same");
    com.google.appengine.api.datastore.Key childKeyA = KeyFactory.createKey(parentKeyA, "SimpleEntity", "different");
    Entity entA1 = new Entity(childKeyA);
    ds.put(entA1);
    Entity entA2 = ds.get(childKeyA);
    assert new String(MemcacheSerialization.makePbKey(entA1.getKey())).equals(new String(MemcacheSerialization.makePbKey(childKeyA)));
    assert new String(MemcacheSerialization.makePbKey(entA2.getKey())).equals(new String(MemcacheSerialization.makePbKey(childKeyA)));
    com.google.appengine.api.datastore.Key parentKeyB = KeyFactory.createKey("SimpleParent", "same");
    com.google.appengine.api.datastore.Key childKeyB = KeyFactory.createKey(parentKeyB, "SimpleEntity", "same");
    Entity entB1 = new Entity(childKeyB);
    ds.put(entB1);
    Entity entB2 = ds.get(childKeyB);
    // This works
    assert new String(MemcacheSerialization.makePbKey(entB1.getKey())).equals(new String(MemcacheSerialization.makePbKey(childKeyB)));
    // Update: This succeeds!  As of SDK 1.6.0 this has been fixed.  The Objectify workaround (stringifying keys) has been removed.
    assert new String(MemcacheSerialization.makePbKey(entB2.getKey())).equals(new String(MemcacheSerialization.makePbKey(childKeyB)));
}

12. EvilMemcacheBugTests#testRawTransactionalCaching()

Project: objectify
Source File: EvilMemcacheBugTests.java
View license
//	/** */
//	@Test
//	public void testMoreSophisticatedInAndOutOfTransaction() throws Exception {
//		fact().register(SimpleParent.class);
//		fact().register(SimpleEntity.class);
//		String simpleId = "btoc";
//
//		Key<SimpleEntity> childKey = SimpleEntity.getSimpleChildKey(simpleId);
//		SimpleEntity simple = new SimpleEntity(simpleId);
//
//		TestObjectify nonTxnOfy = fact().begin();
//		nonTxnOfy.put(simple);
//
//		TestObjectify txnOfy = fact().begin().startTransaction();
//		SimpleEntity simple2;
//		try {
//			simple2 = txnOfy.get(childKey);
//			simple2.foo = "joe";
//			txnOfy.put(simple2);
//			txnOfy.getTransaction().commit();
//		} finally {
//			if (txnOfy.getTransaction().isActive())
//				txnOfy.getTransaction().rollback();
//		}
//
//		nonTxnOfy.clear();
//		SimpleEntity simple3 = nonTxnOfy.get(childKey);
//
//		assert simple2.foo.equals(simple3.foo);
//	}
/** */
@Test
public void testRawTransactionalCaching() throws Exception {
    // Need to register it so the entity kind becomes cacheable
    fact().register(SimpleEntity.class);
    DatastoreService ds = TestObjectifyService.ds();
    DatastoreService cacheds = CachingDatastoreServiceFactory.getDatastoreService();
    // This is the weirdest thing.  If you change the *name* of one of these two keys, the test passes.
    // If the keys have the same *name*, the test fails because ent3 has the "original" property.  WTF??
    com.google.appengine.api.datastore.Key parentKey = KeyFactory.createKey("SimpleParent", "asdf");
    com.google.appengine.api.datastore.Key childKey = KeyFactory.createKey(parentKey, "SimpleEntity", "asdf");
    Entity ent1 = new Entity(childKey);
    ent1.setProperty("foo", "original");
    cacheds.put(ent1);
    // Weirdly, this will solve the problem too
    //MemcacheService cs = MemcacheServiceFactory.getMemcacheService();
    //cs.clearAll();
    Transaction txn = cacheds.beginTransaction();
    Entity ent2;
    try {
        ent2 = ds.get(txn, childKey);
        //ent2 = new Entity(childKey);	// solves the problem
        ent2.setProperty("foo", "changed");
        cacheds.put(txn, ent2);
        txn.commit();
    } finally {
        if (txn.isActive())
            txn.rollback();
    }
    Entity ent3 = cacheds.get(childKey);
    assert "changed".equals(ent3.getProperty("foo"));
}

13. GaeDatastoreUserRegistry#removeUser()

View license
public void removeUser(String userId) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key key = KeyFactory.createKey(USER_TYPE, userId);
    datastore.delete(key);
}

14. EvilMemcacheBugTests#testRawCaching()

Project: objectify
Source File: EvilMemcacheBugTests.java
View license
/** */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testRawCaching() throws Exception {
    // I can not for the life of me figure out why this test passes when the
    // previous test fails.
    MemcacheService cs1 = MemcacheServiceFactory.getMemcacheService("blah");
    com.google.appengine.api.datastore.Key parentKey = KeyFactory.createKey("SimpleParent", "asdf");
    com.google.appengine.api.datastore.Key childKey = KeyFactory.createKey(parentKey, "SimpleEntity", "asdf");
    Entity ent = new Entity(childKey);
    ent.setProperty("foo", "original");
    cs1.put(childKey, ent);
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    ds.put(ent);
    Transaction txn = ds.beginTransaction();
    try {
        Entity ent2 = ds.get(txn, childKey);
        //Entity ent2 = (Entity)cs1.get(childKey);
        assert ent2.getProperty("foo").equals("original");
        ent2.setProperty("foo", "changed");
        Map<Object, Object> holder = new HashMap<>();
        holder.put(childKey, ent2);
        cs1.putAll(holder);
        Map<Object, Object> fetched = cs1.getAll((Collection) Collections.singleton(childKey));
        Entity ent3 = (Entity) fetched.get(childKey);
        assert ent3.getProperty("foo").equals("changed");
    } finally {
        if (txn.isActive())
            txn.rollback();
    }
}

15. AppEngineCredentialStore#delete()

View license
@Override
public void delete(String userId, Credential credential) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key key = KeyFactory.createKey(KIND, userId);
    datastore.delete(key);
}

16. AppEngineCredentialStore#store()

View license
@Override
public void store(String userId, Credential credential) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity entity = new Entity(KIND, userId);
    entity.setProperty("accessToken", credential.getAccessToken());
    entity.setProperty("refreshToken", credential.getRefreshToken());
    entity.setProperty("expirationTimeMillis", credential.getExpirationTimeMilliseconds());
    datastore.put(entity);
}

17. CachingDatastoreServiceFactory#getDatastoreService()

View license
/**
	 * Get a caching DatastoreService that uses a particular EntityMemcache configuration.
	 * Ignores the default memcacheService for this factory; that is set when you construct
	 * your EntityMemcache.
	 */
public static CachingDatastoreService getDatastoreService(DatastoreServiceConfig cfg, EntityMemcache em) {
    CachingAsyncDatastoreService cads = getAsyncDatastoreService(cfg, em);
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService(cfg);
    return new CachingDatastoreService(ds, cads);
}

18. CachingDatastoreServiceFactory#getDatastoreService()

View license
/**
	 * Get a caching DatastoreService that uses a particular EntityMemcache configuration. 
	 * Ignores the default memcacheService for this factory; that is set when you construct
	 * your EntityMemcache.
	 */
public static CachingDatastoreService getDatastoreService(EntityMemcache em) {
    CachingAsyncDatastoreService cads = getAsyncDatastoreService(em);
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    return new CachingDatastoreService(ds, cads);
}

19. NotificationCleanupServlet#doCleanup()

View license
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");
}

20. TestObjectifyService#ds()

Project: objectify
Source File: TestObjectifyService.java
View license
/**
	 * Get a DatastoreService
	 */
public static DatastoreService ds() {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    return ds;
}

21. AppEngineCredentialStore#migrateTo()

View license
/**
   * 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);
    }
}

22. NotificationCleanupServlet#doCleanup()

View license
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");
}

23. GaeDatastoreUserRegistry#findUser()

View license
public GaeUser findUser(String userId) {
    Key key = KeyFactory.createKey(USER_TYPE, userId);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    try {
        Entity user = datastore.get(key);
        long binaryAuthorities = (Long) user.getProperty(USER_AUTHORITIES);
        Set<AppRole> roles = EnumSet.noneOf(AppRole.class);
        for (AppRole r : AppRole.values()) {
            if ((binaryAuthorities & (1 << r.getBit())) != 0) {
                roles.add(r);
            }
        }
        GaeUser gaeUser = new GaeUser(user.getKey().getName(), (String) user.getProperty(USER_NICKNAME), (String) user.getProperty(USER_EMAIL), (String) user.getProperty(USER_FORENAME), (String) user.getProperty(USER_SURNAME), roles, (Boolean) user.getProperty(USER_ENABLED));
        return gaeUser;
    } catch (EntityNotFoundException e) {
        logger.debug(userId + " not found in datastore");
        return null;
    }
}