Search in sources :

Example 1 with Value

use of com.google.cloud.datastore.Value in project spring-cloud-gcp by spring-cloud.

the class DefaultDatastoreEntityConverter method write.

@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);
        }
    });
}
Also used : PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) DatastoreDataException(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreDataException) EntityValue(com.google.cloud.datastore.EntityValue) Value(com.google.cloud.datastore.Value) StringValue(com.google.cloud.datastore.StringValue) ListValue(com.google.cloud.datastore.ListValue) StringValue(com.google.cloud.datastore.StringValue) DatastorePersistentProperty(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentProperty)

Example 2 with Value

use of com.google.cloud.datastore.Value in project spring-cloud-gcp by spring-cloud.

the class TwoStepsConversions method applyEntityValueBuilder.

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());
}
Also used : FullEntity(com.google.cloud.datastore.FullEntity) DatastoreMappingContext(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreMappingContext) Arrays(java.util.Arrays) CustomConversions(org.springframework.data.convert.CustomConversions) BiFunction(java.util.function.BiFunction) Builder(com.google.cloud.datastore.FullEntity.Builder) TypeInformation(org.springframework.data.util.TypeInformation) Function(java.util.function.Function) ArrayList(java.util.ArrayList) ValueUtil(org.springframework.cloud.gcp.data.datastore.core.util.ValueUtil) ClassTypeInformation(org.springframework.data.util.ClassTypeInformation) Map(java.util.Map) StreamSupport(java.util.stream.StreamSupport) ValueUtil.boxIfNeeded(org.springframework.cloud.gcp.data.datastore.core.util.ValueUtil.boxIfNeeded) Converter(org.springframework.core.convert.converter.Converter) ClassUtils(org.springframework.util.ClassUtils) BaseEntity(com.google.cloud.datastore.BaseEntity) DatastoreDataException(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreDataException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) EntityValue(com.google.cloud.datastore.EntityValue) GenericConversionService(org.springframework.core.convert.support.GenericConversionService) ConversionException(org.springframework.core.convert.ConversionException) Collectors(java.util.stream.Collectors) IncompleteKey(com.google.cloud.datastore.IncompleteKey) Consumer(java.util.function.Consumer) List(java.util.List) Value(com.google.cloud.datastore.Value) DatastorePersistentProperty(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentProperty) EmbeddedType(org.springframework.cloud.gcp.data.datastore.core.mapping.EmbeddedType) Optional(java.util.Optional) Blob(com.google.cloud.datastore.Blob) ListValue(com.google.cloud.datastore.ListValue) DefaultConversionService(org.springframework.core.convert.support.DefaultConversionService) Assert(org.springframework.util.Assert) Optional(java.util.Optional) FullEntity(com.google.cloud.datastore.FullEntity) IncompleteKey(com.google.cloud.datastore.IncompleteKey)

Example 3 with Value

use of com.google.cloud.datastore.Value in project spring-cloud-gcp by spring-cloud.

the class DatastoreNativeTypes method wrapValue.

/**
 * 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.");
}
Also used : BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) NullValue(com.google.cloud.datastore.NullValue) DatastoreDataException(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreDataException) LongValue(com.google.cloud.datastore.LongValue) DoubleValue(com.google.cloud.datastore.DoubleValue) TimestampValue(com.google.cloud.datastore.TimestampValue) BooleanValue(com.google.cloud.datastore.BooleanValue) NullValue(com.google.cloud.datastore.NullValue) KeyValue(com.google.cloud.datastore.KeyValue) EntityValue(com.google.cloud.datastore.EntityValue) BlobValue(com.google.cloud.datastore.BlobValue) LatLngValue(com.google.cloud.datastore.LatLngValue) Value(com.google.cloud.datastore.Value) StringValue(com.google.cloud.datastore.StringValue)

Example 4 with Value

use of com.google.cloud.datastore.Value in project spring-cloud-gcp by spring-cloud.

the class DefaultDatastoreEntityConverterTests method testCollectionFieldsUnsupportedWriteOnly.

@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));
}
Also used : FullEntity(com.google.cloud.datastore.FullEntity) Entity(com.google.cloud.datastore.Entity) EmbeddedEntity(org.springframework.cloud.gcp.data.datastore.core.convert.TestItemWithEmbeddedEntity.EmbeddedEntity) BaseEntity(com.google.cloud.datastore.BaseEntity) DatastoreMappingContext(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreMappingContext) DiscriminatorValue(org.springframework.cloud.gcp.data.datastore.core.mapping.DiscriminatorValue) NullValue(com.google.cloud.datastore.NullValue) EntityValue(com.google.cloud.datastore.EntityValue) Value(com.google.cloud.datastore.Value) StringValue(com.google.cloud.datastore.StringValue) ListValue(com.google.cloud.datastore.ListValue) Test(org.junit.Test)

Example 5 with Value

use of com.google.cloud.datastore.Value in project spring-cloud-gcp by spring-cloud.

the class GqlDatastoreQueryTests method compoundNameConventionTest.

@Test
public void compoundNameConventionTest() {
    String gql = "SELECT * FROM " + "|org.springframework.cloud.gcp.data.datastore." + "repository.query.GqlDatastoreQueryTests$Trade|" + " WHERE price=:#{#tag6 * -1} AND price<>:#{#tag6 * -1} OR " + "price<>:#{#tag7 * -1} AND " + "( action=@tag0 AND ticker=@tag1 ) OR " + "( trader_id=@tag2 AND price<@tag3 ) OR ( price>=@tag4 AND id<>NULL AND " + "trader_id=NULL AND trader_id LIKE %@tag5 AND price=TRUE AND price=FALSE AND " + "price>@tag6 AND price<=@tag7 AND trade_ref = @tag8) ORDER BY id DESC LIMIT 3;";
    String entityResolvedGql = "SELECT * FROM trades" + " WHERE price=@SpELtag1 AND price<>@SpELtag2 OR price<>@SpELtag3 AND " + "( action=@tag0 AND ticker=@tag1 ) OR " + "( trader_id=@tag2 AND price<@tag3 ) OR ( price>=@tag4 AND id<>NULL AND " + "trader_id=NULL AND trader_id LIKE %@tag5 AND price=TRUE AND price=FALSE AND " + "price>@tag6 AND price<=@tag7 AND trade_ref = @tag8) ORDER BY id DESC LIMIT 3";
    Trade trade = new Trade();
    trade.id = "tradeId1";
    Object[] paramVals = new Object[] { "BUY", "abcd", // this is an array param of the non-natively supported type and will need conversion
    new int[] { 1, 2 }, new double[] { 8.88, 9.99 }, // this parameter is a simple int, which is not a directly supported type and uses
    3, // conversions
    "blahblah", 1.11, 2.22, trade };
    String[] paramNames = new String[] { "tag0", "tag1", "tag2", "tag3", "tag4", "tag5", "tag6", "tag7", "tag8" };
    buildParameters(paramVals, paramNames);
    KeyFactory keyFactory = new KeyFactory("proj");
    keyFactory.setKind("kind");
    Key key = keyFactory.newKey("tradeid1-key");
    doReturn(key).when(this.datastoreTemplate).getKey(any());
    EvaluationContext evaluationContext = new StandardEvaluationContext();
    for (int i = 0; i < paramVals.length; i++) {
        evaluationContext.setVariable(paramNames[i], paramVals[i]);
    }
    when(this.evaluationContextProvider.getEvaluationContext(any(), any())).thenReturn(evaluationContext);
    GqlDatastoreQuery gqlDatastoreQuery = createQuery(gql, false, false);
    doAnswer((invocation) -> {
        GqlQuery statement = invocation.getArgument(0);
        assertThat(statement.getQueryString()).isEqualTo(entityResolvedGql);
        Map<String, Value> paramMap = statement.getNamedBindings();
        assertThat(paramMap.get("tag0").get()).isEqualTo(paramVals[0]);
        assertThat(paramMap.get("tag1").get()).isEqualTo(paramVals[1]);
        // custom conversion is expected to have been used in this param
        assertThat((long) ((LongValue) (((List) paramMap.get("tag2").get()).get(0))).get()).isEqualTo(1L);
        assertThat((long) ((LongValue) (((List) paramMap.get("tag2").get()).get(1))).get()).isEqualTo(2L);
        double actual = ((DoubleValue) (((List) paramMap.get("tag3").get()).get(0))).get();
        assertThat(actual).isEqualTo(((double[]) paramVals[3])[0], DELTA);
        actual = ((DoubleValue) (((List) paramMap.get("tag3").get()).get(1))).get();
        assertThat(actual).isEqualTo(((double[]) paramVals[3])[1], DELTA);
        // 3L is expected even though 3 int was the original param due to custom conversions
        assertThat(paramMap.get("tag4").get()).isEqualTo(3L);
        assertThat(paramMap.get("tag5").get()).isEqualTo(paramVals[5]);
        assertThat(paramMap.get("tag6").get()).isEqualTo(paramVals[6]);
        assertThat(paramMap.get("tag7").get()).isEqualTo(paramVals[7]);
        assertThat((double) paramMap.get("SpELtag1").get()).isEqualTo(-1 * (double) paramVals[6], DELTA);
        assertThat((double) paramMap.get("SpELtag2").get()).isEqualTo(-1 * (double) paramVals[6], DELTA);
        assertThat((double) paramMap.get("SpELtag3").get()).isEqualTo(-1 * (double) paramVals[7], DELTA);
        assertThat(((KeyValue) paramMap.get("tag8")).get()).isSameAs(key);
        return null;
    }).when(this.datastoreTemplate).queryKeysOrEntities(any(), eq(Trade.class));
    doReturn(false).when(gqlDatastoreQuery).isNonEntityReturnedType(any());
    gqlDatastoreQuery.execute(paramVals);
    verify(this.datastoreTemplate, times(1)).queryKeysOrEntities(any(), eq(Trade.class));
}
Also used : StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) KeyValue(com.google.cloud.datastore.KeyValue) GqlQuery(com.google.cloud.datastore.GqlQuery) DoubleValue(com.google.cloud.datastore.DoubleValue) LongValue(com.google.cloud.datastore.LongValue) DoubleValue(com.google.cloud.datastore.DoubleValue) KeyValue(com.google.cloud.datastore.KeyValue) Value(com.google.cloud.datastore.Value) ArrayList(java.util.ArrayList) List(java.util.List) EvaluationContext(org.springframework.expression.EvaluationContext) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) KeyFactory(com.google.cloud.datastore.KeyFactory) Key(com.google.cloud.datastore.Key) Test(org.junit.Test)

Aggregations

Value (com.google.cloud.datastore.Value)17 Test (org.junit.Test)11 KeyValue (com.google.cloud.datastore.KeyValue)10 ListValue (com.google.cloud.datastore.ListValue)9 BaseEntity (com.google.cloud.datastore.BaseEntity)8 EntityValue (com.google.cloud.datastore.EntityValue)8 FullEntity (com.google.cloud.datastore.FullEntity)8 NullValue (com.google.cloud.datastore.NullValue)8 DatastoreMappingContext (org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreMappingContext)8 DoubleValue (com.google.cloud.datastore.DoubleValue)7 Entity (com.google.cloud.datastore.Entity)7 LongValue (com.google.cloud.datastore.LongValue)7 StringValue (com.google.cloud.datastore.StringValue)7 ArrayList (java.util.ArrayList)7 List (java.util.List)7 Cursor (com.google.cloud.datastore.Cursor)6 GqlQuery (com.google.cloud.datastore.GqlQuery)6 Map (java.util.Map)6 DatastoreDataException (org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreDataException)6 Slice (org.springframework.data.domain.Slice)6