Java Code Examples for com.google.cloud.datastore.FullEntity#Builder

The following examples show how to use com.google.cloud.datastore.FullEntity#Builder . 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: TwoStepsConversions.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private EntityValue applyEntityValueBuilder(Object val, String kindName,
		Consumer<Builder> consumer, boolean createKey) {

	FullEntity.Builder<IncompleteKey> builder;
	if (!createKey) {
		builder = FullEntity.newBuilder();
	}
	else {
		/* The following does 3 sequential null checks. We only want an ID value if the object isn't null,
			has an ID property, and the ID property isn't null.
		* */
		Optional idProp = Optional.ofNullable(val)
				.map(v -> this.datastoreMappingContext.getPersistentEntity(v.getClass()))
				.map(datastorePersistentEntity -> datastorePersistentEntity.getIdProperty())
				.map(id -> this.datastoreMappingContext.getPersistentEntity(val.getClass())
						.getPropertyAccessor(val).getProperty(id));

		IncompleteKey key = idProp.isPresent() ? this.objectToKeyFactory.getKeyFromId(idProp.get(), kindName)
				: this.objectToKeyFactory.getIncompleteKey(kindName);
		builder = FullEntity.newBuilder(key);
	}
	consumer.accept(builder);
	return EntityValue.of(builder.build());
}
 
Example 2
Source File: DefaultDatastoreEntityConverter.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private Value setExcludeFromIndexes(Value convertedVal) {
	// ListValues must have its contents individually excluded instead.
	// the entire list must NOT be excluded or there will be an exception.
	// Same for maps and embedded entities which are stored as EntityValue.
	if (convertedVal.getClass().equals(EntityValue.class)) {
		FullEntity.Builder<IncompleteKey> builder = FullEntity.newBuilder();
		((EntityValue) convertedVal).get().getProperties()
						.forEach((key, value) -> builder.set(key, setExcludeFromIndexes(value)));
		return EntityValue.of(builder.build());
	}
	else if (convertedVal.getClass().equals(ListValue.class)) {
		return ListValue.of((List) ((ListValue) convertedVal).get().stream()
						.map(this::setExcludeFromIndexes).collect(Collectors.toList()));
	}
	else {
		return convertedVal.toBuilder().setExcludeFromIndexes(true).build();
	}
}
 
Example 3
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of adding multiple entities with deferred id allocation. */
// [TARGET addWithDeferredIdAllocation(FullEntity...)]
public List<Key> multipleAddEntitiesDeferredId() {
  Datastore datastore = transaction.getDatastore();
  // [START multipleAddEntitiesDeferredId]
  IncompleteKey key1 = datastore.newKeyFactory().setKind("MyKind").newKey();
  FullEntity.Builder entityBuilder1 = FullEntity.newBuilder(key1);
  entityBuilder1.set("propertyName", "value1");
  FullEntity entity1 = entityBuilder1.build();

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

  transaction.addWithDeferredIdAllocation(entity1, entity2);
  Response response = transaction.commit();
  // [END multipleAddEntitiesDeferredId]
  return response.getGeneratedKeys();
}
 
Example 4
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of putting multiple entities with deferred id allocation. */
// [TARGET putWithDeferredIdAllocation(FullEntity...)]
public List<Key> multiplePutEntitiesDeferredId() {
  Datastore datastore = transaction.getDatastore();
  // [START multiplePutEntitiesDeferredId]
  IncompleteKey key1 = datastore.newKeyFactory().setKind("MyKind").newKey();
  FullEntity.Builder entityBuilder1 = FullEntity.newBuilder(key1);
  entityBuilder1.set("propertyName", "value1");
  FullEntity entity1 = entityBuilder1.build();

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

  transaction.putWithDeferredIdAllocation(entity1, entity2);
  Response response = transaction.commit();
  // [END multiplePutEntitiesDeferredId]
  return response.getGeneratedKeys();
}
 
Example 5
Source File: MapMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public ValueBuilder<?, ?, ?> toDatastore(Object input) {
  if (input == null) {
    return NullValue.newBuilder();
  }
  Map<String, ?> map = (Map<String, ?>) input;
  FullEntity.Builder<IncompleteKey> entityBuilder = FullEntity.newBuilder();
  for (Map.Entry<String, ?> entry : map.entrySet()) {
    String key = entry.getKey();
    entityBuilder.set(key, valueMapper.toDatastore(entry.getValue()).build());
  }
  return EntityValue.newBuilder(entityBuilder.build());
}
 
Example 6
Source File: EmbeddedObjectMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public ValueBuilder<?, ?, ?> toDatastore(Object input) {
  if (input == null) {
    return NullValue.newBuilder();
  }
  try {
    FullEntity.Builder<IncompleteKey> entityBuilder = FullEntity.newBuilder();
    for (PropertyMetadata propertyMetadata : metadata.getPropertyMetadataCollection()) {
      Object propertyValue = propertyMetadata.getReadMethod().invoke(input);
      if (propertyValue == null && propertyMetadata.isOptional()) {
        continue;
      }
      ValueBuilder<?, ?, ?> valueBuilder = propertyMetadata.getMapper()
          .toDatastore(propertyValue);
      // ListValues cannot have indexing turned off. Indexing is turned on by
      // default, so we don't touch excludeFromIndexes for ListValues.
      if (valueBuilder.getValueType() != ValueType.LIST) {
        valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed());
      }
      Value<?> value = valueBuilder.build();
      entityBuilder.set(propertyMetadata.getMappedName(), value);
      Indexer indexer = propertyMetadata.getSecondaryIndexer();
      if (indexer != null) {
        entityBuilder.set(propertyMetadata.getSecondaryIndexName(), indexer.index(value));
      }
    }
    return EntityValue.newBuilder(entityBuilder.build());
  } catch (Throwable exp) {
    throw new MappingException(exp);
  }
}
 
Example 7
Source File: CatchAllMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public ValueBuilder<?, ?, ?> toDatastore(Object input) {
  ValueBuilder<?, ?, ?> builder;
  if (input == null) {
    builder = NullValue.newBuilder();
  } else if (input instanceof Long) {
    builder = LongValue.newBuilder((long) input);
  } else if (input instanceof Double) {
    builder = DoubleValue.newBuilder((double) input);
  } else if (input instanceof Boolean) {
    builder = BooleanValue.newBuilder((boolean) input);
  } else if (input instanceof String) {
    builder = StringValue.newBuilder((String) input);
  } else if (input instanceof DatastoreKey) {
    builder = KeyValue.newBuilder(((DatastoreKey) input).nativeKey());
  } else if (input instanceof GeoLocation) {
    GeoLocation geoLocation = (GeoLocation) input;
    builder = LatLngValue
        .newBuilder(LatLng.of(geoLocation.getLatitude(), geoLocation.getLongitude()));
  } else if (input instanceof Map) {
    @SuppressWarnings("unchecked")
    Map<String, ?> map = (Map<String, ?>) input;
    FullEntity.Builder<IncompleteKey> entityBuilder = FullEntity.newBuilder();
    for (Map.Entry<String, ?> entry : map.entrySet()) {
      String key = entry.getKey();
      entityBuilder.set(key, toDatastore(entry.getValue()).build());
    }
    builder = EntityValue.newBuilder(entityBuilder.build());
  } else {
    throw new MappingException(String.format("Unsupported type: %s", input.getClass().getName()));
  }
  return builder;
}
 
Example 8
Source File: Marshaller.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Marshals the embedded field represented by the given metadata.
 * 
 * @param embeddedMetadata
 *          the metadata of the embedded field.
 * @param target
 *          the object in which the embedded field is defined/accessible from.
 * @return the ValueBuilder equivalent to embedded object
 */
private ValueBuilder<?, ?, ?> marshalWithImplodedStrategy(EmbeddedMetadata embeddedMetadata,
    Object target) {
  try {
    Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target);
    if (embeddedObject == null) {
      if (embeddedMetadata.isOptional()) {
        return null;
      }
      NullValue.Builder nullValueBuilder = NullValue.newBuilder();
      nullValueBuilder.setExcludeFromIndexes(!embeddedMetadata.isIndexed());
      return nullValueBuilder;
    }
    FullEntity.Builder<IncompleteKey> embeddedEntityBuilder = FullEntity.newBuilder();
    for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) {
      marshalField(propertyMetadata, embeddedObject, embeddedEntityBuilder);
    }
    for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) {
      ValueBuilder<?, ?, ?> embeddedEntityBuilder2 = marshalWithImplodedStrategy(
          embeddedMetadata2, embeddedObject);
      if (embeddedEntityBuilder2 != null) {
        embeddedEntityBuilder.set(embeddedMetadata2.getMappedName(),
            embeddedEntityBuilder2.build());
      }
    }
    EntityValue.Builder valueBuilder = EntityValue.newBuilder(embeddedEntityBuilder.build());
    valueBuilder.setExcludeFromIndexes(!embeddedMetadata.isIndexed());
    return valueBuilder;

  } catch (Throwable t) {
    throw new EntityManagerException(t);
  }

}
 
Example 9
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();
}