org.neo4j.driver.v1.Value Java Examples

The following examples show how to use org.neo4j.driver.v1.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: CypherTester.java    From rdf2neo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Runs a Cypher query that is supposed to return a single tuple having at least a single bound variable.
 * Passes it to the test parameter (using a {@link Value}), this should return a boolean, which is also the
 * return value for this method.
 * 
 * For instance, in the test function you might want to compare the Cypher returned value to a reference 
 * value of yours.
 */
public boolean compare ( Function<Value, Boolean> test, String cypher, Object... keyVals )
{
	final String hcypher = this.getCypherHeader () + cypher;		
	final Value result[] = new Value [] { null };
	neo4jDataManager.processCypherMatches ( 
		rec -> 
		{ 
			if ( rec.size () == 0 )
			{
				String emsg = "Test query for CypherTester.compare() must project some field";
				log.error ( "{}. Query is:\n{}", emsg, hcypher );
				throw new IllegalArgumentException ( emsg );
			}
			result [ 0 ] = rec.get ( 0 );
		},
		hcypher, 
		keyVals
	);
	
	return test.apply ( result [ 0 ] );
}
 
Example #2
Source File: Neo4jBoltPersistReader.java    From streams with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public ObjectNode apply(@Nullable Value value) {
  ObjectNode resultNode = null;
  if (value instanceof StringValue) {
    StringValue stringValue = (StringValue) value;
    String string = stringValue.asLiteralString();
    try {
      resultNode = mapper.readValue(string, ObjectNode.class);
    } catch (IOException ex) {
      LOGGER.error("IOException", ex);
    }
  } else if ( value instanceof NodeValue) {
    NodeValue nodeValue = (NodeValue) value;
    Node node = nodeValue.asNode();
    Map<String, Object> nodeMap = node.asMap();
    resultNode = PropertyUtil.getInstance(mapper).unflattenMap(nodeMap);
  } else if (value instanceof RelationshipValue) {
    RelationshipValue relationshipValue = (RelationshipValue) value;
    Relationship relationship = relationshipValue.asRelationship();
    Map<String, Object> relationshipMap = relationship.asMap();
    resultNode = PropertyUtil.getInstance(mapper).unflattenMap(relationshipMap);
  }
  return resultNode;
}
 
Example #3
Source File: QueryRunner.java    From neoprofiler with Apache License 2.0 6 votes vote down vote up
public Value runQuerySingleResult(NeoProfiler parent, String query, String columnReturn) {		
	Session s = parent.getDriver().session();

	try ( Transaction tx = s.beginTransaction()) {
		// log.info(query);
		StatementResult result = tx.run(query);
					
		if(result.hasNext()) {
			Value val = result.next().get(columnReturn);
			return val;
		}
		
		return null;
	} finally {
		s.close();
	}
}
 
Example #4
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 6 votes vote down vote up
private Entity getPropertiesObject(long id, int rowIndex, ElemType typ) {
	Record rec = this.records.get(rowIndex);
	List<Pair<String, Value>> flds = rec.fields();
	for (Pair<String, Value> pair : flds) {
		if (typ == ElemType.NODE && pair.value() instanceof NodeValue) {
			Node nd = pair.value().asNode();
			if (nd.id() == id)
				return nd;
		} else if (typ == ElemType.RELATION && pair.value() instanceof RelationshipValue) {
			Relationship rel = pair.value().asRelationship();
			if (rel.id() == id)
				return rel;
		}
	}
	
	// element with id may not have been loaded
	return this.reloaded.getEntity(id, typ);
}
 
Example #5
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 6 votes vote down vote up
@Override
public PathInfo getPathInfo(String colKey) {
	PathInfo pathInfo = null;
	Value val;
	try {
		val = this.record.get(colKey);
	} catch (NoSuchRecordException e) {
		throw new RuntimeException("no result column: " + colKey);
	}
	String typName = val.type().name();
	if ("PATH".equals(typName)) {
		Path p = val.asPath();
		long startId = p.start().id();
		long endId = p.end().id();
		List<Long> relIds = new ArrayList<Long>();
		Iterator<Relationship> it = p.relationships().iterator();
		while(it.hasNext()) {
			Relationship rel = it.next();
			relIds.add(Long.valueOf(rel.id()));
		}
		pathInfo = new PathInfo(startId, endId, relIds, p);
	}
	return pathInfo;
}
 
Example #6
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> void addValue(String colKey, List<T> vals) {
	Value val;
	try {
		val = this.record.get(colKey);
	} catch (NoSuchRecordException e) {
		throw new RuntimeException("no result column: " + colKey);
	}
	Object v = convertContentValue(val);
	if (v != null)
		vals.add((T) v);
	else {
		if (ResultHandler.includeNullValues.get().booleanValue() 
				|| ResultSettings.includeNullValuesAndDuplicates.get().booleanValue())
			vals.add((T) v);
	}
}
 
Example #7
Source File: ResultHandler.java    From jcypher with Apache License 2.0 6 votes vote down vote up
public static ElementInfo fromRecordValue(Value val) {
	if (val instanceof ListValue)
		return ElementInfo.fromRecordValue(((ListValue)val).get(0));
	ElementInfo ret = null;
	if (val != null) {
		String typName = val.type().name(); // NODE, RELATIONSHIP, NULL
		if ("NODE".equals(typName)) {
			ret = new ElementInfo();
			ret.isNull = false;
			ret.id = val.asNode().id();
			ret.type = ElemType.NODE;
		} else if ("RELATIONSHIP".equals(typName)) {
			ret = new ElementInfo();
			ret.isNull = false;
			ret.id = val.asRelationship().id();
			ret.type = ElemType.RELATION;
		} else if ("NULL".equals(typName))
			ret = ElementInfo.nullElement();
	}
	return ret;
}
 
Example #8
Source File: JavaEnhancement.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
private void enhanceNode(Record record) {
	Node node = record.get("n").asNode();
	Value fqnValue = node.get("fqn");
	String fqn = fqnValue.asString();
	if (fqnValue.isNull()) {
		Node container = connector.executeRead(
			"MATCH (n)<-[:DECLARES]-(container) " +
			"WHERE ID(n) = " + node.id() + " " +
			"RETURN container"
		).single().get("container").asNode();
		String containerFqn = container.get("fqn").asString();
		String name = node.get("name").asString();
		String signature = node.get("signature").asString();
		int index = signature.indexOf(" ") + 1;
		if (node.hasLabel("Method")) {
			int indexOfBracket = signature.indexOf("(");
			if (name.isEmpty()) {
				name = signature.substring(index, indexOfBracket);
			}
			fqn = containerFqn + "." + signature.substring(index);
		} else {
			if (name.isEmpty()) {
				name = signature.substring(index);
			}
			fqn = containerFqn + "." + name;
		}
		connector.executeWrite(
	"MATCH (n) WHERE ID(n) = " + node.id() + " SET n.name = '" + name + "', n.fqn = '" + fqn + "'");
	}
	connector.executeWrite(
"MATCH (n) WHERE ID(n) = " + node.id() + " SET n.hash = '" + createHash(fqn) + "'"
	);
}
 
Example #9
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 5 votes vote down vote up
@Override
public ElementInfo getElementInfo(String colKey) {
	Value val;
	try {
		val = this.record.get(colKey);
	} catch (NoSuchRecordException e) {
		throw new RuntimeException("no result column: " + colKey);
	}
	return ElementInfo.fromRecordValue(val);
}
 
Example #10
Source File: ResultHandler.java    From jcypher with Apache License 2.0 5 votes vote down vote up
public static RelationInfo fromRecordValue(Value val) {
	if (val instanceof ListValue)
		return RelationInfo.fromRecordValue(((ListValue)val).get(0));
	RelationInfo ret = null;
	if (val != null) {
		String typName = val.type().name(); // must be: RELATIONSHIP
		if ("RELATIONSHIP".equals(typName)) {
			ret = new RelationInfo();
			ret.startNodeId = val.asRelationship().startNodeId();
			ret.endNodeId = val.asRelationship().endNodeId();
		}
	}
	return ret;
}
 
Example #11
Source File: RemoteDBAccess.java    From jcypher with Apache License 2.0 5 votes vote down vote up
@Override
public void setAuth(AuthToken authToken) {
	if (authToken instanceof InternalAuthToken) {
		Map<String, Value> map = ((InternalAuthToken)authToken).toMap();
		Value scheme = map.get("scheme");
		if (scheme != null) {
			if ("basic".equals(scheme.asString())) {
				String uid = map.get("principal") != null ? map.get("principal").asString() : null;
				String pw = map.get("credentials") != null ? map.get("credentials").asString() : null;
				if (uid != null && pw != null)
					this.setAuth(uid, pw);
			}
		}
	}
}
 
Example #12
Source File: Neo4jCypherInterpreter.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Override
public InterpreterResult interpret(String cypherQuery, InterpreterContext interpreterContext) {
  logger.info("Opening session");
  if (StringUtils.isBlank(cypherQuery)) {
    return new InterpreterResult(Code.SUCCESS);
  }
  try {
    StatementResult result = this.neo4jConnectionManager.execute(cypherQuery,
            interpreterContext);
    Set<Node> nodes = new HashSet<>();
    Set<Relationship> relationships = new HashSet<>();
    List<String> columns = new ArrayList<>();
    List<List<String>> lines = new ArrayList<List<String>>();
    while (result.hasNext()) {
      Record record = result.next();
      List<Pair<String, Value>> fields = record.fields();
      List<String> line = new ArrayList<>();
      for (Pair<String, Value> field : fields) {
        if (field.value().hasType(InternalTypeSystem.TYPE_SYSTEM.NODE())) {
          nodes.add(field.value().asNode());
        } else if (field.value().hasType(InternalTypeSystem.TYPE_SYSTEM.RELATIONSHIP())) {
          relationships.add(field.value().asRelationship());
        } else if (field.value().hasType(InternalTypeSystem.TYPE_SYSTEM.PATH())) {
          nodes.addAll(Iterables.asList(field.value().asPath().nodes()));
          relationships.addAll(Iterables.asList(field.value().asPath().relationships()));
        } else {
          setTabularResult(field.key(), field.value(), columns, line,
                  InternalTypeSystem.TYPE_SYSTEM);
        }
      }
      if (!line.isEmpty()) {
        lines.add(line);
      }
    }
    if (!nodes.isEmpty()) {
      return renderGraph(nodes, relationships);
    } else {
      return renderTable(columns, lines);
    }
  } catch (Exception e) {
    logger.error("Exception while interpreting cypher query", e);
    return new InterpreterResult(Code.ERROR, e.getMessage());
  }
}
 
Example #13
Source File: Neo4jCypherInterpreter.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
private void addValueToLine(String key, List<String> columns, List<String> line, Object value) {
  if (!columns.contains(key)) {
    columns.add(key);
  }
  int position = columns.indexOf(key);
  if (line.size() < columns.size()) {
    for (int i = line.size(); i < columns.size(); i++) {
      line.add(null);
    }
  }
  if (value != null) {
    if (value instanceof Value) {
      Value val = (Value) value;
      if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.LIST())) {
        value = val.asList();
      } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.MAP())) {
        value = val.asMap();
      } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.POINT())) {
        value = val.asPoint();
      } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.DATE())) {
        value = val.asLocalDate();
      } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.TIME())) {
        value = val.asOffsetTime();
      } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.LOCAL_TIME())) {
        value = val.asLocalTime();
      } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.LOCAL_DATE_TIME())) {
        value = val.asLocalDateTime();
      } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.DATE_TIME())) {
        value = val.asZonedDateTime();
      } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.DURATION())) {
        value = val.asIsoDuration();
      }
    }
    if (value instanceof Collection) {
      try {
        value = jsonMapper.writer().writeValueAsString(value);
      } catch (Exception e) {
        logger.debug("ignored exception: " + e.getMessage());
      }
    }
  }
  line.set(position, value == null ? null : value.toString());
}
 
Example #14
Source File: BoltContentHandler.java    From jcypher with Apache License 2.0 4 votes vote down vote up
@Override
public RelationInfo getRelationInfo(String colKey) {
	Value val = this.record.get(colKey);
	return RelationInfo.fromRecordValue(val);
}