Java Code Examples for com.google.cloud.datastore.Entity#newBuilder()

The following examples show how to use com.google.cloud.datastore.Entity#newBuilder() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GoogleCloudUtils.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an Entity Builder for the given key and properties. Converts the objects to the proper
 * datastore values
 */
static Entity.Builder createEntityBuilder(Key key, Map<String, Object> data) throws IOException {
  Entity.Builder builder = Entity.newBuilder(key);

  for (Map.Entry<String, Object> entry : data.entrySet()) {
    if (entry.getValue() instanceof String) {
      builder.set(entry.getKey(), (String) entry.getValue()); // StringValue
    } else if (entry.getValue() instanceof Integer) {
      builder.set(entry.getKey(), (Integer) entry.getValue()); // LongValue
    } else if (entry.getValue() instanceof Double) {
      builder.set(entry.getKey(), (Double) entry.getValue()); // DoubleValue
    } else if (entry.getValue() instanceof Boolean) {
      builder.set(entry.getKey(), (Boolean) entry.getValue()); // BooleanValue
    } else if (entry.getValue() instanceof Timestamp) {
      builder.set(entry.getKey(), (Timestamp) entry.getValue()); // TimestampValue
    } else {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
        out.writeObject(entry.getValue());
      }
      builder.set(entry.getKey(), Blob.copyFrom(bos.toByteArray())); // BlobValue
    }
  }
  return builder;
}
 
Example 2
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of putting multiple entities. */
// [TARGET put(FullEntity...)]
// [VARIABLE "my_key_name1"]
// [VARIABLE "my_key_name2"]
public void batchPutEntities(String keyName1, String keyName2) {
  // [START batchPutEntities]
  Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
  Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
  entityBuilder1.set("propertyName", "value1");
  Entity entity1 = entityBuilder1.build();

  Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
  Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
  entityBuilder2.set("propertyName", "value2");
  Entity entity2 = entityBuilder2.build();

  datastore.put(entity1, entity2);
  // [END batchPutEntities]
}
 
Example 3
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of adding a single entity. */
// [TARGET add(FullEntity)]
// [VARIABLE "my_key_name"]
public void addSingleEntity(String keyName) {
  // [START addSingleEntity]
  Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
  Entity.Builder entityBuilder = Entity.newBuilder(key);
  entityBuilder.set("propertyName", "value");
  Entity entity = entityBuilder.build();
  try {
    datastore.add(entity);
  } catch (DatastoreException ex) {
    if ("ALREADY_EXISTS".equals(ex.getReason())) {
      // entity.getKey() already exists
    }
  }
  // [END addSingleEntity]
}
 
Example 4
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a value stored in the project's datastore.
 * @param sessionId Request from which the session is extracted.
 */
protected void deleteSessionVariables(String sessionId, String... varNames) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  try {
    Entity stateEntity = transaction.get(key);
    if (stateEntity != null) {
      Entity.Builder builder = Entity.newBuilder(stateEntity);
      StringBuilder delNames = new StringBuilder();
      for (String varName : varNames) {
        delNames.append(varName + " ");
        builder = builder.remove(varName);
      }
      datastore.update(builder.build());
    }
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 5
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of updating multiple entities. */
// [TARGET update(Entity...)]
// [VARIABLE "my_key_name_1"]
// [VARIABLE "my_key_name_2"]
public void batchUpdateEntities(String keyName1, String keyName2) {
  // [START batchUpdateEntities]
  Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
  Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
  entityBuilder1.set("propertyName", "updatedValue1");
  Entity entity1 = entityBuilder1.build();

  Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
  Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
  entityBuilder2.set("propertyName", "updatedValue2");
  Entity entity2 = entityBuilder2.build();

  datastore.update(entity1, entity2);
  // [END batchUpdateEntities]
}
 
Example 6
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of updating multiple entities. */
// [TARGET update(Entity...)]
// [VARIABLE "my_key_name1"]
// [VARIABLE "my_key_name2"]
public void multipleUpdateEntities(String keyName1, String keyName2) {
  Datastore datastore = transaction.getDatastore();
  // [START multipleUpdateEntities]
  Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
  Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
  entityBuilder1.set("propertyName", "value3");
  Entity entity1 = entityBuilder1.build();

  Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
  Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
  entityBuilder2.set("propertyName", "value4");
  Entity entity2 = entityBuilder2.build();

  transaction.update(entity1, entity2);
  transaction.commit();
  // [END multipleUpdateEntities]
}
 
Example 7
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of adding multiple entities. */
// [TARGET add(FullEntity...)]
// [VARIABLE "my_key_name1"]
// [VARIABLE "my_key_name2"]
public void multipleAddEntities(String keyName1, String keyName2) {
  Datastore datastore = transaction.getDatastore();
  // [START multipleAddEntities]
  Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
  Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
  entityBuilder1.set("propertyName", "value1");
  Entity entity1 = entityBuilder1.build();

  Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
  Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
  entityBuilder2.set("propertyName", "value2");
  Entity entity2 = entityBuilder2.build();

  transaction.add(entity1, entity2);
  transaction.commit();
  // [END multipleAddEntities]
}
 
Example 8
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of putting multiple entities. */
// [TARGET put(FullEntity...)]
// [VARIABLE "my_key_name1"]
// [VARIABLE "my_key_name2"]
public void multiplePutEntities(String keyName1, String keyName2) {
  Datastore datastore = transaction.getDatastore();
  // [START multiplePutEntities]
  Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
  Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
  entityBuilder1.set("propertyName", "value1");
  Entity entity1 = entityBuilder1.build();

  Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
  Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
  entityBuilder2.set("propertyName", "value2");
  Entity entity2 = entityBuilder2.build();

  transaction.put(entity1, entity2);
  transaction.commit();
  // [END multiplePutEntities]
}
 
Example 9
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a value stored in the project's datastore.
 *
 * @param sessionId Request from which the session is extracted.
 */
protected void deleteSessionVariables(String sessionId, String... varNames) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  try {
    Entity stateEntity = transaction.get(key);
    if (stateEntity != null) {
      Entity.Builder builder = Entity.newBuilder(stateEntity);
      StringBuilder delNames = new StringBuilder();
      for (String varName : varNames) {
        delNames.append(varName + " ");
        builder = builder.remove(varName);
      }
      datastore.update(builder.build());
    }
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 10
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example of adding a single entity. */
// [TARGET add(FullEntity)]
// [VARIABLE "my_key_name"]
public void addSingleEntity(String keyName) {
  Datastore datastore = transaction.getDatastore();
  // [START addSingleEntity]
  Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
  Entity.Builder entityBuilder = Entity.newBuilder(key);
  entityBuilder.set("propertyName", "value");
  Entity entity = entityBuilder.build();
  transaction.add(entity);
  transaction.commit();
  // [END addSingleEntity]
}
 
Example 11
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example of putting a single entity. */
// [TARGET put(FullEntity)]
// [VARIABLE "my_key_name"]
public void putSingleEntity(String keyName) {
  // [START putSingleEntity]
  Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
  Entity.Builder entityBuilder = Entity.newBuilder(key);
  entityBuilder.set("propertyName", "value");
  Entity entity = entityBuilder.build();
  datastore.put(entity);
  // [END putSingleEntity]
}
 
Example 12
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example of putting a single entity. */
// [TARGET put(FullEntity)]
// [VARIABLE "my_key_name"]
public void putSingleEntity(String keyName) {
  Datastore datastore = transaction.getDatastore();
  // [START putSingleEntity]
  Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
  Entity.Builder entityBuilder = Entity.newBuilder(key);
  entityBuilder.set("propertyName", "value");
  Entity entity = entityBuilder.build();
  transaction.put(entity);
  transaction.commit();
  // [END putSingleEntity]
}
 
Example 13
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the state value in each key-value pair in the project's datastore.
 *
 * @param sessionId Request from which to extract session.
 * @param varName   the name of the desired session variable
 * @param varValue  the value of the desired session variable
 */
protected void setSessionVariables(String sessionId, Map<String, String> setMap) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  dt.toString(dtf);
  try {
    Entity stateEntity = transaction.get(key);
    Entity.Builder seBuilder;
    if (stateEntity == null) {
      seBuilder = Entity.newBuilder(key);
    } else {
      seBuilder = Entity.newBuilder(stateEntity);
    }
    for (String varName : setMap.keySet()) {
      seBuilder.set(varName, setMap.get(varName));
    }
    transaction.put(seBuilder.set("lastModified", dt.toString(dtf)).build());
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 14
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the state value in each key-value pair in the project's datastore.
 *
 * @param sessionId Request from which to extract session.
 * @param varName   the name of the desired session variable
 * @param varValue  the value of the desired session variable
 */
protected void setSessionVariables(String sessionId, Map<String, String> setMap) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  dt.toString(dtf);
  try {
    Entity stateEntity = transaction.get(key);
    Entity.Builder seBuilder;
    if (stateEntity == null) {
      seBuilder = Entity.newBuilder(key);
    } else {
      seBuilder = Entity.newBuilder(stateEntity);
    }
    for (String varName : setMap.keySet()) {
      seBuilder.set(varName, setMap.get(varName));
    }
    transaction.put(seBuilder.set("lastModified", dt.toString(dtf)).build());
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 15
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the state value in each key-value pair in the project's datastore.
 * @param sessionId Request from which to extract session.
 * @param varName the name of the desired session variable
 * @param varValue the value of the desired session variable
 */
protected void setSessionVariables(String sessionId, Map<String, String> setMap) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  dt.toString(dtf);
  try {
    Entity stateEntity = transaction.get(key);
    Entity.Builder seBuilder;
    if (stateEntity == null) {
      seBuilder = Entity.newBuilder(key);
    } else {
      seBuilder = Entity.newBuilder(stateEntity);
    }
    for (String varName : setMap.keySet()) {
      seBuilder.set(varName, setMap.get(varName));
    }
    transaction.put(seBuilder.set("lastModified", dt.toString(dtf)).build());
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 16
Source File: ITDatastoreSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
private void addEntity(String keyName, String keyClass, String property, String value) {
  Key key = datastore.newKeyFactory().setKind(keyClass).newKey(keyName);
  Entity.Builder entityBuilder = Entity.newBuilder(key);
  entityBuilder.set(property, value);
  Entity entity = entityBuilder.build();
  datastore.put(entity);
}
 
Example 17
Source File: DatastoreTemplate.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private List<Entity> convertToEntityForSave(Object entity, Set<Key> persistedEntities, Key... ancestors) {
	if (ancestors != null) {
		for (Key ancestor : ancestors) {
			validateKey(entity, keyToPathElement(ancestor));
		}
	}
	Key key = getKey(entity, true, ancestors);
	Builder builder = Entity.newBuilder(key);
	List<Entity> entitiesToSave = new ArrayList<>();
	this.datastoreEntityConverter.write(entity, builder);
	entitiesToSave.addAll(getDescendantEntitiesForSave(entity, key, persistedEntities));
	entitiesToSave.addAll(getReferenceEntitiesForSave(entity, builder, persistedEntities));
	entitiesToSave.add(builder.build());
	return entitiesToSave;
}
 
Example 18
Source File: DatastoreTemplate.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
public <V> void writeMap(Key datastoreKey, Map<String, V> map) {
	Assert.notNull(datastoreKey, "A non-null Key is required.");
	Assert.notNull(map, "A non-null map is required.");

	Builder builder = Entity.newBuilder(datastoreKey);
	map.forEach(
			(key, value) ->
					builder.set(key, this.datastoreEntityConverter.getConversions().convertOnWriteSingle(value)));
	Entity entity = builder.build();
	getDatastoreReadWriter().put(entity);
}
 
Example 19
Source File: DefaultDatastoreEntityConverterTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
private Entity.Builder getEntityBuilder() {
	return Entity.newBuilder(this.datastore.newKeyFactory().setKind("aKind").newKey("1"));
}
 
Example 20
Source File: DatastoreTemplate.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
private <T> StructuredQuery exampleToQuery(Example<T> example, DatastoreQueryOptions queryOptions, boolean keyQuery) {
	validateExample(example);

	T probe = example.getProbe();
	FullEntity.Builder<IncompleteKey> probeEntityBuilder = Entity.newBuilder();
	this.datastoreEntityConverter.write(probe, probeEntityBuilder);

	FullEntity<IncompleteKey> probeEntity = probeEntityBuilder.build();
	DatastorePersistentEntity<?> persistentEntity =
			this.datastoreMappingContext.getPersistentEntity(example.getProbeType());

	StructuredQuery.Builder builder = keyQuery ? Query.newKeyQueryBuilder() : Query.newEntityQueryBuilder();
	builder.setKind(persistentEntity.kindName());

	ExampleMatcherAccessor matcherAccessor = new ExampleMatcherAccessor(example.getMatcher());
	matcherAccessor.getPropertySpecifiers();
	LinkedList<StructuredQuery.Filter> filters = new LinkedList<>();
	persistentEntity.doWithColumnBackedProperties((persistentProperty) -> {

		if (!example.getMatcher().isIgnoredPath(persistentProperty.getName())) {
			// ID properties are not stored as regular fields in Datastore.
			String fieldName = persistentProperty.getFieldName();
			Value<?> value;
			if (persistentProperty.isIdProperty()) {
				PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(probe);
				value = KeyValue.of(
						createKey(persistentEntity.kindName(), accessor.getProperty(persistentProperty)));
			}
			else {
				value = probeEntity.getValue(fieldName);
			}
			if (value instanceof NullValue
					&& example.getMatcher().getNullHandler() != ExampleMatcher.NullHandler.INCLUDE) {
				//skip null value
				return;
			}
			filters.add(StructuredQuery.PropertyFilter.eq(fieldName, value));
		}
	});


	if (!filters.isEmpty()) {
		builder.setFilter(
				StructuredQuery.CompositeFilter.and(filters.pop(), filters.toArray(new StructuredQuery.Filter[0])));
	}

	applyQueryOptions(builder, queryOptions, persistentEntity);
	return builder.build();
}