com.google.appengine.api.datastore.Entity

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

1. GaeDatastoreUserRegistry#registerUser()

Project: spring-security
File: GaeDatastoreUserRegistry.java
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. DatastoreStateRepository#setFeatureState()

Project: togglz
File: DatastoreStateRepository.java
@Override
public void setFeatureState(final FeatureState featureState) {
    final Entity featureEntity = new Entity(kind(), featureState.getFeature().name());
    featureEntity.setUnindexedProperty(ENABLED, featureState.isEnabled());
    featureEntity.setUnindexedProperty(STRATEGY_ID, featureState.getStrategyId());
    final Map<String, String> params = featureState.getParameterMap();
    if (params != null && !params.isEmpty()) {
        final List<String> strategyParamsNames = new ArrayList<String>(params.size());
        final List<String> strategyParamsValues = new ArrayList<String>(params.size());
        for (final String paramName : params.keySet()) {
            strategyParamsNames.add(paramName);
            strategyParamsValues.add(params.get(paramName));
        }
        featureEntity.setUnindexedProperty(STRATEGY_PARAMS_NAMES, strategyParamsNames);
        featureEntity.setUnindexedProperty(STRATEGY_PARAMS_VALUES, strategyParamsValues);
    }
    putInsideTransaction(featureEntity);
}

3. CloudEndpointsConfigManager#setAuthenticationInfo()

Project: solutions-mobile-backend-starter-java
File: CloudEndpointsConfigManager.java
/**
   * Configures the Cloud Endpoints exposed from this backend. Specifically, it
   * configures {@link EndpointV1} endpoints. This call overwrites any
   * previously specified settings.
   * 
   * @param clientIds
   *          list of clientIds that will be allowed to make authenticated calls
   *          to this backend.
   * @param audiences
   *          list of audiences that will be allowed to make authenticated calls
   *          to this backend.
   */
public void setAuthenticationInfo(Class<?> endpointClass, List<String> clientIds, List<String> audiences) {
    Entity config = getEndpointEntity(endpointClass);
    config.setProperty(CLIENT_IDS, clientIds);
    config.setProperty(AUDIENCES, audiences);
    datastoreService.put(config);
    // Google Cloud Endpoints infrastructure caches the configuration in Memcache.
    // In order for the changes to be applied without restart/redeployment
    // they need to be updated not only in Datastore, but also in Memcache.
    memcacheService.put(ENDPOINT_CONFIGURATION_KIND + "." + endpointClass.getName(), config);
}

4. RawEntityTests#deleteRawEntityWorks()

Project: objectify
File: RawEntityTests.java
/** */
@Test
public void deleteRawEntityWorks() throws Exception {
    Entity ent = new Entity("asdf");
    ent.setProperty("foo", "bar");
    ofy().save().entity(ent).now();
    ofy().clear();
    ofy().delete().entity(ent);
    Entity fetched = ofy().load().<Entity>value(ent).now();
    assertThat(fetched, nullValue());
}

5. RawEntityTests#saveAndLoadRawEntityWorks()

Project: objectify
File: RawEntityTests.java
/** */
@Test
public void saveAndLoadRawEntityWorks() throws Exception {
    Entity ent = new Entity("asdf");
    ent.setProperty("foo", "bar");
    ofy().save().entity(ent).now();
    ofy().clear();
    Entity fetched = ofy().load().<Entity>value(ent).now();
    assertThat(fetched.getProperty("foo"), equalTo(ent.getProperty("foo")));
}

6. DatastoreEntityTests#testCollectionContainingNullInEntity()

Project: objectify
File: DatastoreEntityTests.java
/**
	 * 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;
}

7. DatastoreEntityTests#testEmptyCollectionInEntity()

Project: objectify
File: DatastoreEntityTests.java
/**
	 * 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;
}

8. AlsoLoadTests2#testAlsoLoadMap()

Project: objectify
File: AlsoLoadTests2.java
@Test
public void testAlsoLoadMap() throws Exception {
    fact().register(HasMap.class);
    Entity ent = new Entity(Key.getKind(HasMap.class));
    ent.setProperty("alsoPrimitives", makeEmbeddedEntityWithProperty("one", 1L));
    ent.setProperty("primitives", makeEmbeddedEntityWithProperty("two", 2L));
    ds().put(ent);
    Key<HasMap> key = Key.create(ent.getKey());
    try {
        ofy().load().key(key).now();
        assert false;
    } catch (TranslateException ex) {
    }
}

9. AlsoLoadTests#testHarderHasEmbeddedArray()

Project: objectify
File: AlsoLoadTests.java
/** */
@Test
public void testHarderHasEmbeddedArray() throws Exception {
    List<String> values = new ArrayList<>();
    values.add(TEST_VALUE);
    values.add(TEST_VALUE);
    Entity ent = new Entity(Key.getKind(HasEmbeddedArray.class));
    List<EmbeddedEntity> list = new ArrayList<>();
    list.add(makeEmbeddedEntityWithProperty("oldFoo", TEST_VALUE));
    list.add(makeEmbeddedEntityWithProperty("oldFoo", TEST_VALUE));
    ent.setProperty("oldFieldUsers", list);
    ent.setProperty("oldMethodUsers", list);
    ds().put(ent);
    Key<HasEmbeddedArray> key = Key.create(ent.getKey());
    HasEmbeddedArray fetched = ofy().load().key(key).now();
    HasAlsoLoadField[] expectedFieldUsers = new HasAlsoLoadField[] { new HasAlsoLoadField(TEST_VALUE), new HasAlsoLoadField(TEST_VALUE) };
    HasAlsoLoadMethod[] expectedMethodUsers = new HasAlsoLoadMethod[] { new HasAlsoLoadMethod(TEST_VALUE), new HasAlsoLoadMethod(TEST_VALUE) };
    assert Arrays.equals(fetched.fieldUsers, expectedFieldUsers);
    assert Arrays.equals(fetched.methodUsers, expectedMethodUsers);
}

10. AlsoLoadTests#testEasyHasEmbeddedArray()

Project: objectify
File: AlsoLoadTests.java
/** */
@Test
public void testEasyHasEmbeddedArray() throws Exception {
    List<String> values = new ArrayList<>();
    values.add(TEST_VALUE);
    values.add(TEST_VALUE);
    Entity ent = new Entity(Key.getKind(HasEmbeddedArray.class));
    List<EmbeddedEntity> list = new ArrayList<>();
    list.add(makeEmbeddedEntityWithProperty("oldFoo", TEST_VALUE));
    list.add(makeEmbeddedEntityWithProperty("oldFoo", TEST_VALUE));
    ent.setProperty("fieldUsers", list);
    ent.setProperty("methodUsers", list);
    ds().put(ent);
    Key<HasEmbeddedArray> key = Key.create(ent.getKey());
    HasEmbeddedArray fetched = ofy().load().key(key).now();
    HasAlsoLoadField[] expectedFieldUsers = new HasAlsoLoadField[] { new HasAlsoLoadField(TEST_VALUE), new HasAlsoLoadField(TEST_VALUE) };
    HasAlsoLoadMethod[] expectedMethodUsers = new HasAlsoLoadMethod[] { new HasAlsoLoadMethod(TEST_VALUE), new HasAlsoLoadMethod(TEST_VALUE) };
    assert Arrays.equals(fetched.fieldUsers, expectedFieldUsers);
    assert Arrays.equals(fetched.methodUsers, expectedMethodUsers);
}

11. AlsoLoadTests#testHarderHasEmbedded()

Project: objectify
File: AlsoLoadTests.java
/** */
@Test
public void testHarderHasEmbedded() throws Exception {
    Entity ent = new Entity(Key.getKind(HasEmbedded.class));
    ent.setProperty("oldFieldUser", makeEmbeddedEntityWithProperty("oldFoo", TEST_VALUE));
    ent.setProperty("oldMethodUser", makeEmbeddedEntityWithProperty("oldFoo", TEST_VALUE));
    ds().put(ent);
    Key<HasEmbedded> key = Key.create(ent.getKey());
    HasEmbedded fetched = ofy().load().key(key).now();
    assert TEST_VALUE.equals(fetched.fieldUser.foo);
    assert TEST_VALUE.equals(fetched.methodUser.foo);
}

12. AlsoLoadTests#testEasyHasEmbedded()

Project: objectify
File: AlsoLoadTests.java
/** */
@Test
public void testEasyHasEmbedded() throws Exception {
    Entity ent = new Entity(Key.getKind(HasEmbedded.class));
    ent.setProperty("fieldUser", makeEmbeddedEntityWithProperty("oldFoo", TEST_VALUE));
    ent.setProperty("methodUser", makeEmbeddedEntityWithProperty("oldFoo", TEST_VALUE));
    ds().put(ent);
    Key<HasEmbedded> key = Key.create(ent.getKey());
    HasEmbedded fetched = ofy().load().key(key).now();
    assert TEST_VALUE.equals(fetched.fieldUser.foo);
    assert TEST_VALUE.equals(fetched.methodUser.foo);
}

13. AlsoLoadTests#testAlsoLoadDuplicateError()

Project: objectify
File: AlsoLoadTests.java
/** */
@Test
public void testAlsoLoadDuplicateError() throws Exception {
    Entity ent = new Entity(Key.getKind(HasAlsoLoads.class));
    ent.setProperty("stuff", "stuff");
    ent.setProperty("oldStuff", "oldStuff");
    ds().put(ent);
    try {
        Key<HasAlsoLoads> key = Key.create(ent.getKey());
        ofy().load().key(key).now();
        assert false : "Shouldn't be able to read data duplicated with @AlsoLoad";
    } catch (Exception ex) {
    }
}

14. CloudEndpointsConfigManager#setAuthenticationInfo()

Project: io2014-codelabs
File: CloudEndpointsConfigManager.java
/**
   * Configures the Cloud Endpoints exposed from this backend. Specifically, it
   * configures {@link com.google.cloud.backend.spi.EndpointV1} endpoints. This call overwrites any
   * previously specified settings.
   * 
   * @param clientIds
   *          list of clientIds that will be allowed to make authenticated calls
   *          to this backend.
   * @param audiences
   *          list of audiences that will be allowed to make authenticated calls
   *          to this backend.
   */
public void setAuthenticationInfo(Class<?> endpointClass, List<String> clientIds, List<String> audiences) {
    Entity config = getEndpointEntity(endpointClass);
    config.setProperty(CLIENT_IDS, clientIds);
    config.setProperty(AUDIENCES, audiences);
    datastoreService.put(config);
    // Google Cloud Endpoints infrastructure caches the configuration in Memcache.
    // In order for the changes to be applied without restart/redeployment
    // they need to be updated not only in Datastore, but also in Memcache.
    memcacheService.put(ENDPOINT_CONFIGURATION_KIND + "." + endpointClass.getName(), config);
}

15. ValueTranslationTests#shortBlobsAreConvertedToByteArrays()

Project: objectify
File: ValueTranslationTests.java
/** */
@Test
public void shortBlobsAreConvertedToByteArrays() throws Exception {
    fact().register(Blobby.class);
    final Entity ent = new Entity("Blobby");
    final ShortBlob shortBlob = new ShortBlob(new byte[] { 1, 2, 3 });
    ent.setProperty("stuff", shortBlob);
    final Key<Blobby> blobbyKey = Key.create(ds().put(ent));
    final Blobby blobby = ofy().load().key(blobbyKey).safe();
    assert Arrays.equals(blobby.stuff, shortBlob.getBytes());
}

16. ValueTranslationTests#numbersCanBeConvertedToText()

Project: objectify
File: ValueTranslationTests.java
/**
	 * Stored numbers can be converted to Text in the data model
	 */
@Test
public void numbersCanBeConvertedToText() throws Exception {
    fact().register(HasText.class);
    Entity ent = new Entity(Key.getKind(HasText.class));
    // setting a number
    ent.setProperty("text", 2);
    ds().put(null, ent);
    Key<HasText> key = Key.create(ent.getKey());
    HasText fetched = ofy().load().key(key).now();
    assert fetched.text.getValue().equals("2");
}

17. ValueTranslationTests#stringsCanBeConvertedToText()

Project: objectify
File: ValueTranslationTests.java
/**
	 * Stored Strings can be converted to Text in the data model
	 */
@Test
public void stringsCanBeConvertedToText() throws Exception {
    fact().register(HasText.class);
    Entity ent = new Entity(Key.getKind(HasText.class));
    // setting a string
    ent.setProperty("text", "foo");
    ds().put(null, ent);
    Key<HasText> key = Key.create(ent.getKey());
    HasText fetched = ofy().load().key(key).now();
    assert fetched.text.getValue().equals("foo");
}

18. ValueTranslationTests#stringToNumber()

Project: objectify
File: ValueTranslationTests.java
/**
	 * 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;
}

19. ValueTranslationTests#numberToString()

Project: objectify
File: ValueTranslationTests.java
/**
	 * Anything can be converted to a String
	 */
@Test
public void numberToString() throws Exception {
    fact().register(HasString.class);
    Entity ent = new Entity(Key.getKind(HasString.class));
    // setting a number
    ent.setProperty("string", 2);
    ds().put(null, ent);
    Key<HasString> key = Key.create(ent.getKey());
    HasString fetched = ofy().load().key(key).now();
    // should be a string
    assert fetched.string.equals("2");
}

20. TriggerFutureTests#testSimpleAsyncGetWithDatastore()

Project: objectify
File: TriggerFutureTests.java
/** This seemed to be an issue related to the listenable but apparently not */
@Test
public void testSimpleAsyncGetWithDatastore() throws Exception {
    AsyncDatastoreService ads = DatastoreServiceFactory.getAsyncDatastoreService();
    Entity ent = new Entity("thing");
    ent.setUnindexedProperty("foo", "bar");
    // Without the null txn (ie, using implicit transactions) we get a "handle 0 not found" error
    Future<Key> fut = ads.put(null, ent);
    fut.get();
}

21. NullDefaultFieldTests#testNewVersionOfEntity()

Project: objectify
File: NullDefaultFieldTests.java
/**
	 * Test that an entity in the datastore with absent fields loads correctly,
	 * when the fields in the entity class have default values
	 */
@Test
public void testNewVersionOfEntity() throws Exception {
    fact().register(EntityWithDefault.class);
    // e1 has absent properties
    Entity e1 = new Entity("EntityWithDefault");
    e1.setProperty("a", "1");
    com.google.appengine.api.datastore.Key k1 = ds().put(null, e1);
    EntityWithDefault o = ofy().load().type(EntityWithDefault.class).id(k1.getId()).now();
    assert o.a != null;
    assert "1".equals(o.a);
    assert o.b != null;
    assert "foo".equals(o.b);
    assert o.c != null;
    assert "bar".equals(o.c);
    assert o.s != null;
    assert "default2".equals(o.s.s);
}

22. IgnoreSaveTests#testCompletelyUnsaved()

Project: objectify
File: IgnoreSaveTests.java
/** */
@Test
public void testCompletelyUnsaved() throws Exception {
    fact().register(CompletelyUnsaved.class);
    Entity ent = new Entity(Key.getKind(CompletelyUnsaved.class));
    ent.setProperty("foo", TEST_VALUE);
    ds().put(null, ent);
    Key<CompletelyUnsaved> key = Key.create(ent.getKey());
    CompletelyUnsaved fetched = ofy().load().key(key).now();
    assert fetched.foo.equals(TEST_VALUE);
    fetched = ofy().saveClearLoad(fetched);
    // this would fail without the session clear()
    assert fetched.foo == null;
}

23. CollectionTests#testCollectionContainingNull()

Project: objectify
File: CollectionTests.java
@Test
public void testCollectionContainingNull() throws Exception {
    fact().register(HasCollections.class);
    HasCollections hc = new HasCollections();
    hc.integerList = Arrays.asList((Integer) null);
    Key<HasCollections> key = ofy().save().entity(hc).now();
    hc = ofy().load().key(key).now();
    assert hc.integerList != null;
    assert hc.integerList.size() == 1;
    assert hc.integerList.get(0) == null;
    Entity e = ds().get(key.getRaw());
    assert e.hasProperty("integerList");
    List<?> l = (List<?>) e.getProperty("integerList");
    assert l != null;
    assert l.size() == 1;
    assert l.get(0) == null;
}

24. AlsoLoadTests2#testMethodOverridingField()

Project: objectify
File: AlsoLoadTests2.java
/** */
@Test
public void testMethodOverridingField() throws Exception {
    com.google.appengine.api.datastore.Entity ent = new com.google.appengine.api.datastore.Entity(Key.getKind(MethodOverridesField.class));
    ent.setProperty("foo", TEST_VALUE);
    ds().put(ent);
    Key<MethodOverridesField> key = Key.create(ent.getKey());
    MethodOverridesField fetched = ofy().load().key(key).now();
    assert fetched.foo == null;
    assert fetched.bar.equals(TEST_VALUE);
}

25. AlsoLoadTests#testSimpleAlsoLoad()

Project: objectify
File: AlsoLoadTests.java
/** */
@Test
public void testSimpleAlsoLoad() throws Exception {
    Entity ent = new Entity(Key.getKind(HasAlsoLoads.class));
    ent.setProperty("oldStuff", "oldStuff");
    ds().put(ent);
    Key<HasAlsoLoads> key = Key.create(ent.getKey());
    HasAlsoLoads fetched = ofy().load().key(key).now();
    assert fetched.getStuff().equals("oldStuff");
    assert fetched.getOtherStuff() == null;
}

26. DatastoreStateRepository#getInsideTransaction()

Project: togglz
File: DatastoreStateRepository.java
/**
     * @param key
     * @return
     * @throws EntityNotFoundException
     */
protected Entity getInsideTransaction(final Key key) throws EntityNotFoundException {
    Entity featureEntity;
    if (this.datastoreService.getCurrentTransaction(null) == null) {
        featureEntity = this.datastoreService.get(key);
    } else {
        final Transaction txn = this.datastoreService.beginTransaction();
        try {
            featureEntity = this.datastoreService.get(txn, key);
            txn.commit();
        } finally {
            if (txn.isActive()) {
                txn.rollback();
            }
        }
    }
    return featureEntity;
}

27. ProspectiveSearchServlet#isSubscriptionActive()

Project: solutions-mobile-backend-starter-java
File: ProspectiveSearchServlet.java
/**
   * Checks if subscriptions for the device are active.
   *
   * @param deviceId A unique device identifier
   * @return True, if subscriptions are active; False, the otherwise
   */
private boolean isSubscriptionActive(String deviceId) {
    Date lastDeleteAll = backendConfigManager.getLastSubscriptionDeleteAllTime();
    // still active.
    if (lastDeleteAll == null) {
        return true;
    }
    Entity deviceEntity = deviceSubscription.get(deviceId);
    if (deviceEntity == null) {
        return false;
    }
    Date latestSubscriptionTime = (Date) deviceEntity.getProperty(DeviceSubscription.PROPERTY_TIMESTAMP);
    return latestSubscriptionTime.after(lastDeleteAll);
}

28. DeviceSubscription#getSubscriptionIds()

Project: solutions-mobile-backend-starter-java
File: DeviceSubscription.java
/**
   * Returns a set of subscriptions subscribed from the device.
   *
   * @param deviceId A unique device identifier 
   */
public Set<String> getSubscriptionIds(String deviceId) {
    if (StringUtility.isNullOrEmpty(deviceId)) {
        return new HashSet<String>();
    }
    Entity deviceSubscription = get(deviceId);
    if (deviceSubscription == null) {
        return new HashSet<String>();
    }
    String subscriptionString = (String) deviceSubscription.getProperty(PROPERTY_SUBSCRIPTION_IDS);
    if (StringUtility.isNullOrEmpty(subscriptionString)) {
        return new HashSet<String>();
    }
    return this.gson.fromJson(subscriptionString, setType);
}

29. DeviceSubscription#get()

Project: solutions-mobile-backend-starter-java
File: DeviceSubscription.java
/**
   * Returns an entity with device subscription information from memcache or datastore based on the
   *     provided deviceId.
   *
   * @param deviceId A unique device identifier
   * @return an entity with device subscription information; or null when no corresponding
   *         information found
   */
public Entity get(String deviceId) {
    if (StringUtility.isNullOrEmpty(deviceId)) {
        throw new IllegalArgumentException("DeviceId cannot be null or empty");
    }
    Key key = getKey(deviceId);
    Entity entity = (Entity) this.memcacheService.get(key);
    // Get from datastore if unable to get data from cache
    if (entity == null) {
        try {
            entity = this.datastoreService.get(key);
        } catch (EntityNotFoundException e) {
            return null;
        }
    }
    return entity;
}

30. CrudOperations#deleteAll()

Project: solutions-mobile-backend-starter-java
File: CrudOperations.java
protected EntityListDto deleteAll(EntityListDto cdl, User user) throws UnauthorizedException {
    // check ACL
    Map<String, Entity> entities = getAllEntitiesByKeyList(cdl.readKeyList(user));
    for (Entity e : entities.values()) {
        SecurityChecker.getInstance().checkAclForWrite(e, user);
    }
    // delete from memcache
    memcache.deleteAll(cdl.readIdList());
    // delete all the Entities
    datastore.delete(cdl.readKeyList(user));
    // return a dummy collection
    return new EntityListDto();
}

31. CrudOperations#delete()

Project: solutions-mobile-backend-starter-java
File: CrudOperations.java
protected EntityDto delete(@Named("kind") String kindName, @Named("id") String id, User user) throws UnauthorizedException {
    // check ACL
    Entity e;
    try {
        e = getEntityById(kindName, id, user);
    } catch (NotFoundException e1) {
        return null;
    }
    SecurityChecker.getInstance().checkAclForWrite(e, user);
    // delete from memcache
    memcache.delete(id);
    // delete the CE
    datastore.delete(e.getKey());
    // return a EntityDto
    return EntityDto.createFromEntity(e);
}

32. CrudOperations#getAllEntities()

Project: solutions-mobile-backend-starter-java
File: CrudOperations.java
protected EntityListDto getAllEntities(EntityListDto cdl, User user) {
    // get all entities by CbIdList
    Map<String, Entity> entities = getAllEntitiesByKeyList(cdl.readKeyList(user));
    // convert to CbDtos
    EntityListDto resultCdl = new EntityListDto();
    for (Entity e : entities.values()) {
        EntityDto cd = EntityDto.createFromEntity(e);
        resultCdl.getEntries().add(cd);
    }
    return resultCdl;
}

33. CrudOperations#getEntityById()

Project: solutions-mobile-backend-starter-java
File: CrudOperations.java
private Entity getEntityById(String kindName, String id, User user) throws NotFoundException {
    // try to find the Entity on Memcache
    Entity e = (Entity) memcache.get(id);
    // try to find the Entity
    if (e == null) {
        try {
            e = datastore.get(SecurityChecker.getInstance().createKeyWithNamespace(kindName, id, user));
        } catch (EntityNotFoundException e2) {
            throw new NotFoundException("Cloud Entity not found for id: " + id);
        }
    }
    return e;
}

34. ConfigurationServlet#readConfig()

Project: solutions-mobile-backend-starter-java
File: ConfigurationServlet.java
private void readConfig(JsonObject jsonResponse) {
    Entity config = configMgr.getConfiguration();
    jsonResponse.addProperty(BackendConfigManager.AUTHENTICATION_MODE, (String) config.getProperty(BackendConfigManager.AUTHENTICATION_MODE));
    jsonResponse.addProperty(BackendConfigManager.ANDROID_CLIENT_ID, (String) config.getProperty(BackendConfigManager.ANDROID_CLIENT_ID));
    jsonResponse.addProperty(BackendConfigManager.IOS_CLIENT_ID, (String) config.getProperty(BackendConfigManager.IOS_CLIENT_ID));
    jsonResponse.addProperty(BackendConfigManager.AUDIENCE, (String) config.getProperty(BackendConfigManager.AUDIENCE));
    jsonResponse.addProperty(BackendConfigManager.PUSH_ENABLED, (Boolean) config.getProperty(BackendConfigManager.PUSH_ENABLED));
    jsonResponse.addProperty(BackendConfigManager.ANDROID_GCM_KEY, (String) config.getProperty(BackendConfigManager.ANDROID_GCM_KEY));
    jsonResponse.addProperty(BackendConfigManager.PUSH_NOTIFICATION_CERT_PASSWORD, (String) config.getProperty(BackendConfigManager.PUSH_NOTIFICATION_CERT_PASSWORD));
}

35. TranslationTests#simplePojoEntityTranslates()

Project: objectify
File: TranslationTests.java
/**
	 */
@Test
public void simplePojoEntityTranslates() throws Exception {
    CreateContext createCtx = new CreateContext(fact());
    ClassTranslator<SimpleEntityPOJO> translator = ClassTranslatorFactory.createEntityClassTranslator(SimpleEntityPOJO.class, createCtx, Path.root());
    SimpleEntityPOJO pojo = new SimpleEntityPOJO();
    pojo.id = 123L;
    pojo.foo = "bar";
    SaveContext saveCtx = new SaveContext();
    Entity ent = (Entity) translator.save(pojo, false, saveCtx, Path.root());
    assert ent.getKey().getKind().equals(SimpleEntityPOJO.class.getSimpleName());
    assert ent.getKey().getId() == pojo.id;
    assert ent.getProperties().size() == 1;
    assert ent.getProperty("foo").equals("bar");
}

36. IgnoreSaveTests#testUnsavedDefaults()

Project: objectify
File: IgnoreSaveTests.java
/** */
@Test
public void testUnsavedDefaults() throws Exception {
    fact().register(UnsavedDefaults.class);
    UnsavedDefaults thing = new UnsavedDefaults();
    Key<UnsavedDefaults> key = ofy().save().entity(thing).now();
    // Now get the raw entity and verify that it doesn't have properties saved
    Entity ent = ds().get(null, key.getRaw());
    assert ent.getProperties().isEmpty();
}

37. EmbeddingFormatTests#indexFormatIsCorrect()

Project: objectify
File: EmbeddingFormatTests.java
/** */
@Test
public void indexFormatIsCorrect() throws Exception {
    fact().register(OuterWithIndex.class);
    InnerIndexed inner = new InnerIndexed("stuff");
    OuterWithIndex outer = new OuterWithIndex(inner);
    Key<OuterWithIndex> key = ofy().save().entity(outer).now();
    Entity entity = ds().get(key.getRaw());
    assert entity.getProperties().size() == 2;
    assert entity.getProperty("inner.stuff").equals(Collections.singletonList("stuff"));
    assert !entity.isUnindexedProperty("inner.stuff");
    ofy().clear();
    OuterWithIndex fetched = ofy().load().type(OuterWithIndex.class).filter("inner.stuff", "stuff").iterator().next();
    assert fetched.inner.stuff.equals(inner.stuff);
}

38. EmbeddingFormatTests#embeddedList()

Project: objectify
File: EmbeddingFormatTests.java
/** */
@Test
public void embeddedList() throws Exception {
    fact().register(OuterWithList.class);
    OuterWithList outer = new OuterWithList();
    outer.inner.add(new Inner("stuff0"));
    outer.inner.add(new Inner("stuff1"));
    Key<OuterWithList> key = ofy().save().entity(outer).now();
    Entity entity = ds().get(key.getRaw());
    @SuppressWarnings("unchecked") List<EmbeddedEntity> entityInner = (List<EmbeddedEntity>) entity.getProperty("inner");
    assert entityInner.size() == 2;
    assert entityInner.get(0).getProperty("stuff").equals("stuff0");
    assert entityInner.get(1).getProperty("stuff").equals("stuff1");
    ofy().clear();
    OuterWithList fetched = ofy().load().key(key).now();
    assert fetched.inner.get(0).stuff.equals(outer.inner.get(0).stuff);
    assert fetched.inner.get(1).stuff.equals(outer.inner.get(1).stuff);
}

39. EmbeddingFormatTests#simpleOneLayerEmbedding()

Project: objectify
File: EmbeddingFormatTests.java
/** */
@Test
public void simpleOneLayerEmbedding() throws Exception {
    fact().register(Outer.class);
    Inner inner = new Inner("stuff");
    Outer outer = new Outer(inner);
    Key<Outer> key = ofy().save().entity(outer).now();
    Entity entity = ds().get(key.getRaw());
    EmbeddedEntity entityInner = (EmbeddedEntity) entity.getProperty("inner");
    assert entityInner.getProperty("stuff").equals("stuff");
    ofy().clear();
    Outer fetched = ofy().load().key(key).now();
    assert fetched.inner.stuff.equals(inner.stuff);
}

40. EmbeddedMapFormatTests#v2EmbedMapFormatIsCorrect()

Project: objectify
File: EmbeddedMapFormatTests.java
/** */
@Test
public void v2EmbedMapFormatIsCorrect() throws Exception {
    fact().register(OuterWithMap.class);
    OuterWithMap outer = new OuterWithMap();
    outer.map.put("asdf", 123L);
    Key<OuterWithMap> key = ofy().save().entity(outer).now();
    Entity entity = ds().get(key.getRaw());
    EmbeddedEntity entityInner = (EmbeddedEntity) entity.getProperty("map");
    assert entityInner.getProperty("asdf").equals(123L);
    ofy().clear();
    OuterWithMap fetched = ofy().load().key(key).now();
    assert fetched.map.equals(outer.map);
}

41. DatastoreEntityTests#testSerializableObjectProperty()

Project: objectify
File: DatastoreEntityTests.java
/**
	 * What happens if it is serializable?
	 */
@Test
public void testSerializableObjectProperty() throws Exception {
    SerializableThing thing = new SerializableThing();
    thing.name = "foo";
    thing.age = 10;
    Entity ent = new Entity("Test");
    try {
        ent.setProperty("thing", thing);
        assert false;
    } catch (IllegalArgumentException ex) {
    }
//		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
//		ds.put(ent);
//		
//		Entity fetched = ds.get(ent.getKey());
//		SerializableThing fetchedThing = (SerializableThing)fetched.getProperty("thing");
//		assert thing.name.equals(fetchedThing.name);
//		assert thing.age == fetchedThing.age;
}

42. DatastoreEntityTests#testObjectProperty()

Project: objectify
File: DatastoreEntityTests.java
/**
	 * What happens when you put an object in an Entity?
	 */
@Test
public void testObjectProperty() throws Exception {
    Thing thing = new Thing();
    thing.name = "foo";
    thing.age = 10;
    Entity ent = new Entity("Test");
    try {
        ent.setProperty("thing", thing);
        assert false;
    } catch (IllegalArgumentException ex) {
    }
//		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
//		ds.put(ent);
//		
//		Entity fetched = ds.get(ent.getKey());
//		Thing fetchedThing = (Thing)fetched.getProperty("thing");
//		assert thing.name.equals(fetchedThing.name);
//		assert thing.age == fetchedThing.age;
}

43. CollectionTests#testEmptyCollections()

Project: objectify
File: CollectionTests.java
/**
	 * Test rule: never store an empty Collection, leaves value as null
	 */
@Test
public void testEmptyCollections() throws Exception {
    fact().register(HasCollections.class);
    HasCollections hc = new HasCollections();
    hc.integerList = new ArrayList<>();
    Key<HasCollections> key = ofy().save().entity(hc).now();
    ofy().clear();
    hc = ofy().load().key(key).now();
    System.out.println(ds().get(Key.create(hc).getRaw()));
    // This wouldn't be valid if we didn't clear the session
    assert hc.integerList == null;
    Entity e = ds().get(key.getRaw());
    // rule : never store an empty collection
    assert !e.hasProperty("integerList");
    assert hc.initializedList != null;
    assert hc.initializedList instanceof LinkedList<?>;
}

44. CollectionTests#testNullCollections()

Project: objectify
File: CollectionTests.java
/**
	 * Rule: never store a null Collection, always leave it alone when loaded
	 */
@Test
public void testNullCollections() throws Exception {
    fact().register(HasCollections.class);
    HasCollections hc = new HasCollections();
    hc.integerList = null;
    Key<HasCollections> key = ofy().save().entity(hc).now();
    hc = ofy().load().key(key).now();
    ofy().save().entity(hc).now();
    hc = ofy().load().key(key).now();
    // not loaded
    assert hc.integerList == null;
    Entity e = ds().get(key.getRaw());
    // rule : never store a null collection
    assert !e.hasProperty("integerList");
}

45. CachingDatastoreTests#setUpExtra()

Project: objectify
File: CachingDatastoreTests.java
/**
	 */
@BeforeMethod
public void setUpExtra() {
    EntityMemcache mc = new EntityMemcache(null);
    cads = new CachingAsyncDatastoreService(DatastoreServiceFactory.getAsyncDatastoreService(), mc);
    nods = new CachingAsyncDatastoreService(new MockAsyncDatastoreService(), mc);
    key = KeyFactory.createKey("thing", 1);
    keyInSet = Collections.singleton(key);
    entity = new Entity(key);
    entity.setProperty("foo", "bar");
    entityInList = Collections.singletonList(entity);
}

46. APIUpdater#isUpToDate()

Project: iosched
File: APIUpdater.java
private boolean isUpToDate(byte[] newHash, UpdateRunLogger logger) {
    Entity lastUpdate = logger.getLastRun();
    byte[] currentHash = null;
    if (lastUpdate != null) {
        ShortBlob hash = (ShortBlob) lastUpdate.getProperty("hash");
        if (hash != null) {
            currentHash = hash.getBytes();
        }
    }
    return Arrays.equals(currentHash, newHash);
}

47. ApiKeyInitializer#contextInitialized()

Project: iosched
File: ApiKeyInitializer.java
@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);
}

48. ProspectiveSearchServlet#isSubscriptionActive()

Project: io2014-codelabs
File: ProspectiveSearchServlet.java
/**
   * Checks if subscriptions for the device are active.
   *
   * @param deviceId A unique device identifier
   * @return True, if subscriptions are active; False, the otherwise
   */
private boolean isSubscriptionActive(String deviceId) {
    Date lastDeleteAll = backendConfigManager.getLastSubscriptionDeleteAllTime();
    // still active.
    if (lastDeleteAll == null) {
        return true;
    }
    Entity deviceEntity = deviceSubscription.get(deviceId);
    if (deviceEntity == null) {
        return false;
    }
    Date latestSubscriptionTime = (Date) deviceEntity.getProperty(DeviceSubscription.PROPERTY_TIMESTAMP);
    return latestSubscriptionTime.after(lastDeleteAll);
}

49. DeviceSubscription#getSubscriptionIds()

Project: io2014-codelabs
File: DeviceSubscription.java
/**
   * Returns a set of subscriptions subscribed from the device.
   *
   * @param deviceId A unique device identifier 
   */
public Set<String> getSubscriptionIds(String deviceId) {
    if (StringUtility.isNullOrEmpty(deviceId)) {
        return new HashSet<String>();
    }
    Entity deviceSubscription = get(deviceId);
    if (deviceSubscription == null) {
        return new HashSet<String>();
    }
    String subscriptionString = (String) deviceSubscription.getProperty(PROPERTY_SUBSCRIPTION_IDS);
    if (StringUtility.isNullOrEmpty(subscriptionString)) {
        return new HashSet<String>();
    }
    return this.gson.fromJson(subscriptionString, setType);
}

50. DeviceSubscription#get()

Project: io2014-codelabs
File: DeviceSubscription.java
/**
   * Returns an entity with device subscription information from memcache or datastore based on the
   *     provided deviceId.
   *
   * @param deviceId A unique device identifier
   * @return an entity with device subscription information; or null when no corresponding
   *         information found
   */
public Entity get(String deviceId) {
    if (StringUtility.isNullOrEmpty(deviceId)) {
        throw new IllegalArgumentException("DeviceId cannot be null or empty");
    }
    Key key = getKey(deviceId);
    Entity entity = (Entity) this.memcacheService.get(key);
    // Get from datastore if unable to get data from cache
    if (entity == null) {
        try {
            entity = this.datastoreService.get(key);
        } catch (EntityNotFoundException e) {
            return null;
        }
    }
    return entity;
}

51. CrudOperations#deleteAll()

Project: io2014-codelabs
File: CrudOperations.java
protected EntityListDto deleteAll(EntityListDto cdl, User user) throws UnauthorizedException {
    // check ACL
    Map<String, Entity> entities = getAllEntitiesByKeyList(cdl.readKeyList(user));
    for (Entity e : entities.values()) {
        SecurityChecker.getInstance().checkAclForWrite(e, user);
    }
    // delete from memcache
    memcache.deleteAll(cdl.readIdList());
    // delete all the Entities
    datastore.delete(cdl.readKeyList(user));
    // return a dummy collection
    return new EntityListDto();
}

52. CrudOperations#delete()

Project: io2014-codelabs
File: CrudOperations.java
protected EntityDto delete(@Named("kind") String kindName, @Named("id") String id, User user) throws UnauthorizedException {
    // check ACL
    Entity e;
    try {
        e = getEntityById(kindName, id, user);
    } catch (NotFoundException e1) {
        return null;
    }
    SecurityChecker.getInstance().checkAclForWrite(e, user);
    // delete from memcache
    memcache.delete(id);
    // delete the CE
    datastore.delete(e.getKey());
    // return a EntityDto
    return EntityDto.createFromEntity(e);
}

53. CrudOperations#getAllEntities()

Project: io2014-codelabs
File: CrudOperations.java
protected EntityListDto getAllEntities(EntityListDto cdl, User user) {
    // get all entities by CbIdList
    Map<String, Entity> entities = getAllEntitiesByKeyList(cdl.readKeyList(user));
    // convert to CbDtos
    EntityListDto resultCdl = new EntityListDto();
    for (Entity e : entities.values()) {
        EntityDto cd = EntityDto.createFromEntity(e);
        resultCdl.getEntries().add(cd);
    }
    return resultCdl;
}

54. CrudOperations#getEntityById()

Project: io2014-codelabs
File: CrudOperations.java
private Entity getEntityById(String kindName, String id, User user) throws NotFoundException {
    // try to find the Entity on Memcache
    Entity e = (Entity) memcache.get(id);
    // try to find the Entity
    if (e == null) {
        try {
            e = datastore.get(SecurityChecker.getInstance().createKeyWithNamespace(kindName, id, user));
        } catch (EntityNotFoundException e2) {
            throw new NotFoundException("Cloud Entity not found for id: " + id);
        }
    }
    return e;
}

55. ConfigurationServlet#readConfig()

Project: io2014-codelabs
File: ConfigurationServlet.java
private void readConfig(JsonObject jsonResponse) {
    Entity config = configMgr.getConfiguration();
    jsonResponse.addProperty(BackendConfigManager.AUTHENTICATION_MODE, (String) config.getProperty(BackendConfigManager.AUTHENTICATION_MODE));
    jsonResponse.addProperty(BackendConfigManager.ANDROID_CLIENT_ID, (String) config.getProperty(BackendConfigManager.ANDROID_CLIENT_ID));
    jsonResponse.addProperty(BackendConfigManager.IOS_CLIENT_ID, (String) config.getProperty(BackendConfigManager.IOS_CLIENT_ID));
    jsonResponse.addProperty(BackendConfigManager.AUDIENCE, (String) config.getProperty(BackendConfigManager.AUDIENCE));
    jsonResponse.addProperty(BackendConfigManager.PUSH_ENABLED, (Boolean) config.getProperty(BackendConfigManager.PUSH_ENABLED));
    jsonResponse.addProperty(BackendConfigManager.ANDROID_GCM_KEY, (String) config.getProperty(BackendConfigManager.ANDROID_GCM_KEY));
    jsonResponse.addProperty(BackendConfigManager.PUSH_NOTIFICATION_CERT_PASSWORD, (String) config.getProperty(BackendConfigManager.PUSH_NOTIFICATION_CERT_PASSWORD));
}

56. MyEndpoint#getTasks()

Project: endpoints-codelab-android
File: MyEndpoint.java
@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;
}

57. BackendConfigManager#setConfiguration()

Project: solutions-mobile-backend-starter-java
File: BackendConfigManager.java
protected void setConfiguration(String authMode, String androidClientId, String iOSClientId, String audience, boolean pushEnabled, String androidGCMKey, String pushCertPasswd, String pushCertBase64String) {
    // put config entity into Datastore and Memcache
    Key key = getKey();
    Entity configuration;
    try {
        configuration = datastoreService.get(key);
    } catch (EntityNotFoundException e) {
        throw new IllegalStateException(e);
    }
    configuration.setProperty(AUTHENTICATION_MODE, authMode);
    configuration.setProperty(ANDROID_CLIENT_ID, androidClientId);
    configuration.setProperty(IOS_CLIENT_ID, iOSClientId);
    configuration.setProperty(AUDIENCE, audience);
    configuration.setProperty(PUSH_ENABLED, pushEnabled);
    configuration.setProperty(ANDROID_GCM_KEY, androidGCMKey);
    configuration.setProperty(PUSH_NOTIFICATION_CERT_PASSWORD, pushCertPasswd);
    if (!StringUtility.isNullOrEmpty(pushCertPasswd)) {
        Text data = removeClientHeaderFromData(pushCertBase64String);
        if (StringUtility.isNullOrEmpty(data)) {
            log.severe("Input file is not saved as it is not in expected format and encoding");
        } else {
            configuration.setProperty(PUSH_NOTIFICATION_CERT_BINARY, data);
        }
    }
    datastoreService.put(configuration);
    memcache.put(getMemKeyForConfigEntity(key), configuration);
    // Set endpoints auth config using client Ids that are not empty.
    List<String> clientIds = new ArrayList<String>();
    List<String> audiences = new ArrayList<String>();
    if (!StringUtility.isNullOrEmpty(androidClientId)) {
        clientIds.add(androidClientId);
    }
    if (!StringUtility.isNullOrEmpty(iOSClientId)) {
        clientIds.add(iOSClientId);
    }
    // The latter is the same as audience field.
    if (!StringUtility.isNullOrEmpty(audience)) {
        clientIds.add(audience);
        audiences.add(audience);
    } else {
        audiences.add(new String());
    }
    if (clientIds.size() == 0) {
        clientIds.add(new String());
    }
    endpointsConfigManager.setAuthenticationInfo(EndpointV1.class, clientIds, audiences);
    endpointsConfigManager.setAuthenticationInfo(BlobEndpoint.class, clientIds, audiences);
}

58. UpdateRunLogger#logUpdateRun()

Project: iosched
File: UpdateRunLogger.java
public void logUpdateRun(int majorVersion, int minorVersion, String filename, byte[] hash, JsonObject data, boolean forced) {
    Entity updateRun = new Entity(UPDATERUN_ENTITY_KIND);
    updateRun.setProperty("date", new Date());
    updateRun.setProperty("hash", new ShortBlob(hash));
    updateRun.setProperty("forced", forced);
    updateRun.setProperty("majorVersion", majorVersion);
    updateRun.setProperty("minorVersion", minorVersion);
    for (Entry<String, Long> performanceItem : timers.entrySet()) {
        updateRun.setProperty("time_" + performanceItem.getKey(), performanceItem.getValue());
    }
    updateRun.setProperty("filename", filename);
    StringBuilder sb = new StringBuilder();
    for (Entry<String, JsonElement> el : data.entrySet()) {
        if (el.getValue().isJsonArray()) {
            sb.append(el.getKey()).append("=").append(el.getValue().getAsJsonArray().size()).append(" ");
        }
    }
    if (sb.length() > 0) {
        // remove trailing space
        sb.deleteCharAt(sb.length() - 1);
    }
    updateRun.setProperty("summary", sb.toString());
    datastore.put(updateRun);
    timers.clear();
}

59. BackendConfigManager#setConfiguration()

Project: io2014-codelabs
File: BackendConfigManager.java
protected void setConfiguration(String authMode, String androidClientId, String iOSClientId, String audience, boolean pushEnabled, String androidGCMKey, String pushCertPasswd, String pushCertBase64String) {
    // put config entity into Datastore and Memcache
    Key key = getKey();
    Entity configuration;
    try {
        configuration = datastoreService.get(key);
    } catch (EntityNotFoundException e) {
        throw new IllegalStateException(e);
    }
    configuration.setProperty(AUTHENTICATION_MODE, authMode);
    configuration.setProperty(ANDROID_CLIENT_ID, androidClientId);
    configuration.setProperty(IOS_CLIENT_ID, iOSClientId);
    configuration.setProperty(AUDIENCE, audience);
    configuration.setProperty(PUSH_ENABLED, pushEnabled);
    configuration.setProperty(ANDROID_GCM_KEY, androidGCMKey);
    configuration.setProperty(PUSH_NOTIFICATION_CERT_PASSWORD, pushCertPasswd);
    if (!StringUtility.isNullOrEmpty(pushCertPasswd)) {
        Text data = removeClientHeaderFromData(pushCertBase64String);
        if (StringUtility.isNullOrEmpty(data)) {
            log.severe("Input file is not saved as it is not in expected format and encoding");
        } else {
            configuration.setProperty(PUSH_NOTIFICATION_CERT_BINARY, data);
        }
    }
    datastoreService.put(configuration);
    memcache.put(getMemKeyForConfigEntity(key), configuration);
    // Set endpoints auth config using client Ids that are not empty.
    List<String> clientIds = new ArrayList<String>();
    List<String> audiences = new ArrayList<String>();
    if (!StringUtility.isNullOrEmpty(androidClientId)) {
        clientIds.add(androidClientId);
    }
    if (!StringUtility.isNullOrEmpty(iOSClientId)) {
        clientIds.add(iOSClientId);
    }
    // The latter is the same as audience field.
    if (!StringUtility.isNullOrEmpty(audience)) {
        clientIds.add(audience);
        audiences.add(audience);
    } else {
        audiences.add(new String());
    }
    if (clientIds.size() == 0) {
        clientIds.add(new String());
    }
    endpointsConfigManager.setAuthenticationInfo(EndpointV1.class, clientIds, audiences);
    endpointsConfigManager.setAuthenticationInfo(BlobEndpoint.class, clientIds, audiences);
}

60. EvilMemcacheBugTests#testEntityKeys()

Project: objectify
File: EvilMemcacheBugTests.java
/** */
@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)));
}

61. EvilMemcacheBugTests#testRawTransactionalCaching()

Project: objectify
File: EvilMemcacheBugTests.java
//	/** */
//	@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"));
}

62. AppEngineCredentialStore#store()

Project: google-oauth-java-client
File: AppEngineCredentialStore.java
@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);
}

63. QueryOperations#executeQuery()

Project: solutions-mobile-backend-starter-java
File: QueryOperations.java
private EntityListDto executeQuery(QueryDto queryDto, User user) {
    // check if kindName is not the config kinds
    SecurityChecker.getInstance().checkIfKindNameAccessible(queryDto.getKindName());
    // create Query
    Query q = SecurityChecker.getInstance().createKindQueryWithNamespace(queryDto.getKindName(), user);
    q.setKeysOnly();
    // set filters
    FilterDto cf = queryDto.getFilterDto();
    if (cf != null) {
        q.setFilter(cf.getDatastoreFilter());
    }
    // add sort orders
    if (queryDto.getSortedPropertyName() != null) {
        q.addSort(queryDto.getSortedPropertyName(), queryDto.isSortAscending() ? SortDirection.ASCENDING : SortDirection.DESCENDING);
    }
    // add limit
    FetchOptions fo;
    if (queryDto.getLimit() != null && queryDto.getLimit() > 0) {
        fo = FetchOptions.Builder.withLimit(queryDto.getLimit());
    } else {
        fo = FetchOptions.Builder.withDefaults();
    }
    // execute the query
    List<Entity> results = datastore.prepare(q).asList(fo);
    // get entities from the keys
    List<Key> keyList = new LinkedList<Key>();
    for (Entity e : results) {
        keyList.add(e.getKey());
    }
    Map<String, Entity> resultEntities = CrudOperations.getInstance().getAllEntitiesByKeyList(keyList);
    // convert the Entities to CbDtos
    EntityListDto cdl = new EntityListDto();
    for (Entity keyOnlyEntity : results) {
        Entity e = resultEntities.get(keyOnlyEntity.getKey().getName());
        cdl.getEntries().add(EntityDto.createFromEntity(e));
    }
    return cdl;
}

64. CrudOperations#saveAll()

Project: solutions-mobile-backend-starter-java
File: CrudOperations.java
/**
   * Saves all CloudEntities.
   * 
   * @param cdl
   *          {@link EntityListDto} that contains the CloudEntities.
   * @param user
   *          {@link User} of the caller.
   * @return {@link EntityListDto} that contains the saved CloudEntities with
   *         auto-generated properties.
   * @throws UnauthorizedException
   */
public EntityListDto saveAll(EntityListDto cdl, User user) throws UnauthorizedException {
    // find and update existing entities
    Map<String, Entity> existingEntities = findAndUpdateExistingEntities(cdl, user);
    // create new entities
    Set<Entity> newEntities = createNewEntities(cdl, user, existingEntities);
    // apply changes to Datastore
    Set<Entity> allEntities = new HashSet<Entity>();
    allEntities.addAll(newEntities);
    allEntities.addAll(existingEntities.values());
    datastore.put(allEntities);
    // update Memcache and ProsSearch
    Map<String, Entity> allEntitiesMap = new HashMap<String, Entity>();
    for (Entity e : allEntities) {
        // if it's a "private" entity, skip memcache and prossearch
        if (e.getKind().startsWith(SecurityChecker.KIND_PREFIX_PRIVATE)) {
            continue;
        }
        // apply changes to Memcache
        allEntitiesMap.put(e.getKey().getName(), e);
    }
    memcache.putAll(allEntitiesMap);
    // match with subscribers (date props converted to double)
    for (Entity e : allEntities) {
        convertDatePropertyToEpochTime(e, EntityDto.PROP_CREATED_AT);
        convertDatePropertyToEpochTime(e, EntityDto.PROP_UPDATED_AT);
        prosSearch.match(e, QueryOperations.PROS_SEARCH_DEFAULT_TOPIC);
    }
    // return a list of the updated EntityDto
    return cdl;
}

65. Worker#recordTaskProcessed()

Project: solutions-mobile-backend-starter-java
File: Worker.java
private void recordTaskProcessed(TaskHandle task) {
    cache.put(task.getName(), 1, Expiration.byDeltaSeconds(60 * 60 * 2));
    Entity entity = new Entity(PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND, task.getName());
    entity.setProperty("processedAt", new Date());
    dataStore.put(entity);
}

66. BackendConfigManager#setLastSubscriptionDeleteAllTime()

Project: solutions-mobile-backend-starter-java
File: BackendConfigManager.java
/**
   * Sets the last subscription delete time to current time.
   */
public void setLastSubscriptionDeleteAllTime(Date time) {
    Entity config = getConfiguration();
    config.setProperty(LAST_SUBSCRIPTION_DELETE_TIMESTAMP, time);
    this.datastoreService.put(config);
    this.memcache.put(getMemKeyForConfigEntity(getKey()), config);
}

67. EvilMemcacheBugTests#testRawCaching()

Project: objectify
File: EvilMemcacheBugTests.java
/** */
@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();
    }
}

68. AlsoLoadTests#testAlsoLoadMethods()

Project: objectify
File: AlsoLoadTests.java
/** */
@Test
public void testAlsoLoadMethods() throws Exception {
    Entity ent = new Entity(Key.getKind(HasAlsoLoads.class));
    ent.setProperty("weirdStuff", "5");
    ds().put(ent);
    Key<HasAlsoLoads> key = Key.create(ent.getKey());
    HasAlsoLoads fetched = ofy().load().key(key).now();
    assert fetched.getWeird() == 5;
}

69. QueryOperations#executeQuery()

Project: io2014-codelabs
File: QueryOperations.java
private EntityListDto executeQuery(QueryDto queryDto, User user) {
    // check if kindName is not the config kinds
    SecurityChecker.getInstance().checkIfKindNameAccessible(queryDto.getKindName());
    // create Query
    Query q = SecurityChecker.getInstance().createKindQueryWithNamespace(queryDto.getKindName(), user);
    q.setKeysOnly();
    // set filters
    FilterDto cf = queryDto.getFilterDto();
    if (cf != null) {
        q.setFilter(cf.getDatastoreFilter());
    }
    // add sort orders
    if (queryDto.getSortedPropertyName() != null) {
        q.addSort(queryDto.getSortedPropertyName(), queryDto.isSortAscending() ? SortDirection.ASCENDING : SortDirection.DESCENDING);
    }
    // add limit
    FetchOptions fo;
    if (queryDto.getLimit() != null && queryDto.getLimit() > 0) {
        fo = FetchOptions.Builder.withLimit(queryDto.getLimit());
    } else {
        fo = FetchOptions.Builder.withDefaults();
    }
    // execute the query
    List<Entity> results = datastore.prepare(q).asList(fo);
    // get entities from the keys
    List<Key> keyList = new LinkedList<Key>();
    for (Entity e : results) {
        keyList.add(e.getKey());
    }
    Map<String, Entity> resultEntities = CrudOperations.getInstance().getAllEntitiesByKeyList(keyList);
    // convert the Entities to CbDtos
    EntityListDto cdl = new EntityListDto();
    for (Entity keyOnlyEntity : results) {
        Entity e = resultEntities.get(keyOnlyEntity.getKey().getName());
        cdl.getEntries().add(EntityDto.createFromEntity(e));
    }
    return cdl;
}

70. CrudOperations#saveAll()

Project: io2014-codelabs
File: CrudOperations.java
/**
   * Saves all CloudEntities.
   * 
   * @param cdl
   *          {@link com.google.cloud.backend.beans.EntityListDto} that contains the CloudEntities.
   * @param user
   *          {@link com.google.appengine.api.users.User} of the caller.
   * @return {@link com.google.cloud.backend.beans.EntityListDto} that contains the saved CloudEntities with
   *         auto-generated properties.
   * @throws com.google.api.server.spi.response.UnauthorizedException
   */
public EntityListDto saveAll(EntityListDto cdl, User user) throws UnauthorizedException {
    // find and update existing entities
    Map<String, Entity> existingEntities = findAndUpdateExistingEntities(cdl, user);
    // create new entities
    Set<Entity> newEntities = createNewEntities(cdl, user, existingEntities);
    // apply changes to Datastore
    Set<Entity> allEntities = new HashSet<Entity>();
    allEntities.addAll(newEntities);
    allEntities.addAll(existingEntities.values());
    datastore.put(allEntities);
    // update Memcache and ProsSearch
    Map<String, Entity> allEntitiesMap = new HashMap<String, Entity>();
    for (Entity e : allEntities) {
        // if it's a "private" entity, skip memcache and prossearch
        if (e.getKind().startsWith(SecurityChecker.KIND_PREFIX_PRIVATE)) {
            continue;
        }
        // apply changes to Memcache
        allEntitiesMap.put(e.getKey().getName(), e);
    }
    memcache.putAll(allEntitiesMap);
    // match with subscribers (date props converted to double)
    for (Entity e : allEntities) {
        convertDatePropertyToEpochTime(e, EntityDto.PROP_CREATED_AT);
        convertDatePropertyToEpochTime(e, EntityDto.PROP_UPDATED_AT);
        prosSearch.match(e, QueryOperations.PROS_SEARCH_DEFAULT_TOPIC);
    }
    // return a list of the updated EntityDto
    return cdl;
}

71. Worker#recordTaskProcessed()

Project: io2014-codelabs
File: Worker.java
private void recordTaskProcessed(TaskHandle task) {
    cache.put(task.getName(), 1, Expiration.byDeltaSeconds(60 * 60 * 2));
    Entity entity = new Entity(PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND, task.getName());
    entity.setProperty("processedAt", new Date());
    dataStore.put(entity);
}

72. BackendConfigManager#setLastSubscriptionDeleteAllTime()

Project: io2014-codelabs
File: BackendConfigManager.java
/**
   * Sets the last subscription delete time to current time.
   */
public void setLastSubscriptionDeleteAllTime(Date time) {
    Entity config = getConfiguration();
    config.setProperty(LAST_SUBSCRIPTION_DELETE_TIMESTAMP, time);
    this.datastoreService.put(config);
    this.memcache.put(getMemKeyForConfigEntity(getKey()), config);
}

73. SecurityChecker#getUserId()

Project: solutions-mobile-backend-starter-java
File: SecurityChecker.java
private String getUserId(User u) {
    // check if User is available
    if (u == null) {
        return USER_ID_FOR_ANONYMOUS;
    }
    // check if valid email is available
    String email = u.getEmail();
    if (email == null || email.trim().length() == 0) {
        throw new IllegalArgumentException("Illegal email: " + email);
    }
    // try to find it on local cache
    String memKey = USER_ID_PREFIX + email;
    String id = userIdCache.get(memKey);
    if (id != null) {
        return id;
    }
    // try to find it on memcache
    id = (String) memcache.get(memKey);
    if (id != null) {
        userIdCache.put(memKey, id);
        return id;
    }
    // create a key to find the user on Datastore
    String origNamespace = NamespaceManager.get();
    NamespaceManager.set(NAMESPACE_DEFAULT);
    Key key = KeyFactory.createKey(KIND_NAME_USERS, email);
    NamespaceManager.set(origNamespace);
    // try to find it on Datastore
    Entity e;
    try {
        e = datastore.get(key);
        id = (String) e.getProperty(USERS_PROP_USERID);
    } catch (EntityNotFoundException ex) {
        e = new Entity(key);
        id = USER_ID_PREFIX + UUID.randomUUID().toString();
        e.setProperty(USERS_PROP_USERID, id);
        datastore.put(e);
    }
    // put the user on memcache and local cache
    userIdCache.put(memKey, id);
    memcache.put(memKey, id);
    return id;
}

74. DeviceSubscription#create()

Project: solutions-mobile-backend-starter-java
File: DeviceSubscription.java
/**
   * Creates an entity to persist a subscriptionID subscribed by a specific device.
   *
   * @param deviceType device type according to platform
   * @param deviceId unique device identifier
   * @param subscriptionId subscription identifier subscribed by this specific device
   * @return a datastore entity
   */
public Entity create(SubscriptionUtility.MobileType deviceType, String deviceId, String subscriptionId) {
    if (StringUtility.isNullOrEmpty(deviceId) || StringUtility.isNullOrEmpty(subscriptionId)) {
        return null;
    }
    Key key;
    String newDeviceId = SubscriptionUtility.extractRegId(deviceId);
    Entity deviceSubscription = get(newDeviceId);
    // Subscriptions is a "set" instead of a "list" to ensure uniqueness of each subscriptionId
    // for a device
    Set<String> subscriptions = new HashSet<String>();
    if (deviceSubscription == null) {
        // Create a brand new one
        key = getKey(newDeviceId);
        deviceSubscription = new Entity(key);
        deviceSubscription.setProperty(PROPERTY_ID, newDeviceId);
        deviceSubscription.setProperty(PROPERTY_DEVICE_TYPE, deviceType.toString());
    } else {
        key = deviceSubscription.getKey();
        // Update the existing subscription list
        String ids = (String) deviceSubscription.getProperty(PROPERTY_SUBSCRIPTION_IDS);
        if (!StringUtility.isNullOrEmpty(ids)) {
            subscriptions = this.gson.fromJson(ids, setType);
        }
    }
    // in the set, we don't save this duplicated value into the entity.
    if (subscriptions.add(subscriptionId)) {
        deviceSubscription.setProperty(PROPERTY_SUBSCRIPTION_IDS, this.gson.toJson(subscriptions));
        Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        deviceSubscription.setProperty(PROPERTY_TIMESTAMP, time.getTime());
        this.datastoreService.put(deviceSubscription);
        this.memcacheService.put(key, deviceSubscription);
    }
    return deviceSubscription;
}

75. CrudOperations#getEntity()

Project: solutions-mobile-backend-starter-java
File: CrudOperations.java
protected EntityDto getEntity(String kindName, String id, User user) throws NotFoundException {
    // get entity
    Entity e = getEntityById(kindName, id, user);
    // create EntityDto from the Entity
    return EntityDto.createFromEntity(e);
}

76. BackendConfigManager#getLastSubscriptionDeleteAllTime()

Project: solutions-mobile-backend-starter-java
File: BackendConfigManager.java
/**
   * Gets the last subscription deletion time.
   * @return The last subscription deletion time.  If it's null, then no subscription delete all
   *         has been issued yet.
   */
public Date getLastSubscriptionDeleteAllTime() {
    Entity config = getConfiguration();
    return (Date) config.getProperty(LAST_SUBSCRIPTION_DELETE_TIMESTAMP);
}

77. BackendConfigManager#getConfiguration()

Project: solutions-mobile-backend-starter-java
File: BackendConfigManager.java
/**
   * Returns the current configuration of the backend.
   * 
   * @result Entity that represents the current configurations of the backend.
   */
protected Entity getConfiguration() {
    // check memcache
    Key key = getKey();
    Entity config = (Entity) memcache.get(getMemKeyForConfigEntity(key));
    if (config != null) {
        return config;
    }
    // get from datastore
    try {
        config = datastoreService.get(key);
    } catch (EntityNotFoundException e) {
        config = new Entity(key);
        config.setProperty(AUTHENTICATION_MODE, AuthMode.LOCKED.name());
        config.setProperty(PUSH_ENABLED, false);
        config.setProperty(LAST_SUBSCRIPTION_DELETE_TIMESTAMP, null);
        SecureRandom rnd = new SecureRandom();
        String secret = new BigInteger(256, rnd).toString();
        config.setProperty(PER_APP_SECRET_KEY, secret);
        datastoreService.put(config);
    }
    // put the config entity to memcache and return it
    memcache.put(getMemKeyForConfigEntity(key), config);
    return config;
}

78. IgnoreTests#testTransientFields()

Project: objectify
File: IgnoreTests.java
/** */
@Test
public void testTransientFields() throws Exception {
    fact().register(HasTransients.class);
    HasTransients o = new HasTransients();
    o.name = "saved";
    o.transientKeyword = 42;
    o.transientAnnotation = 43;
    Key<HasTransients> k = ofy().save().entity(o).now();
    // reset session
    ofy().clear();
    o = ofy().load().key(k).now();
    assert "saved".equals(o.name);
    assert o.transientKeyword == 42;
    // would fail without session clear
    assert o.transientAnnotation == 0;
    Entity e = ds().get(null, k.getRaw());
    assert e.getProperties().size() == 2;
    assert e.getProperty("name") != null;
    assert e.getProperty("name").equals("saved");
    assert e.getProperty("transientKeyword") != null;
    assert ((Number) e.getProperty("transientKeyword")).intValue() == 42;
}

79. KeysOnlyIterator#next()

Project: objectify
File: KeysOnlyIterator.java
@Override
public Key<T> next() {
    Entity ent = source.next();
    loaded(ent);
    return Key.create(ent.getKey());
}

80. CachingDatastoreService#get()

Project: objectify
File: CachingDatastoreService.java
/* (non-Javadoc)
	 * @see com.google.appengine.api.datastore.DatastoreService#get(com.google.appengine.api.datastore.Transaction, com.google.appengine.api.datastore.Key)
	 */
@Override
public Entity get(Transaction txn, Key key) throws EntityNotFoundException {
    // This one is a little tricky because of the declared exception
    Map<Key, Entity> result = this.get(txn, Collections.singleton(key));
    Entity ent = result.get(key);
    if (ent == null)
        throw new EntityNotFoundException(key);
    else
        return ent;
}

81. CachingAsyncDatastoreService#put()

Project: objectify
File: CachingAsyncDatastoreService.java
/* (non-Javadoc)
	 * @see com.google.appengine.api.datastore.AsyncDatastoreService#put(com.google.appengine.api.datastore.Transaction, java.lang.Iterable)
	 */
@Override
public Future<List<Key>> put(final Transaction txn, final Iterable<Entity> entities) {
    // There is one weird case we have to watch out for.  When you put() entities without
    // a key, the backend autogenerates the key for you.  But the put() might throw an
    // exception (eg timeout) even though it succeeded in the backend.  Thus we wrote
    // an entity in the datastore but we don't know what the key was, so we can't empty
    // out any negative cache entry that might exist.
    // The solution to this is that we need to allocate ids ourself before put()ing the entity.
    // Unfortunately there is no Entity.setKey() method or Key.setId() method, so we can't do this
    // The best we can do is watch out for when there is a potential problem and warn the
    // developer in the logs.
    final List<Key> inputKeys = new ArrayList<>();
    boolean foundAutoGenKeys = false;
    for (Entity ent : entities) if (ent.getKey() != null)
        inputKeys.add(ent.getKey());
    else
        foundAutoGenKeys = true;
    final boolean hasAutoGenKeys = foundAutoGenKeys;
    // Always trigger, even on failure - the delete might have succeeded even though a timeout
    // exception was thrown.  We will always be safe emptying the key from the cache.
    Future<List<Key>> future = new TriggerFuture<List<Key>>(this.rawAsync.put(txn, entities)) {

        @Override
        protected void trigger() {
            // This is complicated by the fact that some entities may have been put() without keys,
            // so they will have been autogenerated in the backend.  If a timeout error is thrown,
            // it's possible the commit succeeded but we won't know what the key was.  If there was
            // already a negative cache entry for this, we have no way of knowing to clear it.
            // This must be pretty rare:  A timeout on a autogenerated key when there was already a
            // negative cache entry.  We can detect when this is a potential case and log a warning.
            // The only real solution to this is to allocate ids in advance.  Which maybe we should do.
            List<Key> keys;
            try {
                keys = this.raw.get();
            } catch (Exception ex) {
                keys = inputKeys;
                if (hasAutoGenKeys)
                    log.log(Level.WARNING, "A put() for an Entity with an autogenerated key threw an exception. Because the write" + " might have succeeded and there might be a negative cache entry for the (generated) id, there" + " is a small potential for cache to be incorrect.");
            }
            if (txn != null) {
                for (Key key : keys) ((CachingTransaction) txn).deferEmptyFromCache(key);
            } else {
                memcache.empty(keys);
            }
        }
    };
    if (txn instanceof CachingTransaction)
        ((CachingTransaction) txn).enlist(future);
    return future;
}

82. DatastoreDocumentServiceTestCase#setUp()

Project: nuvem
File: DatastoreDocumentServiceTestCase.java
@Before
public void setUp() {
    super.setUp();
    key = KeyFactory.createKey(Customer.class.getName(), customer.getId());
    customerEntity = new Entity(key);
    customerEntity.setProperty("id", customer.getId());
    customerEntity.setProperty("name", customer.getName());
    customerEntity.setProperty("creditCard", customer.getCreditCard());
    documentService.init();
}

83. DatastoreDocumentServiceImpl#get()

Project: nuvem
File: DatastoreDocumentServiceImpl.java
public Entity get(Key key) throws NotFoundException {
    Entity entity = null;
    try {
        entity = googleDataStoreService.get(key);
    } catch (EntityNotFoundException nf) {
        throw new NotFoundException(nf);
    }
    return entity;
}

84. ScoreDAO#createScoreRecord()

Project: LeaderboardServer
File: ScoreDAO.java
/**
	 * Method to create a record from a json string and store the record to the datastore
	 * @param jsonString
	 * @param countryCode
	 * @return
	 */
public Entity createScoreRecord(String jsonString, String countryCode) {
    Entity record = null;
    log.info("Creating gamescore record");
    log.info("Record:" + jsonString);
    //if country code is null set it to 'n/a'
    if (countryCode == null) {
        countryCode = Constants.NOTAVAILABLE;
    }
    //parse json string
    JsonParser parser = new JsonParser();
    JsonObject obj = (JsonObject) parser.parse(jsonString);
    //read json object properties
    JsonElement score = obj.get(Constants.SCORE);
    JsonElement username = obj.get(Constants.USERNAME);
    JsonElement platform = obj.get(Constants.PLATFORM);
    if (!Tools.isEmptyOrNull(score.getAsString()) && !Tools.isEmptyOrNull(username.getAsString()) && !Tools.isEmptyOrNull(platform.getAsString())) {
        //create and populate record
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        record = new Entity(Constants.RECORD);
        record.setProperty(Constants.SCORE, new Double(score.getAsString()));
        record.setProperty(Constants.USERNAME, username.getAsString());
        record.setProperty(Constants.PLATFORM, platform.getAsString());
        record.setProperty(Constants.DATE, date);
        record.setProperty(Constants.COUNTRY_CODE, countryCode);
        /*
	         *Google app engine datastore does not allow queries with inequality comparison that are not sorted
	         *with the comparison property. So, we store the date info we want in order to only use simple equality comparison in
	         *order to sort just with score
	         */
        record.setProperty(Constants.YEAR, calendar.get(Calendar.YEAR));
        record.setProperty(Constants.MONTH, calendar.get(Calendar.MONTH));
        record.setProperty(Constants.WEEK_OF_THE_YEAR, calendar.get(Calendar.WEEK_OF_YEAR));
        record.setProperty(Constants.DAY_OF_THE_YEAR, calendar.get(Calendar.DAY_OF_YEAR));
        //persist record
        log.info("Persisting record " + score.getAsString() + " " + username.getAsString());
        datastore.put(record);
    } else {
        log.warning("Insufficient data to create gamescore record");
    }
    return record;
}

85. LogDataServlet#doGet()

Project: iosched
File: LogDataServlet.java
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("application/json");
    UpdateRunLogger logger = new UpdateRunLogger();
    JsonObject response = new JsonObject();
    int limitElements = 10;
    if (req.getParameter("limit") != null) {
        limitElements = Integer.parseInt(req.getParameter("limit"));
    }
    List<Entity> lastRunsEntities = logger.getMostRecentRuns(limitElements);
    JsonArray lastRuns = new JsonArray();
    for (Entity run : lastRunsEntities) {
        JsonObject obj = new JsonObject();
        JsonObject timings = new JsonObject();
        TreeMap<String, Object> sortedMap = new TreeMap<String, Object>(run.getProperties());
        for (Entry<String, Object> property : sortedMap.entrySet()) {
            Object value = property.getValue();
            String key = property.getKey();
            if (key.startsWith("time_")) {
                timings.add(key.substring("time_".length()), new JsonPrimitive((Number) value));
            } else {
                JsonPrimitive converted = null;
                if (value instanceof ShortBlob) {
                    converted = new JsonPrimitive(bytesToHex(((ShortBlob) value).getBytes()));
                } else if (value instanceof String) {
                    converted = new JsonPrimitive((String) value);
                } else if (value instanceof Number) {
                    converted = new JsonPrimitive((Number) value);
                } else if (value instanceof Boolean) {
                    converted = new JsonPrimitive((Boolean) value);
                } else if (value instanceof Character) {
                    converted = new JsonPrimitive((Character) value);
                } else if (value instanceof Date) {
                    converted = new JsonPrimitive(DateFormat.getDateTimeInstance().format((Date) value));
                }
                if (converted != null) {
                    obj.add(key, converted);
                }
            }
        }
        obj.add("timings", timings);
        lastRuns.add(obj);
    }
    response.add("lastruns", lastRuns);
    CloudFileManager cloudManager = new CloudFileManager();
    response.add("bucket", new JsonPrimitive(cloudManager.getBucketName()));
    response.add("productionManifest", new JsonPrimitive(cloudManager.getProductionManifestURL()));
    response.add("stagingManifest", new JsonPrimitive(cloudManager.getStagingManifestURL()));
    new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(response, resp.getWriter());
}

86. SecurityChecker#getUserId()

Project: io2014-codelabs
File: SecurityChecker.java
private String getUserId(User u) {
    // check if User is available
    if (u == null) {
        return USER_ID_FOR_ANONYMOUS;
    }
    // check if valid email is available
    String email = u.getEmail();
    if (email == null || email.trim().length() == 0) {
        throw new IllegalArgumentException("Illegal email: " + email);
    }
    // try to find it on local cache
    String memKey = USER_ID_PREFIX + email;
    String id = userIdCache.get(memKey);
    if (id != null) {
        return id;
    }
    // try to find it on memcache
    id = (String) memcache.get(memKey);
    if (id != null) {
        userIdCache.put(memKey, id);
        return id;
    }
    // create a key to find the user on Datastore
    String origNamespace = NamespaceManager.get();
    NamespaceManager.set(NAMESPACE_DEFAULT);
    Key key = KeyFactory.createKey(KIND_NAME_USERS, email);
    NamespaceManager.set(origNamespace);
    // try to find it on Datastore
    Entity e;
    try {
        e = datastore.get(key);
        id = (String) e.getProperty(USERS_PROP_USERID);
    } catch (EntityNotFoundException ex) {
        e = new Entity(key);
        id = USER_ID_PREFIX + UUID.randomUUID().toString();
        e.setProperty(USERS_PROP_USERID, id);
        datastore.put(e);
    }
    // put the user on memcache and local cache
    userIdCache.put(memKey, id);
    memcache.put(memKey, id);
    return id;
}

87. DeviceSubscription#create()

Project: io2014-codelabs
File: DeviceSubscription.java
/**
   * Creates an entity to persist a subscriptionID subscribed by a specific device.
   *
   * @param deviceType device type according to platform
   * @param deviceId unique device identifier
   * @param subscriptionId subscription identifier subscribed by this specific device
   * @return a datastore entity
   */
public Entity create(SubscriptionUtility.MobileType deviceType, String deviceId, String subscriptionId) {
    if (StringUtility.isNullOrEmpty(deviceId) || StringUtility.isNullOrEmpty(subscriptionId)) {
        return null;
    }
    Key key;
    String newDeviceId = SubscriptionUtility.extractRegId(deviceId);
    Entity deviceSubscription = get(newDeviceId);
    // Subscriptions is a "set" instead of a "list" to ensure uniqueness of each subscriptionId
    // for a device
    Set<String> subscriptions = new HashSet<String>();
    if (deviceSubscription == null) {
        // Create a brand new one
        key = getKey(newDeviceId);
        deviceSubscription = new Entity(key);
        deviceSubscription.setProperty(PROPERTY_ID, newDeviceId);
        deviceSubscription.setProperty(PROPERTY_DEVICE_TYPE, deviceType.toString());
    } else {
        key = deviceSubscription.getKey();
        // Update the existing subscription list
        String ids = (String) deviceSubscription.getProperty(PROPERTY_SUBSCRIPTION_IDS);
        if (!StringUtility.isNullOrEmpty(ids)) {
            subscriptions = this.gson.fromJson(ids, setType);
        }
    }
    // in the set, we don't save this duplicated value into the entity.
    if (subscriptions.add(subscriptionId)) {
        deviceSubscription.setProperty(PROPERTY_SUBSCRIPTION_IDS, this.gson.toJson(subscriptions));
        Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        deviceSubscription.setProperty(PROPERTY_TIMESTAMP, time.getTime());
        this.datastoreService.put(deviceSubscription);
        this.memcacheService.put(key, deviceSubscription);
    }
    return deviceSubscription;
}

88. CrudOperations#getEntity()

Project: io2014-codelabs
File: CrudOperations.java
protected EntityDto getEntity(String kindName, String id, User user) throws NotFoundException {
    // get entity
    Entity e = getEntityById(kindName, id, user);
    // create EntityDto from the Entity
    return EntityDto.createFromEntity(e);
}

89. BackendConfigManager#getLastSubscriptionDeleteAllTime()

Project: io2014-codelabs
File: BackendConfigManager.java
/**
   * Gets the last subscription deletion time.
   * @return The last subscription deletion time.  If it's null, then no subscription delete all
   *         has been issued yet.
   */
public Date getLastSubscriptionDeleteAllTime() {
    Entity config = getConfiguration();
    return (Date) config.getProperty(LAST_SUBSCRIPTION_DELETE_TIMESTAMP);
}

90. BackendConfigManager#getConfiguration()

Project: io2014-codelabs
File: BackendConfigManager.java
/**
   * Returns the current configuration of the backend.
   * 
   * @result Entity that represents the current configurations of the backend.
   */
protected Entity getConfiguration() {
    // check memcache
    Key key = getKey();
    Entity config = (Entity) memcache.get(getMemKeyForConfigEntity(key));
    if (config != null) {
        return config;
    }
    // get from datastore
    try {
        config = datastoreService.get(key);
    } catch (EntityNotFoundException e) {
        config = new Entity(key);
        config.setProperty(AUTHENTICATION_MODE, AuthMode.LOCKED.name());
        config.setProperty(PUSH_ENABLED, false);
        config.setProperty(LAST_SUBSCRIPTION_DELETE_TIMESTAMP, null);
        SecureRandom rnd = new SecureRandom();
        String secret = new BigInteger(256, rnd).toString();
        config.setProperty(PER_APP_SECRET_KEY, secret);
        datastoreService.put(config);
    }
    // put the config entity to memcache and return it
    memcache.put(getMemKeyForConfigEntity(key), config);
    return config;
}

91. AppEngineCredentialStore#migrateTo()

Project: google-oauth-java-client
File: AppEngineCredentialStore.java
/**
   * 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);
    }
}