Java Code Examples for com.google.cloud.datastore.Value

The following examples show how to use com.google.cloud.datastore.Value. These examples are extracted from open source projects. 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 Project: spring-cloud-gcp   Source File: TwoStepsConversions.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Value convertOnWriteSingle(Object propertyVal) {
	Object result = propertyVal;
	if (result != null) {
		TypeTargets typeTargets = computeTypeTargets(result.getClass());
		if (typeTargets.getFirstStepTarget() != null) {
			result = this.conversionService.convert(propertyVal, typeTargets.getFirstStepTarget());
		}

		if (typeTargets.getSecondStepTarget() != null) {
			result = this.internalConversionService.convert(result, typeTargets.getSecondStepTarget());
		}
	}
	return DatastoreNativeTypes.wrapValue(result);
}
 
Example 2
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 Project: spring-cloud-gcp   Source File: DatastoreNativeTypes.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Wraps Datastore native type to Datastore value type.
 * @param propertyVal the property value to wrap
 * @return the wrapped value
*/
@SuppressWarnings("unchecked")
public static Value wrapValue(Object propertyVal) {
	if (propertyVal == null) {
		return new NullValue();
	}
	Class propertyClass = getTypeForWrappingInDatastoreValue(propertyVal);
	Function wrapper = DatastoreNativeTypes.DATASTORE_TYPE_WRAPPERS
			.get(propertyClass);
	if (wrapper != null) {
		return (Value) wrapper.apply(propertyVal);
	}
	throw new DatastoreDataException(
			"Unable to convert " + propertyClass
			+ " to Datastore supported type.");
}
 
Example 4
@Test
public void testCollectionFieldsUnsupportedWriteOnly() {
	TestItemUnsupportedFields.CollectionOfUnsupportedTypes item = getCollectionOfUnsupportedTypesItem();

	DatastoreEntityConverter entityConverter =
			new DefaultDatastoreEntityConverter(new DatastoreMappingContext(),
					new TwoStepsConversions(new DatastoreCustomConversions(Collections.singletonList(
							getNewTypeToIntegerConverter())), null, datastoreMappingContext));

	Entity.Builder builder = getEntityBuilder();
	entityConverter.write(item, builder);
	Entity entity = builder.build();

	List<Value<?>> intList = entity.getList("unsupportedElts");
	assertThat(intList.stream().map(Value::get).collect(Collectors.toList()))
			.as("validate int list values").isEqualTo(Arrays.asList(1L, 0L));
}
 
Example 5
@Test
public void testCollectionFieldsUnsupportedWriteRead() {
	TestItemUnsupportedFields.CollectionOfUnsupportedTypes item = getCollectionOfUnsupportedTypesItem();

	DatastoreEntityConverter entityConverter =
			new DefaultDatastoreEntityConverter(new DatastoreMappingContext(),
					new TwoStepsConversions(new DatastoreCustomConversions(Arrays.asList(
							getIntegerToNewTypeConverter(),
							getNewTypeToIntegerConverter()
					)), null, datastoreMappingContext));

	Entity.Builder builder = getEntityBuilder();
	entityConverter.write(item, builder);
	Entity entity = builder.build();

	List<Value<?>> intList = entity.getList("unsupportedElts");
	assertThat(intList.stream().map(Value::get).collect(Collectors.toList()))
			.as("validate long list values").isEqualTo(Arrays.asList(1L, 0L));

	TestItemUnsupportedFields.CollectionOfUnsupportedTypes read =
			entityConverter.read(TestItemUnsupportedFields.CollectionOfUnsupportedTypes.class, entity);

	assertThat(read.equals(item)).as("read object should be equal to original").isTrue();

}
 
Example 6
Source Project: catatumbo   Source File: UpperCaseStringListIndexer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Value<?> index(Value<?> input) {
  if (input.getType() == ValueType.NULL) {
    return NullValue.of();
  }
  try {
    ListValue.Builder builder = ListValue.newBuilder();
    List<? extends Value<?>> list = ((ListValue) input).get();
    for (Value<?> item : list) {
      builder.addValue(ITEM_INDEXER.index(item));
    }
    return builder.build();
  } catch (Exception exp) {
    throw new IndexingException(exp);
  }
}
 
Example 7
Source Project: catatumbo   Source File: SetMapper.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  List<? extends Value<?>> list = ((ListValue) input).get();
  Set<Object> output;
  if (Modifier.isAbstract(setClass.getModifiers())) {
    if (SortedSet.class.isAssignableFrom(setClass)) {
      output = new TreeSet<>();
    } else {
      output = new HashSet<>();
    }
  } else {
    output = (Set<Object>) IntrospectionUtils.instantiateObject(setClass);
  }
  for (Value<?> item : list) {
    output.add(itemMapper.toModel(item));
  }
  return output;
}
 
Example 8
Source Project: catatumbo   Source File: DateMapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  try {
    Timestamp ts = ((TimestampValue) input).get();
    long millis = TimeUnit.SECONDS.toMillis(ts.getSeconds())
        + TimeUnit.NANOSECONDS.toMillis(ts.getNanos());
    return new Date(millis);
  } catch (ClassCastException exp) {
    String pattern = "Expecting %s, but found %s";
    throw new MappingException(
        String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp);
  }
}
 
Example 9
Source Project: catatumbo   Source File: MapMapper.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  EntityValue entityValue = (EntityValue) input;
  FullEntity<?> entity = entityValue.get();
  Map<String, Object> map;
  if (Modifier.isAbstract(mapClass.getModifiers())) {
    if (SortedMap.class.equals(mapClass)) {
      map = new TreeMap<>();
    } else {
      map = new HashMap<>();
    }
  } else {
    map = (Map<String, Object>) IntrospectionUtils.instantiateObject(mapClass);
  }
  for (String property : entity.getNames()) {
    map.put(property, valueMapper.toModel(entity.getValue(property)));
  }
  return map;
}
 
Example 10
Source Project: catatumbo   Source File: EmbeddedObjectMapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input.getType() == ValueType.NULL) {
    return null;
  }
  try {
    FullEntity<?> entity = ((EntityValue) input).get();
    ConstructorMetadata constructorMetadata = metadata.getConstructorMetadata();
    Object embeddedObject = constructorMetadata.getConstructorMethodHandle().invoke();
    for (PropertyMetadata propertyMetadata : metadata.getPropertyMetadataCollection()) {
      String mappedName = propertyMetadata.getMappedName();
      if (entity.contains(mappedName)) {
        Value<?> propertyValue = entity.getValue(mappedName);
        Object fieldValue = propertyMetadata.getMapper().toModel(propertyValue);
        propertyMetadata.getWriteMethod().invoke(embeddedObject, fieldValue);
      }
    }
    if (constructorMetadata.isBuilderConstructionStrategy()) {
      embeddedObject = metadata.getConstructorMetadata().getBuildMethodHandle()
          .invoke(embeddedObject);
    }
    return embeddedObject;
  } catch (Throwable exp) {
    throw new MappingException(exp);
  }
}
 
Example 11
Source Project: catatumbo   Source File: ZonedDateTimeMapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  try {
    Timestamp ts = ((TimestampValue) input).get();
    long seconds = ts.getSeconds();
    int nanos = ts.getNanos();
    return ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanos), ZoneId.systemDefault());
  } catch (ClassCastException exp) {
    String pattern = "Expecting %s, but found %s";
    throw new MappingException(
        String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp);
  }
}
 
Example 12
Source Project: catatumbo   Source File: OffsetDateTimeMapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  try {
    Timestamp ts = ((TimestampValue) input).get();
    long seconds = ts.getSeconds();
    int nanos = ts.getNanos();
    return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanos),
        ZoneId.systemDefault());
  } catch (ClassCastException exp) {
    String pattern = "Expecting %s, but found %s";
    throw new MappingException(
        String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp);
  }
}
 
Example 13
Source Project: catatumbo   Source File: ListMapper.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  List<? extends Value<?>> list = ((ListValue) input).get();
  List<Object> output;
  if (Modifier.isAbstract(listClass.getModifiers())) {
    output = new ArrayList<>();
  } else {
    output = (List<Object>) IntrospectionUtils.instantiateObject(listClass);
  }
  for (Value<?> item : list) {
    output.add(itemMapper.toModel(item));
  }
  return output;
}
 
Example 14
Source Project: catatumbo   Source File: Marshaller.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Marshals the field with the given property metadata.
 * 
 * @param propertyMetadata
 *          the metadata of the field to be marshaled.
 * @param target
 *          the object in which the field is defined/accessible from
 * @param entityBuilder
 *          the native entity on which the marshaled field should be set
 */
private static void marshalField(PropertyMetadata propertyMetadata, Object target,
    BaseEntity.Builder<?, ?> entityBuilder) {
  Object fieldValue = IntrospectionUtils.getFieldValue(propertyMetadata, target);
  if (fieldValue == null && propertyMetadata.isOptional()) {
    return;
  }
  ValueBuilder<?, ?, ?> valueBuilder = propertyMetadata.getMapper().toDatastore(fieldValue);
  // 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<?> datastoreValue = valueBuilder.build();
  entityBuilder.set(propertyMetadata.getMappedName(), datastoreValue);
  Indexer indexer = propertyMetadata.getSecondaryIndexer();
  if (indexer != null) {
    entityBuilder.set(propertyMetadata.getSecondaryIndexName(), indexer.index(datastoreValue));
  }
}
 
Example 15
Source Project: catatumbo   Source File: FloatMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore_7() {
  float f = -Float.MAX_VALUE;
  FloatMapper mapper = new FloatMapper();
  Value output = mapper.toDatastore(f).build();
  System.out.printf("%s ---> %s%n", f, output.get());
  assertTrue(Double.valueOf(f).equals(output.get()));
}
 
Example 16
Source Project: spring-cloud-gcp   Source File: PartTreeDatastoreQuery.java    License: Apache License 2.0 5 votes vote down vote up
private Value convertParam(DatastorePersistentProperty persistentProperty, Object val) {
	//persistentProperty.isAssociation() is true if the property is annotated with @Reference,
	// which means that we store keys there
	if (persistentProperty.isAssociation()
			&& this.datastoreMappingContext.hasPersistentEntityFor(val.getClass())) {
		return KeyValue.of(this.datastoreOperations.getKey(val));
	}
	if (persistentProperty.isIdProperty()) {
		return KeyValue.of(this.datastoreOperations.createKey(this.datastorePersistentEntity.kindName(), val));
	}
	return this.datastoreOperations.getDatastoreEntityConverter().getConversions().convertOnWriteSingle(val);
}
 
Example 17
Source Project: catatumbo   Source File: DecimalMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore11() {
  DecimalMapper mapper = new DecimalMapper(6, 2);
  Value<?> value = mapper.toDatastore(new BigDecimal("0.10")).build();
  assertTrue(value instanceof LongValue);
  assertEquals(10L, value.get());
}
 
Example 18
Source Project: spring-cloud-gcp   Source File: DatastoreTemplate.java    License: Apache License 2.0 5 votes vote down vote up
private List<Entity> getReferenceEntitiesForSave(Object entity, Builder builder, Set<Key> persistedEntities) {
	DatastorePersistentEntity datastorePersistentEntity = this.datastoreMappingContext
			.getPersistentEntity(entity.getClass());
	List<Entity> entitiesToSave = new ArrayList<>();
	datastorePersistentEntity.doWithAssociations((AssociationHandler) (association) -> {
		PersistentProperty persistentProperty = association.getInverse();
		PersistentPropertyAccessor accessor = datastorePersistentEntity.getPropertyAccessor(entity);
		Object val = accessor.getProperty(persistentProperty);
		if (val == null) {
			return;
		}
		Value<?> value;
		if (LazyUtil.isLazyAndNotLoaded(val)) {
			value = LazyUtil.getKeys(val);
		}
		else if (persistentProperty.isCollectionLike()) {
			Iterable<?> iterableVal = (Iterable<?>) ValueUtil.toListIfArray(val);
			entitiesToSave.addAll(getEntitiesForSave(iterableVal, persistedEntities));
			List<KeyValue> keyValues = StreamSupport.stream((iterableVal).spliterator(), false)
					.map((o) -> KeyValue.of(this.getKey(o, false)))
					.collect(Collectors.toList());
			value = ListValue.of(keyValues);

		}
		else {
			entitiesToSave.addAll(getEntitiesForSave(Collections.singletonList(val), persistedEntities));
			Key key = getKey(val, false);
			value = KeyValue.of(key);
		}
		builder.set(((DatastorePersistentProperty) persistentProperty).getFieldName(), value);
	});
	return entitiesToSave;
}
 
Example 19
Source Project: catatumbo   Source File: DecimalMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = MappingException.class)
public void testToDatastore14() {
  try {
    DecimalMapper mapper = new DecimalMapper(5, 2);
    Value<?> value = mapper.toDatastore(new BigDecimal("1234.5")).build();
  } catch (Exception e) {
    System.err.println(e);
    throw e;
  }
}
 
Example 20
@Override
@SuppressWarnings("unchecked")
public void write(Object source, BaseEntity.Builder sink) {
	DatastorePersistentEntity<?> persistentEntity = this.mappingContext.getPersistentEntity(source.getClass());

	String discriminationFieldName = persistentEntity.getDiscriminationFieldName();
	List<String> discriminationValues = persistentEntity.getCompatibleDiscriminationValues();
	if (!discriminationValues.isEmpty() || discriminationFieldName != null) {
		sink.set(discriminationFieldName,
				discriminationValues.stream().map(StringValue::of).collect(Collectors.toList()));
	}
	PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(source);
	persistentEntity.doWithColumnBackedProperties(
			(DatastorePersistentProperty persistentProperty) -> {
				// Datastore doesn't store its Key as a regular field.
				if (persistentProperty.isIdProperty()) {
					return;
				}
				try {
					Object val = accessor.getProperty(persistentProperty);
					Value convertedVal = this.conversions.convertOnWrite(val, persistentProperty);

					if (persistentProperty.isUnindexed()) {
						convertedVal = setExcludeFromIndexes(convertedVal);
					}
					sink.set(persistentProperty.getFieldName(), convertedVal);
				}
				catch (DatastoreDataException ex) {
					throw new DatastoreDataException(
							"Unable to write "
									+ persistentEntity.kindName() + "." + persistentProperty.getFieldName(),
							ex);
				}
			});
}
 
Example 21
Source Project: catatumbo   Source File: DecimalMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore7() {
  DecimalMapper mapper = new DecimalMapper(1, 1);
  Value<?> value = mapper.toDatastore(new BigDecimal("0.5")).build();
  assertTrue(value instanceof LongValue);
  assertEquals(5L, value.get());
}
 
Example 22
@Test
public void testCollectionFieldsNulls() {
	TestDatastoreItemCollections item =
			new TestDatastoreItemCollections(
					Arrays.asList(1, 2),
					null,
					null, new boolean[] {true, false}, null, null);

	Entity.Builder builder = getEntityBuilder();
	ENTITY_CONVERTER.write(item, builder);
	Entity entity = builder.build();

	List<Value<?>> intList = entity.getList("intList");
	assertThat(intList.stream().map(Value::get).collect(Collectors.toList()))
			.as("validate int list values").isEqualTo(Arrays.asList(1L, 2L));

	List<Value<?>> stringArray = entity.getList("stringArray");
	assertThat(stringArray)
			.as("validate string array is null").isNull();

	List<Value<?>> beanContext = entity.getList("beanContext");
	assertThat(beanContext)
			.as("validate bean context is null")
			.isNull();

	TestDatastoreItemCollections readItem = ENTITY_CONVERTER.read(TestDatastoreItemCollections.class, entity);
	assertThat(item.equals(readItem)).as("read object should be equal to original").isTrue();

}
 
Example 23
Source Project: catatumbo   Source File: UpperCaseStringIndexer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Value<?> index(Value<?> input) {
  if (input.getType() == ValueType.NULL) {
    return NullValue.of();
  }
  try {
    String str = ((StringValue) input).get();
    return StringValue.of(str.toUpperCase(Locale.ENGLISH));
  } catch (Exception exp) {
    throw new IndexingException(exp);
  }
}
 
Example 24
Source Project: catatumbo   Source File: DecimalMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore9() {
  DecimalMapper mapper = new DecimalMapper(18, 18);
  Value<?> value = mapper.toDatastore(new BigDecimal("0.000000000000000565")).build();
  assertTrue(value instanceof LongValue);
  assertEquals(565L, value.get());
}
 
Example 25
Source Project: catatumbo   Source File: FloatMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore_8() {
  float f = Float.MIN_VALUE;
  FloatMapper mapper = new FloatMapper();
  Value output = mapper.toDatastore(f).build();
  System.out.printf("%s ---> %s%n", f, output.get());
  assertTrue(Double.valueOf(f).equals(output.get()));
}
 
Example 26
Source Project: catatumbo   Source File: LocalDateMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  try {
    return LocalDate.parse(((StringValue) input).get());
  } catch (ClassCastException exp) {
    String pattern = "Mapping of type %s to %s is not supported";
    throw new MappingException(
        String.format(pattern, input.getClass().getName(), LocalDate.class.getName()), exp);
  }
}
 
Example 27
Source Project: catatumbo   Source File: StringMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  return ((StringValue) input).get();
}
 
Example 28
Source Project: catatumbo   Source File: FloatMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore_3() {
  float f = -1.00000f;
  FloatMapper mapper = new FloatMapper();
  Value output = mapper.toDatastore(f).build();
  System.out.printf("%s ---> %s%n", f, output.get());
  assertTrue(Double.valueOf(f).equals(output.get()));
}
 
Example 29
Source Project: catatumbo   Source File: FloatMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore_4() {
  float f = 3.1415927f;
  FloatMapper mapper = new FloatMapper();
  Value output = mapper.toDatastore(f).build();
  System.out.printf("%s ---> %s%n", f, output.get());
  assertTrue(Double.valueOf(f).equals(output.get()));
}
 
Example 30
Source Project: catatumbo   Source File: KeyMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  KeyValue keyValue = (KeyValue) input;
  return new DefaultDatastoreKey(keyValue.get());
}