org.neo4j.driver.Value Java Examples

The following examples show how to use org.neo4j.driver.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: ResultSummaryLogger.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
private void process(ProfiledPlan profilePlan, int indentationLevel) {
    // create details instance
    ProfileInformationDetails information = new ProfileInformationDetails();
    // operator
    information.operator = printOperator(profilePlan.operatorType(), indentationLevel);
    // arguments
    Map<String, Value> arguments = profilePlan.arguments();
    // compile information
    information.indentationLevel = indentationLevel;
    information.estimatedRows = printEstimatedRows(arguments.get("EstimatedRows"));
    information.rows = String.format(Locale.US, "%d", profilePlan.records());
    information.dbHits = String.format(Locale.US, "%d", profilePlan.dbHits());
    information.variables = profilePlan.identifiers().stream().map(String::trim).collect(Collectors.joining(", "));
    information.otherInformation = printOtherInformation(arguments);
    // append to list
    add(information);
    // children
    List<ProfiledPlan> children = profilePlan.children();
    // process children (backwards)
    for (int i = children.size() - 1; i >= 0; i--) {
        // current child
        ProfiledPlan child = children.get(i);
        // process child
        process(child, indentationLevel + i);
    }
}
 
Example #2
Source File: DefaultNeo4jConverter.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Override
public Value writeValueFromProperty(@Nullable Object value, TypeInformation<?> type) {

	if (value == null) {
		return Values.NULL;
	}

	if (isCollection(type)) {
		Collection<?> sourceCollection = (Collection<?>) value;
		Object[] targetCollection = (sourceCollection).stream().map(element ->
			conversionService.convert(element, Value.class)).toArray();
		return Values.value(targetCollection);
	}

	return conversionService.convert(value, Value.class);
}
 
Example #3
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 #4
Source File: StatementBatchBuilder.java    From extended-objects with Apache License 2.0 6 votes vote down vote up
@Override
public void close() {
    for (Map.Entry<String, BatchEntry> entry : batches.entrySet()) {
        String statement = entry.getKey();
        BatchEntry batchEntry = entry.getValue();
        List<Value> batch = batchEntry.getBatch();
        if (!batch.isEmpty()) {
            String batchStatement = "UNWIND $batch as entry " + statement;
            Record result = statementExecutor.getSingleResult(batchStatement, parameters("batch", batch));
            Callback callback = batchEntry.getCallback();
            if (callback != null) {
                callback.process(result);
            }
        }
    }
    batches.clear();
}
 
Example #5
Source File: DynamicLabelsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
protected final List<String> getLabels(Condition idCondition, Object id) {

			Node n = Cypher.anyNode("n");
			String cypher = Renderer.getDefaultRenderer().render(Cypher
				.match(n)
				.where(idCondition).and(not(exists(n.property("moreLabels"))))
				.returning(n.labels().as("labels"))
				.build()
			);

			try (Session session = driver.session()) {
				return session
					.readTransaction(tx -> tx
						.run(cypher, Collections.singletonMap("id", id))
						.single().get("labels")
						.asList(Value::asString)
					);
			}
		}
 
Example #6
Source File: AuditingITBase.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
private void assertDataMatch(AuditableThing expectedValues, Node node) {
	assertThat(node.get("name").asString()).isEqualTo(expectedValues.getName());
	assertThat(node.get("createdAt").asLocalDateTime()).isEqualTo(expectedValues.getCreatedAt());
	assertThat(node.get("createdBy").asString()).isEqualTo(expectedValues.getCreatedBy());

	Value modifiedAt = node.get("modifiedAt");
	Value modifiedBy = node.get("modifiedBy");

	if (expectedValues.getModifiedAt() == null) {
		assertThat(modifiedAt.isNull()).isTrue();
	} else {
		assertThat(modifiedAt.asLocalDateTime()).isEqualTo(expectedValues.getModifiedAt());
	}

	if (expectedValues.getModifiedBy() == null) {
		assertThat(modifiedBy.isNull()).isTrue();
	} else {
		assertThat(modifiedBy.asString()).isEqualTo(expectedValues.getModifiedBy());
	}
}
 
Example #7
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 #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
static void assertWrite(String label, String attribute, Object t) {

		Value driverValue;
		if (t != null && Collection.class.isAssignableFrom(t.getClass())) {
			Collection<?> sourceCollection = (Collection<?>) t;
			Object[] targetCollection = (sourceCollection).stream().map(element ->
				DEFAULT_CONVERSION_SERVICE.convert(element, Value.class)).toArray();
			driverValue = Values.value(targetCollection);
		} else {
			driverValue = DEFAULT_CONVERSION_SERVICE.convert(t, Value.class);
		}

		try (Session session = neo4jConnectionSupport.getDriver().session()) {
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("label", label);
			parameters.put("attribute", attribute);
			parameters.put("v", driverValue);

			long cnt = session
				.run("MATCH (n) WHERE labels(n) = [$label]  AND n[$attribute] = $v RETURN COUNT(n) AS cnt",
					parameters)
				.single().get("cnt").asLong();
			assertThat(cnt).isEqualTo(1L);
		}
	}
 
Example #10
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
public Iterator<Vertex> vertices(String statement, Value parameters) {
    Objects.requireNonNull(statement, "statement cannot be null");
    Objects.requireNonNull(parameters, "parameters cannot be null");
    // get current session
    Neo4JSession session = currentSession();
    // transaction should be ready for io operations
    transaction.readWrite();
    // execute statement
    Result result = session.executeStatement(statement, parameters);
    // find vertices
    Iterator<Vertex> iterator = session.vertices(result)
        .collect(Collectors.toCollection(LinkedList::new))
        .iterator();
    // process summary (query has been already consumed by collect)
    ResultSummaryLogger.log(result.consume());
    // return iterator
    return iterator;
}
 
Example #11
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
public Iterator<Edge> edges(String statement, Value parameters) {
    Objects.requireNonNull(statement, "statement cannot be null");
    Objects.requireNonNull(parameters, "parameters cannot be null");
    // get current session
    Neo4JSession session = currentSession();
    // transaction should be ready for io operations
    transaction.readWrite();
    // execute statement
    Result result = session.executeStatement(statement, parameters);
    // find edges
    Iterator<Edge> iterator = session.edges(result)
        .collect(Collectors.toCollection(LinkedList::new))
        .iterator();
    // process summary (query has been already consumed by collect)
    ResultSummaryLogger.log(result.consume());
    // return iterator
    return iterator;
}
 
Example #12
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void updateSingleEntity(@Autowired ReactivePersonRepository repository) {

	Mono<PersonWithAllConstructor> operationUnderTest = repository.findById(id1)
		.map(originalPerson -> {
			originalPerson.setFirstName("Updated first name");
			originalPerson.setNullable("Updated nullable field");
			return originalPerson;
		})
		.flatMap(repository::save);

	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.expectNextCount(1L)
		.verifyComplete();

	Flux
		.usingWhen(
			Mono.fromSupplier(() -> createRxSession()),
			s -> {
				Value parameters = parameters("id", id1);
				return s.run("MATCH (n:PersonWithAllConstructor) WHERE id(n) = $id RETURN n", parameters).records();
			},
			RxSession::close
		)
		.map(r -> r.get("n").asNode())
		.as(StepVerifier::create)
		.expectNextMatches(node -> node.get("first_name").asString().equals("Updated first name") &&
			node.get("nullable").asString().equals("Updated nullable field"))
		.verifyComplete();
}
 
Example #13
Source File: AdditionalTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static Value value(Short aShort) {
	if (aShort == null) {
		return Values.NULL;
	}

	return Values.value(aShort.longValue());
}
 
Example #14
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveAllIterableWithAssignedId(@Autowired ReactiveThingRepository repository) {

	ThingWithAssignedId existingThing = new ThingWithAssignedId("anId");
	existingThing.setName("Updated name.");
	ThingWithAssignedId newThing = new ThingWithAssignedId("aaBB");
	newThing.setName("That's the thing.");

	List<ThingWithAssignedId> things = Arrays.asList(existingThing, newThing);

	Flux<ThingWithAssignedId> operationUnderTest = repository.saveAll(things);

	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.expectNextCount(2L)
		.verifyComplete();

	Flux
		.usingWhen(
			Mono.fromSupplier(() -> createRxSession()),
			s -> {
				Value parameters = parameters("ids", Arrays.asList("anId", "aaBB"));
				return s.run("MATCH (n:Thing) WHERE n.theId IN ($ids) RETURN n.name as name ORDER BY n.name ASC",
					parameters)
					.records();
			},
			RxSession::close
		)
		.map(r -> r.get("name").asString())
		.as(StepVerifier::create)
		.expectNext("That's the thing.")
		.expectNext("Updated name.")
		.verifyComplete();

	// Make sure we triggered on insert, one update
	repository.count().as(StepVerifier::create).expectNext(22L).verifyComplete();
}
 
Example #15
Source File: SpatialTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static Point[] asPointArray(Value value) {
	Point[] array = new Point[value.size()];
	int i = 0;
	for (Point v : value.values(SpatialTypes::asSpringDataPoint)) {
		array[i++] = v;
	}
	return array;
}
 
Example #16
Source File: Neo4jOperationsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void save() {
	ThingWithGeneratedId testThing = neo4jOperations.save(new ThingWithGeneratedId("testThing"));

	assertThat(testThing.getTheId()).isNotNull();

	try (Session session = driver.session(getSessionConfig())) {
		Result result = session.run("MATCH (t:ThingWithGeneratedId{name: 'testThing'}) return t");
		Value resultValue = result.single().get("t");
		assertThat(resultValue).isNotNull();
		assertThat(resultValue.asMap().get("name")).isEqualTo("testThing");
	}
}
 
Example #17
Source File: ReactiveNeo4jOperationsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void save() {
	StepVerifier.create(neo4jOperations.save(new ThingWithGeneratedId("testThing")))
		.expectNextCount(1)
		.verifyComplete();

	try (Session session = driver.session(getSessionConfig())) {
		Result result = session.run("MATCH (t:ThingWithGeneratedId{name: 'testThing'}) return t");
		Value resultValue = result.single().get("t");
		assertThat(resultValue).isNotNull();
		assertThat(resultValue.asMap().get("name")).isEqualTo("testThing");
	}
}
 
Example #18
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveAll(@Autowired PersonRepository repository) {

	PersonWithAllConstructor newPerson = new PersonWithAllConstructor(null, "Mercury", "Freddie", "Queen", true,
		1509L,
		LocalDate.of(1946, 9, 15), null, emptyList(), null, null);

	PersonWithAllConstructor existingPerson = repository.findById(id1).get();
	existingPerson.setFirstName("Updated first name");
	existingPerson.setNullable("Updated nullable field");

	assertThat(repository.count()).isEqualTo(1);

	List<Long> ids = StreamSupport
		.stream(repository.saveAll(Arrays.asList(existingPerson, newPerson)).spliterator(), false)
		.map(PersonWithAllConstructor::getId)
		.collect(toList());

	assertThat(repository.count()).isEqualTo(2);

	try (Session session = createSession()) {

		Record record = session
			.run(
				"MATCH (n:PersonWithAllConstructor) WHERE id(n) IN ($ids) WITH n ORDER BY n.name ASC RETURN COLLECT(n.name) as names",
				Values.parameters("ids", ids))
			.single();

		assertThat(record.containsKey("names")).isTrue();
		List<String> names = record.get("names").asList(Value::asString);
		assertThat(names).contains("Mercury", TEST_PERSON1_NAME);
	}
}
 
Example #19
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void saveAllWithAssignedId(@Autowired ThingRepository repository) {

	assertThat(repository.count()).isEqualTo(21);

	ThingWithAssignedId newThing = new ThingWithAssignedId("aaBB");
	newThing.setName("That's the thing.");

	ThingWithAssignedId existingThing = repository.findById("anId").get();
	existingThing.setName("Updated name.");

	repository.saveAll(Arrays.asList(newThing, existingThing));

	try (Session session = createSession()) {
		Record record = session
			.run(
				"MATCH (n:Thing) WHERE n.theId IN ($ids) WITH n ORDER BY n.name ASC RETURN COLLECT(n.name) as names",
				Values.parameters("ids", Arrays.asList(newThing.getTheId(), existingThing.getTheId())))
			.single();

		assertThat(record.containsKey("names")).isTrue();
		List<String> names = record.get("names").asList(Value::asString);
		assertThat(names).containsExactly(newThing.getName(), existingThing.getName());

		assertThat(repository.count()).isEqualTo(22);
	}
}
 
Example #20
Source File: SingleValueMappingFunction.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public T apply(TypeSystem typeSystem, Record record) {

	if (record.size() == 0) {
		throw new IllegalArgumentException("Record has no elements, cannot map nothing.");
	}

	if (record.size() > 1) {
		throw new IllegalArgumentException(
			"Records with more than one value cannot be converted without a mapper.");
	}

	Value source = record.get(0);
	return source == null || source == Values.NULL ? null : conversionService.convert(source, targetClass);
}
 
Example #21
Source File: AdditionalTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static Value value(short[] aShortArray) {
	if (aShortArray == null) {
		return Values.NULL;
	}

	long[] values = new long[aShortArray.length];
	int i = 0;
	for (short v : aShortArray) {
		values[i++] = v;
	}
	return Values.value(values);
}
 
Example #22
Source File: AdditionalTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static long[] asLongArray(Value value) {
	long[] array = new long[value.size()];
	int i = 0;
	for (long v : value.values(Value::asLong)) {
		array[i++] = v;
	}
	return array;
}
 
Example #23
Source File: ThingWithCustomTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
	Set<ConvertiblePair> convertiblePairs = new HashSet<>();
	convertiblePairs.add(new ConvertiblePair(Value.class, DifferentType.class));
	convertiblePairs.add(new ConvertiblePair(DifferentType.class, Value.class));
	return convertiblePairs;
}
 
Example #24
Source File: AdditionalTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static Value value(float[] aFloatArray) {
	if (aFloatArray == null) {
		return Values.NULL;
	}

	String[] values = new String[aFloatArray.length];
	int i = 0;
	for (float v : aFloatArray) {
		values[i++] = Float.toString(v);
	}
	return Values.value(values);
}
 
Example #25
Source File: AdditionalTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static float[] asFloatArray(Value value) {
	float[] array = new float[value.size()];
	int i = 0;
	for (float v : value.values(AdditionalTypes::asFloat)) {
		array[i++] = v;
	}
	return array;
}
 
Example #26
Source File: AdditionalTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static double[] asDoubleArray(Value value) {
	double[] array = new double[value.size()];
	int i = 0;
	for (double v : value.values(Value::asDouble)) {
		array[i++] = v;
	}
	return array;
}
 
Example #27
Source File: AdditionalTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static Value value(UUID uuid) {
	if (uuid == null) {
		return Values.NULL;
	}

	return Values.value(uuid.toString());
}
 
Example #28
Source File: AdditionalTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static char[] asCharArray(Value value) {
	char[] array = new char[value.size()];
	int i = 0;
	for (Character v : value.values(AdditionalTypes::asCharacter)) {
		array[i++] = v;
	}
	return array;
}
 
Example #29
Source File: AdditionalTypes.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
static boolean[] asBooleanArray(Value value) {
	boolean[] array = new boolean[value.size()];
	int i = 0;
	for (Boolean v : value.values(Value::asBoolean)) {
		array[i++] = v;
	}
	return array;
}
 
Example #30
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void updateWithAssignedId(@Autowired ThingRepository repository) {

	assertThat(repository.count()).isEqualTo(21);

	ThingWithAssignedId thing = new ThingWithAssignedId("id07");
	thing.setName("An updated thing");
	repository.save(thing);

	thing = repository.findById("id15").get();
	thing.setName("Another updated thing");
	repository.save(thing);

	try (Session session = createSession()) {
		Record record = session
			.run(
				"MATCH (n:Thing) WHERE n.theId IN ($ids) WITH n ORDER BY n.name ASC RETURN COLLECT(n.name) as names",
				Values.parameters("ids", Arrays.asList("id07", "id15")))
			.single();

		assertThat(record.containsKey("names")).isTrue();
		List<String> names = record.get("names").asList(Value::asString);
		assertThat(names).containsExactly("An updated thing", "Another updated thing");

		assertThat(repository.count()).isEqualTo(21);
	}
}