下面列出了org.springframework.core.convert.ConverterNotFoundException#org.neo4j.driver.Value 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
@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);
}
@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();
}
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)
);
}
}
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());
}
}
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);
}
}
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);
}
}
}
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);
}
}
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;
}
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;
}
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);
}
}
/**
* Returns the list of labels for the entity to be created from the "main" node returned.
*
* @param queryResult The complete query result
* @return The list of labels defined by the query variable {@link org.neo4j.springframework.data.core.schema.Constants#NAME_OF_LABELS}.
*/
@NonNull
private List<String> getLabels(MapAccessor queryResult) {
Value labelsValue = queryResult.get(NAME_OF_LABELS);
List<String> labels = new ArrayList<>();
if (!labelsValue.isNull()) {
labels = labelsValue.asList(Value::asString);
} else if (queryResult instanceof Node) {
Node nodeRepresentation = (Node) queryResult;
nodeRepresentation.labels().forEach(labels::add);
}
return labels;
}
private static Value extractValueOf(Neo4jPersistentProperty property, MapAccessor propertyContainer) {
if (property.isInternalIdProperty()) {
return propertyContainer instanceof Node ?
Values.value(((Node) propertyContainer).id()) :
propertyContainer.get(NAME_OF_INTERNAL_ID);
} else {
String graphPropertyName = property.getPropertyName();
return propertyContainer.get(graphPropertyName);
}
}
static Value value(UUID uuid) {
if (uuid == null) {
return Values.NULL;
}
return Values.value(uuid.toString());
}
static Value value(BigInteger bigInteger) {
if (bigInteger == null) {
return Values.NULL;
}
return Values.value(bigInteger.toString());
}
static Value value(Byte aByte) {
if (aByte == null) {
return Values.NULL;
}
return Values.value(new Byte[] { aByte });
}
static Value value(Date date) {
if (date == null) {
return Values.NULL;
}
return Values.value(DATE_TIME_FORMATTER.format(date.toInstant().atZone(ZoneOffset.UTC.normalized())));
}
public Record getSingleResult(String statement, Value parameters) {
try {
return getSingleResult(execute(statement, parameters.asMap()));
} catch (Neo4jException e) {
throw new XOException("Cannot get result for statement '" + statement + "', " + parameters.asMap(), e);
}
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return Value.class.isAssignableFrom(targetType.getType()) ? Values.NULL : null;
}
if (Value.class.isAssignableFrom(sourceType.getType())) {
return Enum.valueOf((Class<Enum>) targetType.getType(), ((Value) source).asString());
} else {
return Values.value(((Enum) source).name());
}
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
if (Value.class.isAssignableFrom(sourceType.getType())) {
return describesSupportedEnumVariant(targetType);
} else if (Value.class.isAssignableFrom(targetType.getType())) {
return describesSupportedEnumVariant(sourceType);
} else {
return false;
}
}
static Value value(Float aFloat) {
if (aFloat == null) {
return Values.NULL;
}
return Values.value(aFloat.toString());
}
static Value value(Locale locale) {
if (locale == null) {
return Values.NULL;
}
return Values.value(locale.toString());
}
static Value value(Short aShort) {
if (aShort == null) {
return Values.NULL;
}
return Values.value(aShort.longValue());
}
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;
}
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;
}
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;
}
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;
}
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);
}
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;
}
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);
}