Refine search
@Override public void run(Transaction tx, Key userKey, String content) { Entity user = tx.get(userKey); if (user == null) { System.out.println("Adding a new user."); user = Entity.newBuilder(userKey).set("count", 1).build(); tx.add(user); } else { user = Entity.newBuilder(user).set("count", user.getLong("count") + 1L).build(); tx.update(user); } IncompleteKey commentKey = IncompleteKey.newBuilder(userKey, COMMENT_KIND).build(); FullEntity<IncompleteKey> comment = FullEntity.newBuilder(commentKey) .set("content", content) .set("timestamp", Timestamp.now()) .build(); tx.addWithDeferredIdAllocation(comment); System.out.printf("Adding a comment to user '%s'.%n", userKey.getName()); }
for (FullEntity<?> entity : entities) { Entity completeEntity = null; if (entity.getKey() instanceof Key) { completeEntity = Entity.convert((FullEntity<Key>) entity); if (completeEntities.put(completeEntity.getKey(), completeEntity) != null) { throw DatastoreException.throwInvalidRequest( "Duplicate entity with the key %s", entity.getKey()); Preconditions.checkArgument(entity.hasKey(), "Entity %s is missing a key", entity); com.google.datastore.v1.Mutation.newBuilder().setInsert(entity.toPb()).build()); ImmutableList.Builder<Entity> responseBuilder = ImmutableList.builder(); for (FullEntity<?> entity : entities) { Entity completeEntity = completeEntities.get(entity.getKey()); if (completeEntity != null) { responseBuilder.add(completeEntity); } else { responseBuilder.add( Entity.newBuilder(Key.fromPb(mutationResults.next().getKey()), entity).build());
@Test public void testAddEntity() { List<Entity> keys = DATASTORE.fetch(ENTITY1.getKey(), ENTITY3.getKey()); assertEquals(ENTITY1, keys.get(0)); assertNull(keys.get(1)); assertEquals(2, keys.size()); try { DATASTORE.add(ENTITY1); fail("Expecting a failure"); } catch (DatastoreException expected) { // expected; } List<Entity> entities = DATASTORE.add(ENTITY3, PARTIAL_ENTITY1, PARTIAL_ENTITY2); assertEquals(ENTITY3, DATASTORE.get(ENTITY3.getKey())); assertEquals(ENTITY3, entities.get(0)); assertEquals(PARTIAL_ENTITY1.getNames(), entities.get(1).getNames()); assertEquals(PARTIAL_ENTITY1.getKey().getAncestors(), entities.get(1).getKey().getAncestors()); assertNotNull(DATASTORE.get(entities.get(1).getKey())); assertEquals(PARTIAL_ENTITY2.getNames(), entities.get(2).getNames()); assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entities.get(2).getKey().getAncestors()); assertNotNull(DATASTORE.get(entities.get(2).getKey())); for (Entity entity : entities) { DATASTORE.delete(entity.getKey()); } }
@Test public void testNoKey() throws Exception { FullEntity<IncompleteKey> entity = FullEntity.newBuilder().set("foo", "bar").build(); assertFalse(entity.hasKey()); assertNull(entity.getKey()); assertEquals("bar", entity.getString("foo")); entity = FullEntity.newBuilder((IncompleteKey) null).build(); assertFalse(entity.hasKey()); assertNull(entity.getKey()); }
@Test public void testFullEntity() throws Exception { assertTrue(COMPLETE_ENTITY1.hasKey()); assertEquals(KEY1, COMPLETE_ENTITY1.getKey()); assertEquals("bar", COMPLETE_ENTITY1.getString("foo")); assertTrue(COMPLETE_ENTITY2.hasKey()); assertEquals(KEY2, COMPLETE_ENTITY2.getKey()); assertEquals("bar", COMPLETE_ENTITY2.getString("foo")); }
@Test public void testNewBatch() { Batch batch = datastore.newBatch(); Entity entity1 = Entity.newBuilder(ENTITY1).clear().build(); Entity entity2 = Entity.newBuilder(ENTITY2).clear().setNull("bla").build(); Entity entity4 = Entity.newBuilder(KEY4).set("value", StringValue.of("value")).build(); Entity entity5 = Entity.newBuilder(KEY5).set("value", "value").build(); Entity entity6 = entities.get(1); assertSame(entity4, entities.get(0)); assertEquals(PARTIAL_ENTITY2.getProperties(), entity6.getProperties()); assertEquals(PARTIAL_ENTITY2.getKey().getProjectId(), entity6.getKey().getProjectId()); assertEquals(PARTIAL_ENTITY2.getKey().getNamespace(), entity6.getKey().getNamespace()); assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entity6.getKey().getAncestors()); assertEquals(PARTIAL_ENTITY2.getKey().getKind(), entity6.getKey().getKind()); assertEquals(PARTIAL_ENTITY2.getKey(), IncompleteKey.newBuilder(entity6.getKey()).build()); assertNotEquals(PARTIAL_ENTITY2.getKey().getPath(), entity6.getKey().getPath()); assertNotEquals(PARTIAL_ENTITY2.getKey(), entity6.getKey()); assertSame(entity5, entities.get(2)); batch.addWithDeferredIdAllocation(PARTIAL_ENTITY3); assertEquals(1, generatedKeys.size()); assertEquals( PARTIAL_ENTITY3.getProperties(), datastore.get(generatedKeys.get(0)).getProperties()); assertEquals(PARTIAL_ENTITY3.getKey(), IncompleteKey.newBuilder(generatedKeys.get(0)).build());
@Test public void testNewBatch() { Batch batch = DATASTORE.newBatch(); Entity entity1 = Entity.newBuilder(ENTITY1).clear().build(); Entity entity2 = Entity.newBuilder(ENTITY2).clear().setNull("bla").build(); Entity entity4 = Entity.newBuilder(KEY4).set("value", StringValue.of("value")).build(); Entity entity5 = Entity.newBuilder(KEY5).set("value", "value").build(); Entity entity6 = entities.get(1); assertSame(entity4, entities.get(0)); assertEquals(PARTIAL_ENTITY2.getNames(), entity6.getNames()); assertEquals(PARTIAL_ENTITY2.getKey().getProjectId(), entity6.getKey().getProjectId()); assertEquals(PARTIAL_ENTITY2.getKey().getNamespace(), entity6.getKey().getNamespace()); assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entity6.getKey().getAncestors()); assertEquals(PARTIAL_ENTITY2.getKey().getKind(), entity6.getKey().getKind()); assertEquals(PARTIAL_ENTITY2.getKey(), IncompleteKey.newBuilder(entity6.getKey()).build()); assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entity6.getKey().getAncestors()); assertNotEquals(PARTIAL_ENTITY2.getKey(), entity6.getKey()); assertSame(entity5, entities.get(2)); batch.addWithDeferredIdAllocation(PARTIAL_ENTITY3); List<Key> generatedKeys = response.getGeneratedKeys(); assertEquals(1, generatedKeys.size()); assertEquals(PARTIAL_ENTITY3.getNames(), DATASTORE.get(generatedKeys.get(0)).getNames()); assertEquals(PARTIAL_ENTITY3.getKey(), IncompleteKey.newBuilder(generatedKeys.get(0)).build());
Entity user = tx.get(userKey); if (user == null) { System.out.printf("User '%s' does not exist.%n", userKey.getName()); return; if (user.contains("contact")) { FullEntity<IncompleteKey> contact = user.getEntity("contact"); String email = contact.getString("email"); String phone = contact.getString("phone"); System.out.printf( "User '%s' email is '%s', phone is '%s'.%n", userKey.getName(), email, phone); System.out.printf("User '%s' has %d comment[s].%n", userKey.getName(), user.getLong("count")); int limit = 200; Map<Timestamp, String> sortedComments = new TreeMap<>();
@Test public void testAddEntity() { List<Entity> keys = datastore.fetch(ENTITY1.getKey(), ENTITY3.getKey()); assertEquals(ENTITY1, keys.get(0)); assertNull(keys.get(1)); assertEquals(2, keys.size()); try { datastore.add(ENTITY1); fail("Expecting a failure"); } catch (DatastoreException expected) { // expected; } List<Entity> entities = datastore.add(ENTITY3, PARTIAL_ENTITY1, PARTIAL_ENTITY2); assertEquals(ENTITY3, datastore.get(ENTITY3.getKey())); assertEquals(ENTITY3, entities.get(0)); assertEquals(PARTIAL_ENTITY1.getProperties(), entities.get(1).getProperties()); assertEquals(PARTIAL_ENTITY1.getKey().getAncestors(), entities.get(1).getKey().getAncestors()); assertNotNull(datastore.get(entities.get(1).getKey())); assertEquals(PARTIAL_ENTITY2.getProperties(), entities.get(2).getProperties()); assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entities.get(2).getKey().getAncestors()); assertNotNull(datastore.get(entities.get(2).getKey())); }
@Override public void run(Transaction tx, Key userKey, Contact contact) { Entity user = tx.get(userKey); if (user == null) { System.out.println("Adding a new user."); user = Entity.newBuilder(userKey).set("count", 0L).build(); tx.add(user); } FullEntity<IncompleteKey> contactEntity = FullEntity.newBuilder() .set("email", contact.email()) .set("phone", contact.phone()) .build(); tx.update(Entity.newBuilder(user).set("contact", contactEntity).build()); System.out.printf("Setting contact for user '%s'.%n", userKey.getName()); }
@SuppressWarnings("unchecked") @Override public final List<Entity> add(FullEntity<?>... entities) { validateActive(); List<IncompleteKey> incompleteKeys = Lists.newArrayListWithExpectedSize(entities.length); for (FullEntity<?> entity : entities) { IncompleteKey key = entity.getKey(); Preconditions.checkArgument(key != null, "Entity must have a key"); if (!(key instanceof Key)) { if (!incompleteKeys.isEmpty()) { IncompleteKey[] toAllocate = Iterables.toArray(incompleteKeys, IncompleteKey.class); allocated = getDatastore().allocateId(toAllocate).iterator(); } else { allocated = Collections.emptyIterator(); if (entity.getKey() instanceof Key) { addInternal((FullEntity<Key>) entity); answer.add(Entity.convert((FullEntity<Key>) entity)); } else { Entity entityWithAllocatedId = Entity.newBuilder(allocated.next(), entity).build(); addInternal(entityWithAllocatedId); answer.add(entityWithAllocatedId);
@SuppressWarnings("unchecked") @Override public final List<Entity> put(FullEntity<?>... entities) { validateActive(); List<IncompleteKey> incompleteKeys = Lists.newArrayListWithExpectedSize(entities.length); for (FullEntity<?> entity : entities) { IncompleteKey key = entity.getKey(); Preconditions.checkArgument(key != null, "Entity must have a key"); if (!(key instanceof Key)) { if (!incompleteKeys.isEmpty()) { IncompleteKey[] toAllocate = Iterables.toArray(incompleteKeys, IncompleteKey.class); allocated = getDatastore().allocateId(toAllocate).iterator(); } else { allocated = Collections.emptyIterator(); if (entity.getKey() instanceof Key) { putInternal((FullEntity<Key>) entity); answer.add(Entity.convert((FullEntity<Key>) entity)); } else { Entity entityWithAllocatedId = Entity.newBuilder(allocated.next(), entity).build(); putInternal(entityWithAllocatedId); answer.add(entityWithAllocatedId);
@Test public void testCopyFromIncompleteEntity() throws Exception { Entity.Builder builder = Entity.newBuilder(KEY2, INCOMPLETE_ENTITY); Entity entity = builder.build(); assertNotEquals(INCOMPLETE_ENTITY, entity); assertEquals(INCOMPLETE_ENTITY.getProperties(), entity.getProperties()); } }
@Test public void testCopyFrom() throws Exception { FullEntity.Builder<Key> builder1 = FullEntity.newBuilder(ENTITY); assertEquals(ENTITY, builder1.build()); builder1 = FullEntity.newBuilder(COMPLETE_ENTITY1); assertEquals(COMPLETE_ENTITY1, builder1.build()); FullEntity.Builder<IncompleteKey> builder2 = FullEntity.newBuilder(INCOMPLETE_ENTITY); assertEquals(INCOMPLETE_ENTITY, builder2.build()); } }
/** * Marshals the given entity and and returns the equivalent Entity needed for the underlying Cloud * Datastore API. * * @return A native entity that is equivalent to the POJO being marshalled. The returned value * could either be a FullEntity or Entity. */ private BaseEntity<?> marshal() { marshalKey(); if (key instanceof Key) { entityBuilder = Entity.newBuilder((Key) key); } else { entityBuilder = FullEntity.newBuilder(key); } marshalFields(); marshalAutoTimestampFields(); if (intent == Intent.UPDATE) { marshalVersionField(); } marshalEmbeddedFields(); return entityBuilder.build(); }
Entity(FullEntity<Key> from) { super(from); Preconditions.checkArgument(from.getKey() != null); }
FullEntity.Builder<IncompleteKey> probeEntityBuilder = Entity.newBuilder(); this.datastoreEntityConverter.write(probe, probeEntityBuilder); if (!example.getMatcher().isIgnoredPath(persistentProperty.getName())) { String fieldName = persistentProperty.getFieldName(); Value<?> value = probeEntity.getValue(fieldName); if (value instanceof NullValue && example.getMatcher().getNullHandler() != ExampleMatcher.NullHandler.INCLUDE) {
protected List<com.google.datastore.v1.Mutation> toMutationPbList() { List<com.google.datastore.v1.Mutation> mutationsPb = new ArrayList<>(); for (FullEntity<IncompleteKey> entity : toAddAutoId()) { mutationsPb.add( com.google.datastore.v1.Mutation.newBuilder().setInsert(entity.toPb()).build()); } for (FullEntity<Key> entity : toAdd().values()) { mutationsPb.add( com.google.datastore.v1.Mutation.newBuilder().setInsert(entity.toPb()).build()); } for (FullEntity<Key> entity : toUpdate().values()) { mutationsPb.add( com.google.datastore.v1.Mutation.newBuilder().setUpdate(entity.toPb()).build()); } for (FullEntity<Key> entity : toPut().values()) { mutationsPb.add( com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build()); } for (Key key : toDelete()) { mutationsPb.add(com.google.datastore.v1.Mutation.newBuilder().setDelete(key.toPb()).build()); } return mutationsPb; }
@Override public Map<Object, Object> loadInto(final Value<FullEntity<?>> node, final LoadContext ctx, final Path path, Map<Object, Object> into) { // Make this work more like collections than atomic values if (node == null) throw new SkipException(); if (into == null) //noinspection unchecked into = (Map<Object, Object>)fact.constructMap(mapType); else into.clear(); for (final String name : node.get().getNames()) { final Object key = stringifier.fromString(name); final Value<?> nodeValue = node.get().getValue(name); @SuppressWarnings("unchecked") final Object value = componentTranslator.load((Value)nodeValue, ctx, path.extend(name)); into.put(key, value); } return into; }
@Override public P loadSafe(final Value<FullEntity<?>> container, final LoadContext ctx, final Path path) throws SkipException { // check if we need to redirect to a different translator final String containerDiscriminator = container.get().contains(DISCRIMINATOR_PROPERTY) ? container.get().getString(DISCRIMINATOR_PROPERTY) : null; // wow no Optional or nullable get if (!Objects.equals(discriminator, containerDiscriminator)) { final ClassTranslator<? extends P> translator = byDiscriminator.get(containerDiscriminator); if (translator == null) { throw new IllegalStateException("Datastore object has discriminator value '" + containerDiscriminator + "' but no relevant @Subclass is registered"); } else { // This fixes alsoLoad names in discriminators by changing the discriminator to what the // translator expects for loading that subclass. Otherwise we'll get the error above since the // translator discriminator and the container discriminator won't match. final StringValue discriminatorValue = StringValue.newBuilder(translator.getDiscriminator()).setExcludeFromIndexes(true).build(); final FullEntity<?> updatedEntity = FullEntity.newBuilder(container.get()).set(DISCRIMINATOR_PROPERTY, discriminatorValue).build(); return translator.load(EntityValue.of(updatedEntity), ctx, path); } } else { // This is a normal load if (log.isTraceEnabled()) log.trace(LogUtils.msg(path, "Instantiating a " + declaredClass.getName())); final P into = forge.construct(declaredClass); populator.load(container.get(), ctx, path, into); return into; } }