Search in sources :

Example 1 with DatastoreMappingContext

use of com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext in project spring-cloud-gcp by GoogleCloudPlatform.

the class DatastoreTemplateTests method setUpConverters.

private void setUpConverters(Entity ce1, Query childTestEntityQuery, QueryResults childTestEntityQueryResults, QueryResults testEntityQueryResults) {
    // mocking the converter to return the final objects corresponding to their
    // specific entities.
    DatastorePersistentEntity testPersistentEntity = new DatastoreMappingContext().getDatastorePersistentEntity(TestEntity.class);
    DatastorePersistentEntity childPersistentEntity = new DatastoreMappingContext().getDatastorePersistentEntity(ChildEntity.class);
    when(this.datastoreEntityConverter.read(TestEntity.class, this.e1)).thenReturn(this.ob1);
    when(this.datastoreEntityConverter.getDiscriminationPersistentEntity(TestEntity.class, this.e1)).thenReturn(testPersistentEntity);
    when(this.datastoreEntityConverter.read(TestEntity.class, this.e2)).thenReturn(this.ob2);
    when(this.datastoreEntityConverter.getDiscriminationPersistentEntity(TestEntity.class, this.e2)).thenReturn(testPersistentEntity);
    when(this.datastoreEntityConverter.read(eq(ChildEntity.class), same(ce1))).thenAnswer(invocationOnMock -> createChildEntity());
    when(this.datastoreEntityConverter.getDiscriminationPersistentEntity(eq(ChildEntity.class), same(ce1))).thenReturn(childPersistentEntity);
    doAnswer(invocation -> {
        FullEntity.Builder builder = invocation.getArgument(1);
        builder.set("color", "simple_test_color");
        builder.set("int_field", 1);
        return null;
    }).when(this.datastoreEntityConverter).write(same(this.simpleTestEntity), any());
    doAnswer(invocation -> {
        FullEntity.Builder builder = invocation.getArgument(1);
        builder.set("color", NullValue.of());
        builder.set("int_field", NullValue.of());
        return null;
    }).when(this.datastoreEntityConverter).write(same(this.simpleTestEntityNullVallues), any());
    when(this.datastore.run(this.testEntityQuery)).thenReturn(testEntityQueryResults);
    when(this.datastore.run(this.findAllTestEntityQuery)).thenReturn(testEntityQueryResults);
    when(this.datastore.run(childTestEntityQuery)).thenReturn(childTestEntityQueryResults);
    // Because get() takes varags, there is difficulty in matching the single param
    // case using just thenReturn.
    doAnswer(invocation -> {
        Object key = invocation.getArgument(0);
        List<Entity> result = new ArrayList<>();
        if (key instanceof Key) {
            if (key == this.key1) {
                result.add(this.e1);
            } else if (key == this.keyChild1) {
                result.add(ce1);
            } else {
                result.add(null);
            }
        }
        return result;
    }).when(this.datastore).fetch((Key[]) any());
    when(this.objectToKeyFactory.getKeyFromId(eq(this.key1), any())).thenReturn(this.key1);
    when(this.objectToKeyFactory.getKeyFromId(eq(this.key2), any())).thenReturn(this.key2);
    when(this.objectToKeyFactory.getKeyFromId(eq(this.keyChild1), any())).thenReturn(this.keyChild1);
    when(this.objectToKeyFactory.getKeyFromId(eq(this.badKey), any())).thenReturn(this.badKey);
    when(this.objectToKeyFactory.getKeyFromObject(eq(this.ob1), any())).thenReturn(this.key1);
    when(this.objectToKeyFactory.getKeyFromObject(eq(this.ob2), any())).thenReturn(this.key2);
    this.childKey2 = createFakeKey("child_id2");
    when(this.objectToKeyFactory.allocateKeyForObject(same(this.childEntity2), any(), eq(this.key1))).thenReturn(this.childKey2);
    this.childKey3 = createFakeKey("child_id3");
    when(this.objectToKeyFactory.allocateKeyForObject(same(this.childEntity3), any(), eq(this.key1))).thenReturn(this.childKey3);
    this.childKey4 = createFakeKey("child_id4");
    when(this.objectToKeyFactory.allocateKeyForObject(same(this.childEntity4), any(), any())).thenReturn(this.childKey4);
    when(this.objectToKeyFactory.getKeyFromObject(same(this.childEntity4), any())).thenReturn(this.childKey4);
    this.childKey5 = createFakeKey("child_id5");
    when(this.objectToKeyFactory.allocateKeyForObject(same(this.childEntity5), any(), any())).thenReturn(this.childKey5);
    when(this.objectToKeyFactory.getKeyFromObject(same(this.childEntity5), any())).thenReturn(this.childKey5);
    this.childKey6 = createFakeKey("child_id6");
    when(this.objectToKeyFactory.allocateKeyForObject(same(this.childEntity6), any(), any())).thenReturn(this.childKey6);
    when(this.objectToKeyFactory.getKeyFromObject(same(this.childEntity6), any())).thenReturn(this.childKey6);
    this.childKey7 = createFakeKey("child_id7");
    when(this.objectToKeyFactory.allocateKeyForObject(same(this.childEntity7), any(), any())).thenReturn(this.childKey7);
    when(this.objectToKeyFactory.getKeyFromObject(same(this.childEntity7), any())).thenReturn(this.childKey7);
}
Also used : FullEntity(com.google.cloud.datastore.FullEntity) DatastorePersistentEntity(com.google.cloud.spring.data.datastore.core.mapping.DatastorePersistentEntity) Entity(com.google.cloud.datastore.Entity) DatastoreMappingContext(com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext) DatastorePersistentEntity(com.google.cloud.spring.data.datastore.core.mapping.DatastorePersistentEntity) ArrayList(java.util.ArrayList) FullEntity(com.google.cloud.datastore.FullEntity) Key(com.google.cloud.datastore.Key)

Example 2 with DatastoreMappingContext

use of com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext in project spring-cloud-gcp by GoogleCloudPlatform.

the class DatastoreTemplateTests method multipleNamespaceTest.

@Test
void multipleNamespaceTest() {
    Datastore databaseClient1 = mock(Datastore.class);
    Datastore databaseClient2 = mock(Datastore.class);
    AtomicInteger currentClient = new AtomicInteger(1);
    Supplier<Integer> regionProvider = currentClient::getAndIncrement;
    // this client selector will alternate between the two clients
    ConcurrentHashMap<Integer, Datastore> store = new ConcurrentHashMap<>();
    Supplier<Datastore> clientProvider = () -> store.computeIfAbsent(regionProvider.get(), u -> u % 2 == 1 ? databaseClient1 : databaseClient2);
    DatastoreTemplate template = new DatastoreTemplate(clientProvider, this.datastoreEntityConverter, new DatastoreMappingContext(), this.objectToKeyFactory);
    ChildEntity childEntity = new ChildEntity();
    childEntity.id = createFakeKey("key");
    when(this.objectToKeyFactory.getKeyFromObject(same(childEntity), any())).thenReturn(childEntity.id);
    // this first save should use the first client
    template.save(childEntity);
    verify(databaseClient1, times(1)).put((FullEntity<?>[]) any());
    verify(databaseClient2, times(0)).put((FullEntity<?>[]) any());
    // this second save should use the second client
    template.save(childEntity);
    verify(databaseClient1, times(1)).put((FullEntity<?>[]) any());
    verify(databaseClient2, times(1)).put((FullEntity<?>[]) any());
    // this third save should use the first client again
    template.save(childEntity);
    verify(databaseClient1, times(2)).put((FullEntity<?>[]) any());
    verify(databaseClient2, times(1)).put((FullEntity<?>[]) any());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Datastore(com.google.cloud.datastore.Datastore) DatastoreMappingContext(com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) FullEntity(com.google.cloud.datastore.FullEntity) Test(org.junit.jupiter.api.Test)

Example 3 with DatastoreMappingContext

use of com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext in project spring-cloud-gcp by GoogleCloudPlatform.

the class DefaultDatastoreEntityConverterTests method testUnindexedField.

@Test
void testUnindexedField() {
    UnindexedTestDatastoreItem item = new UnindexedTestDatastoreItem();
    item.setIndexedField(1L);
    item.setUnindexedField(2L);
    item.setUnindexedStringListField(Arrays.asList("a", "b"));
    item.setUnindexedMapField(new MapBuilder<String, String>().put("c", "C").put("d", "D").build());
    item.setEmbeddedItem(new UnindexedTestDatastoreItem(2, new UnindexedTestDatastoreItem(3, null)));
    item.setUnindexedItems(Collections.singletonList(new UnindexedTestDatastoreItem(4, new UnindexedTestDatastoreItem(5, null))));
    DatastoreEntityConverter entityConverter = new DefaultDatastoreEntityConverter(new DatastoreMappingContext(), new DatastoreServiceObjectToKeyFactory(() -> this.datastore));
    Entity.Builder builder = getEntityBuilder();
    entityConverter.write(item, builder);
    Entity entity = builder.build();
    assertThat(entity.getLong("indexedField")).as("validate indexed field value").isEqualTo(1L);
    assertThat(entity.getLong("unindexedField")).as("validate unindexed field value").isEqualTo(2L);
    assertThat(entity.getValue("indexedField").excludeFromIndexes()).as("validate excludeFromIndexes on indexed field").isFalse();
    assertThat(entity.getValue("unindexedField").excludeFromIndexes()).as("validate excludeFromIndexes on unindexed field").isTrue();
    // the ListValue itself must NOT be unindexed or it will cause exception. the contents
    // individually must be. Same for map.
    assertThat(entity.getValue("unindexedStringListField").excludeFromIndexes()).isFalse();
    assertThat(((ListValue) entity.getValue("unindexedStringListField")).get().get(0).excludeFromIndexes()).isTrue();
    assertThat(((ListValue) entity.getValue("unindexedStringListField")).get().get(1).excludeFromIndexes()).isTrue();
    assertThat(entity.getValue("unindexedMapField").excludeFromIndexes()).isFalse();
    assertThat(((EntityValue) entity.getValue("unindexedMapField")).get().getValue("c").excludeFromIndexes()).isTrue();
    assertThat(((EntityValue) entity.getValue("unindexedMapField")).get().getValue("d").excludeFromIndexes()).isTrue();
    // Multi-level embedded entities - exclusion from indexes
    testMultiLevelEmbeddedEntityUnindexed(((EntityValue) entity.getValue("embeddedItem")).get());
    // Multi-level embedded entities in a list - exclusion from indexes
    testMultiLevelEmbeddedEntityUnindexed(((EntityValue) ((ListValue) entity.getValue("unindexedItems")).get().get(0)).get());
}
Also used : FullEntity(com.google.cloud.datastore.FullEntity) Entity(com.google.cloud.datastore.Entity) BaseEntity(com.google.cloud.datastore.BaseEntity) EmbeddedEntity(com.google.cloud.spring.data.datastore.core.convert.TestItemWithEmbeddedEntity.EmbeddedEntity) DatastoreMappingContext(com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext) ListValue(com.google.cloud.datastore.ListValue) EntityValue(com.google.cloud.datastore.EntityValue) MapBuilder(com.google.cloud.spring.core.util.MapBuilder) Test(org.junit.jupiter.api.Test)

Example 4 with DatastoreMappingContext

use of com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext in project spring-cloud-gcp by GoogleCloudPlatform.

the class DefaultDatastoreEntityConverterTests method testCollectionFields.

@Test
void testCollectionFields() {
    byte[][] bytes = { { 1, 2 }, { 3, 4 } };
    List<byte[]> listByteArray = Arrays.asList(bytes);
    ComparableBeanContextSupport comparableBeanContextSupport = new ComparableBeanContextSupport();
    comparableBeanContextSupport.add("this implementation of Collection");
    comparableBeanContextSupport.add("is supported through a custom converter!");
    TestDatastoreItemCollections item = new TestDatastoreItemCollections(Arrays.asList(1, 2), comparableBeanContextSupport, new String[] { "abc", "def" }, new boolean[] { true, false }, bytes, listByteArray);
    DatastoreEntityConverter entityConverter = new DefaultDatastoreEntityConverter(new DatastoreMappingContext(), new TwoStepsConversions(new DatastoreCustomConversions(Arrays.asList(new Converter<List<String>, ComparableBeanContextSupport>() {

        @Override
        public ComparableBeanContextSupport convert(List<String> source) {
            ComparableBeanContextSupport bcs = new ComparableBeanContextSupport();
            source.forEach(bcs::add);
            return bcs;
        }
    }, new Converter<ComparableBeanContextSupport, List<String>>() {

        @Override
        public List<String> convert(ComparableBeanContextSupport bcs) {
            List<String> list = new ArrayList<>();
            bcs.iterator().forEachRemaining(s -> list.add((String) s));
            return list;
        }
    })), null, datastoreMappingContext));
    Entity.Builder builder = getEntityBuilder();
    entityConverter.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.stream().map(Value::get).collect(Collectors.toList())).as("validate string array values").isEqualTo(Arrays.asList("abc", "def"));
    List<Value<?>> beanContext = entity.getList("beanContext");
    assertThat(beanContext.stream().map(Value::get).collect(Collectors.toSet())).as("validate bean context values").isEqualTo(new HashSet<>(Arrays.asList("this implementation of Collection", "is supported through a custom converter!")));
    List<Value<?>> bytesVals = entity.getList("bytes");
    assertThat(bytesVals.stream().map(Value::get).collect(Collectors.toList())).as("validate array of byte[] values").isEqualTo(Arrays.asList(Blob.copyFrom(new byte[] { 1, 2 }), Blob.copyFrom(new byte[] { 3, 4 })));
    List<Value<?>> listByteArrayVals = entity.getList("listByteArray");
    assertThat(listByteArrayVals.stream().map(Value::get).collect(Collectors.toList())).as("validate list of byte[]").isEqualTo(Arrays.asList(Blob.copyFrom(new byte[] { 1, 2 }), Blob.copyFrom(new byte[] { 3, 4 })));
    TestDatastoreItemCollections readItem = entityConverter.read(TestDatastoreItemCollections.class, entity);
    assertThat(item).as("read object should be equal to original").isEqualTo(readItem);
}
Also used : ComparableBeanContextSupport(com.google.cloud.spring.data.datastore.core.convert.TestDatastoreItemCollections.ComparableBeanContextSupport) FullEntity(com.google.cloud.datastore.FullEntity) Entity(com.google.cloud.datastore.Entity) BaseEntity(com.google.cloud.datastore.BaseEntity) EmbeddedEntity(com.google.cloud.spring.data.datastore.core.convert.TestItemWithEmbeddedEntity.EmbeddedEntity) DatastoreMappingContext(com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext) ArrayList(java.util.ArrayList) NullValue(com.google.cloud.datastore.NullValue) EntityValue(com.google.cloud.datastore.EntityValue) DiscriminatorValue(com.google.cloud.spring.data.datastore.core.mapping.DiscriminatorValue) Value(com.google.cloud.datastore.Value) StringValue(com.google.cloud.datastore.StringValue) ListValue(com.google.cloud.datastore.ListValue) Converter(org.springframework.core.convert.converter.Converter) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 5 with DatastoreMappingContext

use of com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext in project spring-cloud-gcp by GoogleCloudPlatform.

the class DefaultDatastoreEntityConverterTests method privateCustomMapExceptionTest.

@Test
void privateCustomMapExceptionTest() {
    ServiceConfigurationPrivateCustomMap config = new ServiceConfigurationPrivateCustomMap("a", new PrivateCustomMap());
    DatastoreEntityConverter entityConverter = new DefaultDatastoreEntityConverter(new DatastoreMappingContext(), new DatastoreServiceObjectToKeyFactory(() -> this.datastore));
    Entity.Builder builder = getEntityBuilder();
    entityConverter.write(config, builder);
    Entity entity = builder.build();
    assertThatThrownBy(() -> {
        entityConverter.read(ServiceConfigurationPrivateCustomMap.class, entity);
    }).isInstanceOf(DatastoreDataException.class).hasMessageContaining("Unable to create an instance of a custom map type: " + "class com.google.cloud.spring.data.datastore.core.convert." + "DefaultDatastoreEntityConverterTests$PrivateCustomMap " + "(make sure the class is public and has a public no-args constructor)");
}
Also used : FullEntity(com.google.cloud.datastore.FullEntity) Entity(com.google.cloud.datastore.Entity) BaseEntity(com.google.cloud.datastore.BaseEntity) EmbeddedEntity(com.google.cloud.spring.data.datastore.core.convert.TestItemWithEmbeddedEntity.EmbeddedEntity) DatastoreMappingContext(com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext) DatastoreDataException(com.google.cloud.spring.data.datastore.core.mapping.DatastoreDataException) Test(org.junit.jupiter.api.Test)

Aggregations

DatastoreMappingContext (com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext)16 FullEntity (com.google.cloud.datastore.FullEntity)12 Entity (com.google.cloud.datastore.Entity)11 Test (org.junit.jupiter.api.Test)11 BaseEntity (com.google.cloud.datastore.BaseEntity)8 EmbeddedEntity (com.google.cloud.spring.data.datastore.core.convert.TestItemWithEmbeddedEntity.EmbeddedEntity)8 EntityValue (com.google.cloud.datastore.EntityValue)5 ListValue (com.google.cloud.datastore.ListValue)5 NullValue (com.google.cloud.datastore.NullValue)4 StringValue (com.google.cloud.datastore.StringValue)4 Value (com.google.cloud.datastore.Value)4 DiscriminatorValue (com.google.cloud.spring.data.datastore.core.mapping.DiscriminatorValue)4 BeforeEach (org.junit.jupiter.api.BeforeEach)4 DatastoreTemplate (com.google.cloud.spring.data.datastore.core.DatastoreTemplate)3 DatastorePersistentEntity (com.google.cloud.spring.data.datastore.core.mapping.DatastorePersistentEntity)3 ArrayList (java.util.ArrayList)3 EntityQuery (com.google.cloud.datastore.EntityQuery)2 MapBuilder (com.google.cloud.spring.core.util.MapBuilder)2 List (java.util.List)2 Datastore (com.google.cloud.datastore.Datastore)1