com.google.cloud.datastore.Value Java Examples

The following examples show how to use com.google.cloud.datastore.Value. 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: SetMapper.java    From catatumbo with 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 #2
Source File: Marshaller.java    From catatumbo with 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 #3
Source File: DefaultDatastoreEntityConverterTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: DefaultDatastoreEntityConverterTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: DatastoreNativeTypes.java    From spring-cloud-gcp with 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 #6
Source File: UpperCaseStringListIndexer.java    From catatumbo with 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 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 #8
Source File: TwoStepsConversions.java    From spring-cloud-gcp with 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 #9
Source File: DateMapper.java    From catatumbo with 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 #10
Source File: ListMapper.java    From catatumbo with 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 #11
Source File: OffsetDateTimeMapper.java    From catatumbo with 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 #12
Source File: ZonedDateTimeMapper.java    From catatumbo with 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 #13
Source File: MapMapper.java    From catatumbo with 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 #14
Source File: EmbeddedObjectMapper.java    From catatumbo with 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 #15
Source File: LowerCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test(expected = IndexingException.class)
public void testIndex_5() {
  Value<?>[] inputArray = { StringValue.of("Hello"), NullValue.of(), LongValue.of(5L) };
  ListValue input = ListValue.of(Arrays.asList(inputArray));
  try {
    ListValue output = (ListValue) indexer.index(input);
  } catch (Exception exp) {
    LOGGER.log(Level.INFO, exp.toString());
    throw exp;
  }
}
 
Example #16
Source File: LowerCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test(expected = IndexingException.class)
public void testIndex_4() {
  StringValue input = StringValue.of("Hello World");
  try {
    Value<?> output = indexer.index(input);
  } catch (Exception exp) {
    LOGGER.log(Level.INFO, exp.toString());
    throw exp;
  }
}
 
Example #17
Source File: DecimalMapperTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore10() {
  DecimalMapper mapper = new DecimalMapper(6, 2);
  Value<?> value = mapper.toDatastore(new BigDecimal("0.1")).build();
  assertTrue(value instanceof LongValue);
  assertEquals(10L, value.get());
}
 
Example #18
Source File: LowerCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIndex_3() {
  Value<?>[] inputArray = { StringValue.of("Hello"), NullValue.of() };
  ListValue input = ListValue.of(Arrays.asList(inputArray));
  ListValue output = (ListValue) indexer.index(input);
  List<? extends Value> inputList = input.get();
  List<? extends Value> outputList = output.get();
  assertEquals(((StringValue) inputList.get(0)).get().toLowerCase(Locale.ENGLISH),
      outputList.get(0).get());
  assertEquals(inputList.get(1).get(), outputList.get(1).get());
}
 
Example #19
Source File: LowerCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIndex_2() {
  Value<?>[] inputArray = { StringValue.of("ONE"), StringValue.of("Two"),
      StringValue.of("thRee") };
  ListValue input = ListValue.of(Arrays.asList(inputArray));
  ListValue output = (ListValue) indexer.index(input);
  List<StringValue> inputList = (List<StringValue>) input.get();
  List<StringValue> outputList = (List<StringValue>) output.get();
  assertEquals(inputList.get(0).get().toLowerCase(Locale.ENGLISH), outputList.get(0).get());
  assertEquals(inputList.get(1).get().toLowerCase(Locale.ENGLISH), outputList.get(1).get());
  assertEquals(inputList.get(2).get().toLowerCase(Locale.ENGLISH), outputList.get(2).get());
}
 
Example #20
Source File: ByteMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  Long l = ((LongValue) input).get();
  if (l < Byte.MIN_VALUE || l > Byte.MAX_VALUE) {
    throw new MappingException(String.format("Value %d is out of range for byte type", l));
  }
  return l.byteValue();
}
 
Example #21
Source File: DeviceTypeMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  String s = ((StringValue) input).get();
  return Enum.valueOf(DeviceType.class, s.toUpperCase());
}
 
Example #22
Source File: CharArrayMapper.java    From catatumbo with 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().toCharArray();
}
 
Example #23
Source File: LongMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  return ((LongValue) input).get();
}
 
Example #24
Source File: DecimalMapperTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore4() {
  DecimalMapper mapper = new DecimalMapper(18, 6);
  Value<?> value = mapper.toDatastore(new BigDecimal("-123456789012.123456")).build();
  assertTrue(value instanceof LongValue);
  assertEquals(-123456789012123456L, value.get());
}
 
Example #25
Source File: CatchAllMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  Object javaValue;
  if (input instanceof NullValue) {
    javaValue = null;
  } else if (input instanceof StringValue) {
    javaValue = input.get();
  } else if (input instanceof LongValue) {
    javaValue = input.get();
  } else if (input instanceof DoubleValue) {
    javaValue = input.get();
  } else if (input instanceof BooleanValue) {
    javaValue = input.get();
  } else if (input instanceof KeyValue) {
    javaValue = new DefaultDatastoreKey(((KeyValue) input).get());
  } else if (input instanceof LatLngValue) {
    LatLng latLong = ((LatLngValue) input).get();
    javaValue = new GeoLocation(latLong.getLatitude(), latLong.getLongitude());
  } else if (input instanceof EntityValue) {
    EntityValue entityValue = (EntityValue) input;
    FullEntity<?> entity = entityValue.get();
    Map<String, Object> map = new HashMap<>();
    for (String property : entity.getNames()) {
      map.put(property, toModel(entity.getValue(property)));
    }
    javaValue = map;
  } else {
    throw new MappingException(String.format("Unsupported type %s", input.getClass().getName()));
  }
  return javaValue;
}
 
Example #26
Source File: FloatMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  DoubleValue value = (DoubleValue) input;
  Double d = value.get();
  if (d < -Float.MAX_VALUE || d > Float.MAX_VALUE) {
    throw new MappingException(String.format("Value %s is out of range for float type", d));
  }
  return d.floatValue();
}
 
Example #27
Source File: DecimalMapperTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore12() {
  DecimalMapper mapper = new DecimalMapper(6, 2);
  Value<?> value = mapper.toDatastore(new BigDecimal("0.0")).build();
  assertTrue(value instanceof LongValue);
  assertEquals(0L, value.get());
}
 
Example #28
Source File: FloatMapperTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testToDatastore_5() {
  float f = 1f / 3f;
  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 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 #30
Source File: BigDecimalMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  return BigDecimal.valueOf(((DoubleValue) input).get());
}