org.neo4j.driver.Values Java Examples

The following examples show how to use org.neo4j.driver.Values. 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: AuditingITBase.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@BeforeEach
protected void setupData() {
	try (Transaction transaction = driver.session().beginTransaction()) {
		transaction.run("MATCH (n) detach delete n");

		idOfExistingThing = transaction
			.run(
				"CREATE (t:ImmutableAuditableThing {name: $name, createdBy: $createdBy, createdAt: $createdAt}) RETURN id(t) as id",
				Values.parameters("name", EXISTING_THING_NAME, "createdBy", EXISTING_THING_CREATED_BY, "createdAt",
					EXISTING_THING_CREATED_AT))
			.single().get("id").asLong();

		transaction
			.run(
				"CREATE (t:ImmutableAuditableThingWithGeneratedId {name: $name, createdBy: $createdBy, createdAt: $createdAt, id: $id}) RETURN t.id as id",
				Values.parameters("name", EXISTING_THING_NAME, "createdBy", EXISTING_THING_CREATED_BY, "createdAt",
					EXISTING_THING_CREATED_AT, "id", idOfExistingThingWithGeneratedId));

		transaction.commit();
	}
}
 
Example #2
Source File: Neo4JEdgeWhileRemovingPropertyValueTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void givenPropertyValueShouldAddItToEdge() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(relationship.get(Mockito.eq("id"))).thenAnswer(invocation -> Values.value(1L));
    Mockito.when(relationship.type()).thenAnswer(invocation -> "label");
    Mockito.when(relationship.keys()).thenAnswer(invocation -> Collections.singleton("key1"));
    Mockito.when(relationship.get(Mockito.eq("key1"))).thenAnswer(invocation -> Values.value("value1"));
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    Neo4JEdge edge = new Neo4JEdge(graph, session, provider, outVertex, relationship, inVertex);
    Property<?> result = edge.property("p1", 1L);
    // act
    result.remove();
    // assert
    Assert.assertFalse("Failed to remove property from edge", edge.property("p1").isPresent());
}
 
Example #3
Source File: Neo4JEdgeWhileGettingPropertiesTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void givenNoKeysShouldShouldGetAllProperties() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(relationship.get(Mockito.eq("id"))).thenAnswer(invocation -> Values.value(1L));
    Mockito.when(relationship.type()).thenAnswer(invocation -> "label");
    Mockito.when(relationship.keys()).thenAnswer(invocation -> new ArrayList<>());
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    Neo4JEdge edge = new Neo4JEdge(graph, session, provider, outVertex, relationship, inVertex);
    edge.property("p1", 1L);
    edge.property("p2", 1L);
    // act
    Iterator<Property<Long>> result = edge.properties();
    // assert
    Assert.assertNotNull("Failed to get properties", result);
    Assert.assertTrue("Property is not present", result.hasNext());
    result.next();
    Assert.assertTrue("Property is not present", result.hasNext());
    result.next();
    Assert.assertFalse("Too many properties in edge", result.hasNext());
}
 
Example #4
Source File: Neo4JEdgeWhileGettingPropertiesTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void givenTwoKeysShouldShouldGetPropertyValues() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(relationship.get(Mockito.eq("id"))).thenAnswer(invocation -> Values.value(1L));
    Mockito.when(relationship.type()).thenAnswer(invocation -> "label");
    Mockito.when(relationship.keys()).thenAnswer(invocation -> Collections.singleton("key1"));
    Mockito.when(relationship.get(Mockito.eq("key1"))).thenAnswer(invocation -> Values.value("value1"));
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    Neo4JEdge edge = new Neo4JEdge(graph, session, provider, outVertex, relationship, inVertex);
    edge.property("p1", 1L);
    edge.property("p2", 1L);
    // act
    Iterator<Property<Long>> result = edge.properties("key1", "p2");
    // assert
    Assert.assertNotNull("Failed to get properties", result);
    Assert.assertTrue("Property is not present", result.hasNext());
    result.next();
    Assert.assertTrue("Property is not present", result.hasNext());
    result.next();
    Assert.assertFalse("Too many properties in edge", result.hasNext());
}
 
Example #5
Source File: Neo4JEdgeWhileGettingGraphTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void givenInDirectionShouldGetVertex() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(relationship.get(Mockito.eq("id"))).thenAnswer(invocation -> Values.value(1L));
    Mockito.when(relationship.type()).thenAnswer(invocation -> "label");
    Mockito.when(relationship.keys()).thenAnswer(invocation -> Collections.singleton("key1"));
    Mockito.when(relationship.get(Mockito.eq("key1"))).thenAnswer(invocation -> Values.value("value1"));
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    Neo4JEdge edge = new Neo4JEdge(graph, session, provider, outVertex, relationship, inVertex);
    // act
    Graph result = edge.graph();
    // assert
    Assert.assertNotNull("Invalid graph instance", result);
}
 
Example #6
Source File: DefaultNeo4jConverter.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public Object readValueForProperty(@Nullable Value value, TypeInformation<?> type) {

	boolean valueIsLiteralNullOrNullValue = value == null || value == Values.NULL;

	try {
		Class<?> rawType = type.getType();

		if (!valueIsLiteralNullOrNullValue && isCollection(type)) {
			Collection<Object> target = createCollection(rawType, type.getComponentType().getType(), value.size());
			value.values().forEach(
				element -> target.add(conversionService.convert(element, type.getComponentType().getType())));
			return target;
		}

		return conversionService.convert(valueIsLiteralNullOrNullValue ? null : value, rawType);
	} catch (Exception e) {
		String msg = String.format("Could not convert %s into %s", value, type.toString());
		throw new TypeMismatchDataAccessException(msg, e);
	}
}
 
Example #7
Source File: DatabaseSequenceElementIdProviderWhileGeneratingIdTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void givenTwoIdentifierRequestsShouldRequestPoolOfIdentifiers() {
    // arrange
    Mockito.when(record.get(Mockito.eq(0))).thenAnswer(invocation -> Values.value(1));
    Mockito.when(result.hasNext()).thenAnswer(invocation -> true);
    Mockito.when(result.next()).thenAnswer(invocation -> record);
    Mockito.when(transaction.run(Mockito.any(String.class), Mockito.anyMap())).thenAnswer(invocation -> result);
    Mockito.when(session.beginTransaction()).thenAnswer(invocation -> transaction);
    Mockito.when(driver.session()).thenAnswer(invocation -> session);
    DatabaseSequenceElementIdProvider provider = new DatabaseSequenceElementIdProvider(driver, 1, "field1", "label");
    // act
    Long id = provider.generate();
    // assert
    Assert.assertNotNull("Invalid identifier value", id);
    Assert.assertEquals("Provider returned an invalid identifier value", 1L, (long)id);
    // arrange
    Mockito.when(record.get(Mockito.eq(0))).thenAnswer(invocation -> Values.value(2));
    // act
    id = provider.generate();
    // assert
    Assert.assertNotNull("Invalid identifier value", id);
    Assert.assertEquals("Provider returned an invalid identifier value", 2L, (long)id);
}
 
Example #8
Source File: Neo4jConversionsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
static void assertRead(String label, String attribute, Object t) {
	try (Session session = neo4jConnectionSupport.getDriver().session()) {
		Value v = session.run("MATCH (n) WHERE labels(n) = [$label] RETURN n[$attribute] as r",
			Values.parameters("label", label, "attribute", attribute)).single().get("r");

		TypeDescriptor typeDescriptor = TypeDescriptor.forObject(t);
		if (typeDescriptor.isCollection()) {
			Collection<?> collection = (Collection<?>) t;
			Class<?> targetType = collection.stream().map(Object::getClass).findFirst().get();
			List<Object> convertedObjects = v.asList(elem -> DEFAULT_CONVERSION_SERVICE.convert(elem, targetType));
			assertThat(convertedObjects).containsAll(collection);
		} else {
			Object converted = DEFAULT_CONVERSION_SERVICE.convert(v, typeDescriptor.getType());
			assertThat(converted).isEqualTo(t);
		}
	}
}
 
Example #9
Source File: Neo4jConversionsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void additionalTypes() {

	byte b = DEFAULT_CONVERSION_SERVICE.convert(Values.value(new byte[] { 6 }), byte.class);
	assertThat(b).isEqualTo((byte) 6);

	char c = DEFAULT_CONVERSION_SERVICE.convert(Values.value("x"), char.class);
	assertThat(c).isEqualTo('x');

	float f = DEFAULT_CONVERSION_SERVICE.convert(Values.value("23.42"), float.class);
	assertThat(f).isEqualTo(23.42F);

	int i = DEFAULT_CONVERSION_SERVICE.convert(Values.value(42), int.class);
	assertThat(i).isEqualTo(42);

	short s = DEFAULT_CONVERSION_SERVICE.convert(Values.value((short) 127), short.class);
	assertThat(s).isEqualTo((short) 127);
}
 
Example #10
Source File: Neo4JEdgeWhileRemoveTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void givenInDirectionShouldGetVertex() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(relationship.get(Mockito.eq("id"))).thenAnswer(invocation -> Values.value(1L));
    Mockito.when(relationship.type()).thenAnswer(invocation -> "label");
    Mockito.when(relationship.keys()).thenAnswer(invocation -> Collections.singleton("key1"));
    Mockito.when(relationship.get(Mockito.eq("key1"))).thenAnswer(invocation -> Values.value("value1"));
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    Neo4JEdge edge = new Neo4JEdge(graph, session, provider, outVertex, relationship, inVertex);
    // act
    edge.remove();
    // assert
    Mockito.verify(transaction).readWrite();
    Mockito.verify(session).removeEdge(Mockito.eq(edge), Mockito.eq(true));
}
 
Example #11
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Override
void setupData(Transaction transaction) {
	ZonedDateTime createdAt = LocalDateTime.of(2019, 1, 1, 23, 23, 42, 0).atZone(ZoneOffset.UTC.normalized());
	id1 = transaction.run("" +
			"CREATE (n:PersonWithAllConstructor) " +
			"  SET n.name = $name, n.sameValue = $sameValue, n.first_name = $firstName, n.cool = $cool, n.personNumber = $personNumber, n.bornOn = $bornOn, n.nullable = 'something', n.things = ['a', 'b'], n.place = $place, n.createdAt = $createdAt "
			+
			"RETURN id(n)",
		Values.parameters("name", TEST_PERSON1_NAME, "sameValue", TEST_PERSON_SAMEVALUE, "firstName",
			TEST_PERSON1_FIRST_NAME, "cool", true, "personNumber", 1, "bornOn", TEST_PERSON1_BORN_ON, "place",
			NEO4J_HQ, "createdAt", createdAt)
	).next().get(0).asLong();
	transaction
		.run("CREATE (a:Thing {theId: 'anId', name: 'Homer'})-[:Has]->(b:Thing2{theId: 4711, name: 'Bart'})");
	IntStream.rangeClosed(1, 20).forEach(i ->
		transaction.run("CREATE (a:Thing {theId: 'id' + $i, name: 'name' + $i})",
			Values.parameters("i", String.format("%02d", i))));

	person1 = new PersonWithAllConstructor(id1, TEST_PERSON1_NAME, TEST_PERSON1_FIRST_NAME,
		TEST_PERSON_SAMEVALUE,
		true, 1L, TEST_PERSON1_BORN_ON, "something", Arrays.asList("a", "b"), NEO4J_HQ, createdAt.toInstant());
}
 
Example #12
Source File: StringlyTypedDynamicRelationshipsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test // GH-216
void shouldWriteDynamicCollectionRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithStringlyTypedRelatives newPerson = new PersonWithStringlyTypedRelatives("Test");
	Map<String, List<Pet>> pets = newPerson.getPets();

	List<Pet> monsters = pets.computeIfAbsent("MONSTERS", s -> new ArrayList<>());
	monsters.add(new Pet("Godzilla"));
	monsters.add(new Pet("King Kong"));

	List<Pet> fish = pets.computeIfAbsent("FISH", s -> new ArrayList<>());
	fish.add(new Pet("Nemo"));

	newPerson = repository.save(newPerson);
	pets = newPerson.getPets();
	assertThat(pets).containsOnlyKeys("MONSTERS", "FISH");

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
			+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
			+ "RETURN size((t)-->(:Pet))"
			+ " as numberOfRelations", Values.parameters("id", newPerson.getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(3L);
	}
}
 
Example #13
Source File: CallbacksITBase.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
protected void verifyDatabase(Iterable<ThingWithAssignedId> expectedValues) {

		List<String> ids = StreamSupport.stream(expectedValues.spliterator(), false)
			.map(ThingWithAssignedId::getTheId).collect(toList());
		List<String> names = StreamSupport.stream(expectedValues.spliterator(), false)
			.map(ThingWithAssignedId::getName).collect(toList());
		try (Session session = driver.session()) {
			Record record = session
				.run("MATCH (n:Thing) WHERE n.theId in $ids RETURN COLLECT(n) as things", Values.parameters("ids", ids))
				.single();

			List<Node> nodes = record.get("things").asList(Value::asNode);
			assertThat(nodes).extracting(n -> n.get("theId").asString()).containsAll(ids);
			assertThat(nodes).extracting(n -> n.get("name").asString())
				.containsAll(names);
		}
	}
 
Example #14
Source File: Neo4JEdgeWhileVerticesTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void givenInOutDirectionsShouldGetVertices() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(relationship.get(Mockito.eq("id"))).thenAnswer(invocation -> Values.value(1L));
    Mockito.when(relationship.type()).thenAnswer(invocation -> "label");
    Mockito.when(relationship.keys()).thenAnswer(invocation -> Collections.singleton("key1"));
    Mockito.when(relationship.get(Mockito.eq("key1"))).thenAnswer(invocation -> Values.value("value1"));
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    Neo4JEdge edge = new Neo4JEdge(graph, session, provider, outVertex, relationship, inVertex);
    // act
    Iterator<Vertex> vertices = edge.bothVertices();
    // assert
    Mockito.verify(transaction).readWrite();
    Assert.assertNotNull("Failed to get edge vertex", vertices);
    Assert.assertTrue("Empty iterator", vertices.hasNext());
    vertices.next();
    Assert.assertTrue("Iterator with only one vertex", vertices.hasNext());
    vertices.next();
    Assert.assertFalse("Iterator with too many vertices", vertices.hasNext());
}
 
Example #15
Source File: ReactiveNeo4jOperationsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setupData() {

	Transaction transaction = driver.session(getSessionConfig()).beginTransaction();
	transaction.run("MATCH (n) detach delete n");

	person1Id = transaction.run("CREATE (n:PersonWithAllConstructor) SET n.name = $name RETURN id(n)",
		Values.parameters("name", TEST_PERSON1_NAME)
	).next().get(0).asLong();
	person2Id = transaction.run("CREATE (n:PersonWithAllConstructor) SET n.name = $name RETURN id(n)",
		Values.parameters("name", TEST_PERSON2_NAME)
	).next().get(0).asLong();

	transaction.commit();
	transaction.close();
}
 
Example #16
Source File: Neo4JEdgeWhileAddingPropertyValueTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void givenPropertyValueShouldAddItToEdge() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(relationship.get(Mockito.eq("id"))).thenAnswer(invocation -> Values.value(1L));
    Mockito.when(relationship.type()).thenAnswer(invocation -> "label");
    Mockito.when(relationship.keys()).thenAnswer(invocation -> Collections.singleton("key1"));
    Mockito.when(relationship.get(Mockito.eq("key1"))).thenAnswer(invocation -> Values.value("value1"));
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    Neo4JEdge edge = new Neo4JEdge(graph, session, provider, outVertex, relationship, inVertex);
    // act
    Property<?> result = edge.property("p1", 1L);
    // assert
    Assert.assertNotNull("Failed to add property to edge", result);
    Assert.assertTrue("Property value is not present", result.isPresent());
    Assert.assertTrue("Failed to set edge as dirty", edge.isDirty());
    Assert.assertEquals("Invalid property value", result.value(), 1L);
}
 
Example #17
Source File: Neo4JEdgeWhileGettingPropertyValueTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void givenEdgeWithPropertyValueShouldShouldGetPropertyValue() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(relationship.get(Mockito.eq("id"))).thenAnswer(invocation -> Values.value(1L));
    Mockito.when(relationship.type()).thenAnswer(invocation -> "label");
    Mockito.when(relationship.keys()).thenAnswer(invocation -> Collections.singleton("key1"));
    Mockito.when(relationship.get(Mockito.eq("key1"))).thenAnswer(invocation -> Values.value("value1"));
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    Neo4JEdge edge = new Neo4JEdge(graph, session, provider, outVertex, relationship, inVertex);
    edge.property("p1", 1L);
    // act
    Property<?> result = edge.property("p1");
    // assert
    Assert.assertNotNull("Failed to get property value", result);
    Assert.assertTrue("Property value is not present", result.isPresent());
    Assert.assertEquals("Invalid property key", result.key(), "p1");
    Assert.assertEquals("Invalid property value", result.value(), 1L);
    Assert.assertEquals("Invalid property element", result.element(), edge);
}
 
Example #18
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void saveSingleEntity(@Autowired PersonRepository repository) {

	PersonWithAllConstructor person = new PersonWithAllConstructor(null, "Mercury", "Freddie", "Queen", true,
		1509L,
		LocalDate.of(1946, 9, 15), null, Arrays.asList("b", "a"), null, null);
	PersonWithAllConstructor savedPerson = repository.save(person);
	try (Session session = createSession()) {
		Record record = session
			.run("MATCH (n:PersonWithAllConstructor) WHERE n.first_name = $first_name RETURN n",
				Values.parameters("first_name", "Freddie")).single();

		assertThat(record.containsKey("n")).isTrue();
		Node node = record.get("n").asNode();
		assertThat(savedPerson.getId()).isEqualTo(node.id());
		assertThat(node.get("things").asList()).containsExactly("b", "a");
	}
}
 
Example #19
Source File: Neo4jOperationsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setupData() {

	Transaction transaction = driver.session(getSessionConfig()).beginTransaction();
	transaction.run("MATCH (n) detach delete n");

	person1Id = transaction.run("CREATE (n:PersonWithAllConstructor) SET n.name = $name RETURN id(n)",
		Values.parameters("name", TEST_PERSON1_NAME)
	).next().get(0).asLong();
	person2Id = transaction.run("CREATE (n:PersonWithAllConstructor) SET n.name = $name RETURN id(n)",
		Values.parameters("name", TEST_PERSON2_NAME)
	).next().get(0).asLong();

	transaction.commit();
	transaction.close();
}
 
Example #20
Source File: SingleValueMappingFunctionTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldCheckReturnType() {

	when(record.size()).thenReturn(1);
	when(record.get(0)).thenReturn(Values.value("Guten Tag."));

	SingleValueMappingFunction<Period> mappingFunction = new SingleValueMappingFunction<>(conversionService, Period.class);
	assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> mappingFunction.apply(typeSystem, record))
		.withMessageStartingWith("Failed to convert from type [org.neo4j.driver.internal.value.StringValue] to type [java.time.Period] for value '\"Guten Tag.\"'");
}
 
Example #21
Source File: Neo4jClientTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void reading() {

	prepareMocks();

	when(session.run(anyString(), anyMap())).thenReturn(result);
	when(result.stream()).thenReturn(Stream.of(record1));
	when(record1.get("name")).thenReturn(Values.value("michael"));

	Neo4jClient client = Neo4jClient.create(driver);

	String cypher = "MATCH (o:User {name: $name}) - [:OWNS] -> (b:Bike)" +
		"RETURN o, collect(b) as bikes";

	BikeOwnerReader mappingFunction = new BikeOwnerReader();
	Collection<BikeOwner> bikeOwners = client
		.query(cypher)
		.bind("michael").to("name")
		.fetchAs(BikeOwner.class).mappedBy(mappingFunction)
		.all();

	assertThat(bikeOwners).hasSize(1).first()
		.hasFieldOrPropertyWithValue("name", "michael");

	verifyDatabaseSelection(null);

	Map<String, Object> expectedParameters = new HashMap<>();
	expectedParameters.put("name", "michael");

	verify(session).run(eq(cypher), argThat(new MapAssertionMatcher(expectedParameters)));
	verify(result).stream();
	verify(record1).get("name");
	verify(session).close();
}
 
Example #22
Source File: ReactiveStringlyTypeDynamicRelationshipsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldWriteDynamicRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithStringlyTypedRelatives newPerson = new PersonWithStringlyTypedRelatives("Test");
	Person d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R1");
	newPerson.getRelatives().put("RELATIVE_1", d);
	d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R2");
	newPerson.getRelatives().put("RELATIVE_2", d);

	List<PersonWithStringlyTypedRelatives> recorded = new ArrayList<>();
	repository.save(newPerson)
		.as(StepVerifier::create)
		.recordWith(() -> recorded)
		.consumeNextWith(personWithRelatives -> {
			Map<String, Person> relatives = personWithRelatives.getRelatives();
			assertThat(relatives).containsOnlyKeys("RELATIVE_1", "RELATIVE_2");
		})
		.verifyComplete();

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
				+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
				+ "RETURN size((t)-->(:Person))"
				+ " as numberOfRelations",
			Values.parameters("id", recorded.get(0).getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(2L);
	}
}
 
Example #23
Source File: MovieRepository.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
public Mono<Movie> findByTitle(String title) {
	return Mono.using(driver::rxSession,
		session -> Mono.from(
			session.run("MATCH (m:Movie {title: $title}) RETURN m", Values.parameters("title", title))
				.records()).map(MovieRepository::mapToMovie),
		RxSession::close);
}
 
Example #24
Source File: Neo4jQuerySupport.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * Converts parameter as needed by the query generated, which is not covered by standard conversion services.
 *
 * @param parameter The parameter to fit into the generated query.
 * @return A parameter that fits the place holders of a generated query
 */
final Object convertParameter(Object parameter) {

	if (parameter == null) {
		// According to https://neo4j.com/docs/cypher-manual/current/syntax/working-with-null/#cypher-null-intro
		// it does not make any sense to continue if a `null` value gets into a comparison
		// but we just warn the users and do not throw an exception on `null`.
		log.warn("Do not use `null` as a property value for comparison."
			+ " It will always be false and return an empty result.");

		return Values.NULL;
	}

	// Maybe move all of those into Neo4jConverter at some point.
	if (parameter instanceof Range) {
		return convertRange((Range) parameter);
	} else if (parameter instanceof Distance) {
		return calculateDistanceInMeter((Distance) parameter);
	} else if (parameter instanceof Circle) {
		return convertCircle((Circle) parameter);
	} else if (parameter instanceof Instant) {
		return ((Instant) parameter).atOffset(ZoneOffset.UTC);
	} else if (parameter instanceof Box) {
		return convertBox((Box) parameter);
	} else if (parameter instanceof BoundingBox) {
		return convertBoundingBox((BoundingBox) parameter);
	}

	// Good hook to check the NodeManager whether the thing is an entity and we replace the value with a known id.
	return mappingContext.getConverter()
		.writeValueFromProperty(parameter, ClassTypeInformation.from(parameter.getClass()));
}
 
Example #25
Source File: ReactiveDynamicRelationshipsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldWriteDynamicRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithRelatives newPerson = new PersonWithRelatives("Test");
	Person d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R1");
	newPerson.getRelatives().put(TypeOfRelative.RELATIVE_1, d);
	d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R2");
	newPerson.getRelatives().put(TypeOfRelative.RELATIVE_2, d);

	List<PersonWithRelatives> recorded = new ArrayList<>();
	repository.save(newPerson)
		.as(StepVerifier::create)
		.recordWith(() -> recorded)
		.consumeNextWith(personWithRelatives -> {
			Map<TypeOfRelative, Person> relatives = personWithRelatives.getRelatives();
			assertThat(relatives).containsOnlyKeys(TypeOfRelative.RELATIVE_1, TypeOfRelative.RELATIVE_2);
		})
		.verifyComplete();

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
				+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
				+ "RETURN size((t)-->(:Person))"
				+ " as numberOfRelations",
			Values.parameters("id", recorded.get(0).getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(2L);
	}
}
 
Example #26
Source File: IdGeneratorsITBase.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@BeforeEach
protected void setupData() {
	try (Transaction transaction = driver.session().beginTransaction()) {
		transaction.run("MATCH (n) detach delete n");
		transaction.run("CREATE (t:ThingWithGeneratedId {name: $name, theId: $theId}) RETURN id(t) as id",
			Values.parameters("name", EXISTING_THING_NAME, "theId", ID_OF_EXISTING_THING));
		transaction.commit();
	}
}
 
Example #27
Source File: AuditingITBase.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
protected void verifyDatabase(long id, ImmutableAuditableThing expectedValues) {

		try (Session session = driver.session()) {
			Node node = session
				.run("MATCH (t:ImmutableAuditableThing) WHERE id(t) = $id RETURN t", Values.parameters("id", id))
				.single().get("t").asNode();

			assertDataMatch(expectedValues, node);
		}
	}
 
Example #28
Source File: AuditingITBase.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
protected void verifyDatabase(String id, ImmutableAuditableThingWithGeneratedId expectedValues) {

		try (Session session = driver.session()) {
			Node node = session
				.run("MATCH (t:ImmutableAuditableThingWithGeneratedId) WHERE t.id = $id RETURN t",
					Values.parameters("id", id))
				.single().get("t").asNode();

			assertDataMatch(expectedValues, node);
		}
	}
 
Example #29
Source File: ThingWithCustomTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {

	if (Value.class.isAssignableFrom(sourceType.getType())) {
		return CustomType.of(((Value) source).asString());
	} else {
		return Values.value(((DifferentType) source).getValue());
	}
}
 
Example #30
Source File: IdGeneratorsITBase.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
protected void verifyDatabase(String id, String name) {

		try (Session session = driver.session()) {
			Node node = session
				.run("MATCH (t) WHERE t.theId = $theId RETURN t",
					Values.parameters("theId", id))
				.single().get("t").asNode();

			assertThat(node.get("name").asString()).isEqualTo(name);
			assertThat(node.get("theId").asString()).isEqualTo(id);
		}
	}