org.neo4j.driver.v1.types.Node Java Examples

The following examples show how to use org.neo4j.driver.v1.types.Node. 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: UpdateTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateACopyOfTheCurrentStateIfPatchedWithoutStateProps() throws Throwable {
    // This is in a try-block, to make sure we close the driver after the test
    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {
        // Given
        session.run("CREATE (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'})");
        session.run("MATCH (e:Entity)-[:CURRENT]->(s:State) CREATE (e)-[:HAS_STATE {startDate:localdatetime('1988-10-27T00:00:00')}]->(s)");
        StatementResult stateResult = session.run("MATCH (s:State) RETURN s");
        Node state = stateResult.single().get("s").asNode();

        // When
        StatementResult result = session.run("MATCH (e:Entity) WITH e CALL graph.versioner.patch(e) YIELD node RETURN node");

        // Then
        Node newState = result.single().get("node").asNode();
        assertThat(state.get("key"), equalTo(newState.get("key")));
        assertThat(state.size(), equalTo(newState.size()));
    }
}
 
Example #2
Source File: City2City.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private void setBuildingAttributesOriginal(Node building, int methodCounter, int dataCounter) {
	double width;
	double length;
	double height;
	String color;
	if (dataCounter == 0) {
		width = widthMin;
		length = widthMin;
	} else {
		width = dataCounter;
		length = dataCounter;
	}
	if (methodCounter == 0) {
		height = heightMin;
	} else {
		height = methodCounter;
	}
	if (originalBuildingMetric == BuildingMetric.NOS) {
		color = NOS_colors.get(building.get("numberOfStatements").asInt(0));
	} else  {
		color = classColor;
	}
	connector.executeWrite(cypherSetBuildingSegmentAttributes(building.id(), width, length, height, color));
}
 
Example #3
Source File: UpdateTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateAndPatchANewStateWithoutAdditionalLabelAndDate() throws Throwable {
    // This is in a try-block, to make sure we close the driver after the test
    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {
        // Given
        session.run("CREATE (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'})");
        session.run("MATCH (e:Entity)-[:CURRENT]->(s:State) CREATE (e)-[:HAS_STATE {startDate:localdatetime('1988-10-27T00:00:00')}]->(s)");

        // When
        StatementResult result = session.run("MATCH (e:Entity) WITH e CALL graph.versioner.patch(e, {key:'newValue', newKey:'newestValue'}) YIELD node RETURN node");
        Node currentState = result.single().get("node").asNode();
        StatementResult countStateResult = session.run("MATCH (s:State) RETURN count(s) as s");
        StatementResult nextResult = session.run("MATCH (s1:State)-[:PREVIOUS]->(s2:State) return s2");
        StatementResult correctStateResult = session.run("MATCH (s1:State)-[:PREVIOUS]->(s2:State) WITH s1 MATCH (e:Entity)-[:CURRENT]->(s1) return e");

        // Then
        assertThat(countStateResult.single().get("s").asLong(), equalTo(2L));
        assertThat(nextResult.single().get("s2").asNode().id(), equalTo(1L));
        assertThat(correctStateResult.single().get("e").asNode().id(), equalTo(0L));
        assertThat(currentState.get("key").asString(), equalTo("newValue"));
        assertThat(currentState.get("newKey").asString(), equalTo("newestValue"));
    }
}
 
Example #4
Source File: JQA2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataEnum(Node e) {
	String belongsTo = "";
	StatementResult parent = connector.executeRead("MATCH (parent)-[:DECLARES]->(enum) WHERE ID(enum) = " + e.id() 
		+ " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	return "\"id\":            \"" + e.get("hash").asString() + "\"," +
			"\n" +
			"\"qualifiedName\": \"" + e.get("fqn").asString() + "\"," +
			"\n" +
			"\"name\":          \"" + e.get("name").asString() + "\"," +
			"\n" +
			"\"type\":          \"FAMIX.Enum\"," +
			"\n" +
			"\"modifiers\":     \"" + getModifiers(e) + "\"," +
			"\n" +
			"\"belongsTo\":     \"" + belongsTo + "\"" +
			"\n";
}
 
Example #5
Source File: InitTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateAnEntityWithPropertiesWithAStateAndItsPropertiesWithAdditionalLabelAndDate() throws Throwable {
    // This is in a try-block, to make sure we close the driver after the test
    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {
        // When
        StatementResult result = session.run("CALL graph.versioner.init('Entity', {key:'value'}, {key:'value'}, 'Error', localdatetime('1988-10-27T02:46:40'))");
        StatementResult entityResult = session.run("MATCH (e:Entity) RETURN properties(e) as props");
        StatementResult stateResult = session.run("MATCH (s:State) RETURN s");
        Node state = stateResult.single().get("s").asNode();
        StatementResult stateProps = session.run("MATCH (s:State) RETURN properties(s) as props");
        StatementResult currentResult = session.run("MATCH (e:Entity)-[:CURRENT]->(s:State) RETURN id(e) as id");
        StatementResult hasStatusResult = session.run("MATCH (e:Entity)-[:HAS_STATE]->(s:State) RETURN id(e) as id");
        StatementResult hasStatusDateResult = session.run("MATCH (e:Entity)-[rel:CURRENT]->(s:State) RETURN rel.date as date");

        // Then
        assertThat(result.single().get("node").asNode().id(), equalTo(0L));
        assertThat(entityResult.single().get("props").asMap().isEmpty(), equalTo(false));
        assertThat(state.id(), equalTo(1L));
        assertThat(stateProps.single().get("props").asMap().isEmpty(), equalTo(false));
        assertThat(currentResult.single().get("id").asLong(), equalTo(0L));
        assertThat(hasStatusResult.single().get("id").asLong(), equalTo(0L));
        assertThat(state.hasLabel("Error"), equalTo(true));
        assertThat(hasStatusDateResult.single().get("date").asLocalDateTime(), equalTo(convertEpochToLocalDateTime(593920000000L)));
    }
}
 
Example #6
Source File: CEnhancement.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private void enhanceTranslationUnit(Record record) {
	Node node = record.get("n").asNode();
	String fileName = record.get("f.fileName").asString();
	if(fileName.endsWith(".ast")) {
		fileName = fileName.replaceAll(".ast", "");
		if(!fileName.endsWith(".h")) {
			fileName = fileName + ".c";
		}
	}

	this.fileNameTranslationUnit = fileName;
	connector.executeWrite(
			"MATCH (n) WHERE ID(n) = " + node.id() + " SET n.name = '" + fileName + "', n.fqn = '" + fileName + "', n.hash = '" + createHash(fileName) + "'"
	);

}
 
Example #7
Source File: JQA2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataEnumValue(Node ev) {
	String belongsTo = "";
	StatementResult parent = connector.executeRead("MATCH (parent)-[:DECLARES]->(enumValue) WHERE ID(enumValue) = " + ev.id() 
		+ " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	return "\"id\":            \"" + ev.get("hash").asString() + "\"," +
			"\n" +
			"\"qualifiedName\": \"" + ev.get("fqn").asString() + "\"," +
			"\n" +
			"\"name\":          \"" + ev.get("name").asString() + "\"," +
			"\n" +
			"\"type\":          \"FAMIX.EnumValue\"," +
			"\n" +
			"\"belongsTo\":     \"" + belongsTo + "\"" +
			"\n";
}
 
Example #8
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 #9
Source File: City2X3D.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toChimney(Node chimney, Node entity) {
	final Node position = connector.getPosition(chimney.id());
    StringBuilder builder = new StringBuilder();
    builder.append("<Group DEF='" + entity.get("hash").asString() + "'>");
    builder.append("\n");
    builder.append("\t <Transform translation='" + position.get("x").asDouble() + " " + position.get("y").asDouble() + " " + position.get("z").asDouble() + "'>");
    builder.append("\n");
    builder.append("\t\t <Shape>");
    builder.append("\n");
    builder.append("\t\t\t <Cylinder height='" + chimney.get("height").asDouble() + "' radius='" + chimney.get("width").asDouble() + "'></Cylinder>");
    builder.append("\n");
    builder.append("\t\t\t <Appearance>");
    builder.append("\n");
    builder.append("\t\t\t\t <Material diffuseColor='" + chimney.get("color").asString() + "'></Material>");
    builder.append("\n");
    builder.append("\t\t\t </Appearance>");
    builder.append("\n");
    builder.append("\t\t </Shape>");
    builder.append("\n");
    builder.append("\t </Transform>");
    builder.append("\n");
    builder.append("</Group>\t\t");
    builder.append("\n");
    return builder.toString();
}
 
Example #10
Source File: CityLayout.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private static List<Rectangle> sortChildrenAsRectangles(List<Node> children) {
	List<Rectangle> elements = new ArrayList<>();
	// copy all child-elements into a List<Rectangle> (for easier sort) with links
	// to former entities
	for (Node child : children) {
		double width = properties.get(child.id())[0];
		double length = properties.get(child.id())[1];

		Rectangle rectangle = new Rectangle(0, 0, width + config.getBuildingHorizontalGap(),
				length + config.getBuildingHorizontalGap(), 1);
		rectangle.setNodeLink(child);
		elements.add(rectangle);
	}
	// sort elements by size in descending order
	Collections.sort(elements);
	Collections.reverse(elements);
	return elements;
}
 
Example #11
Source File: JQA2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataAnnotation(Node annotation) {
	String belongsTo = "";
	StatementResult parent = connector.executeRead("MATCH (parent:Package)-[:CONTAINS|DECLARES]->(annotation) WHERE ID(annotation) = " + annotation.id() 
		+ " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	return "\"id\":            \"" + annotation.get("hash").asString() + "\"," +
			"\n" +
			"\"qualifiedName\": \"" + annotation.get("fqn").asString() + "\"," +
			"\n" +
			"\"name\":          \"" + annotation.get("name").asString() + "\"," +
			"\n" +
			"\"type\":          \"FAMIX.AnnotationType\"," +
			"\n" +
			"\"modifiers\":     \"" + getModifiers(annotation) + "\"," +
			"\n" +
			"\"subClassOf\":    \"\"," +
			"\n" +
			"\"superClassOf\":  \"\"," +
			"\n" +
			"\"belongsTo\":     \"" + belongsTo + "\"" +
			"\n";
}
 
Example #12
Source File: InitTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateAnEntityWithPropertiesWithAStateAndItsPropertiesWithAdditionalLabelButNoDate() throws Throwable {
    // This is in a try-block, to make sure we close the driver after the test
    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {
        // When
        StatementResult result = session.run("CALL graph.versioner.init('Entity', {key:'value'}, {key:'value'}, 'Error')");
        StatementResult entityResult = session.run("MATCH (e:Entity) RETURN properties(e) as props");
        StatementResult stateResult = session.run("MATCH (s:State) RETURN s");
        Node state = stateResult.single().get("s").asNode();
        StatementResult stateProps = session.run("MATCH (s:State) RETURN properties(s) as props");
        StatementResult currentResult = session.run("MATCH (e:Entity)-[:CURRENT]->(s:State) RETURN id(e) as id");
        StatementResult hasStatusResult = session.run("MATCH (e:Entity)-[:HAS_STATE]->(s:State) RETURN id(e) as id");

        // Then
        assertThat(result.single().get("node").asNode().id(), equalTo(0L));
        assertThat(entityResult.single().get("props").asMap().isEmpty(), equalTo(false));
        assertThat(state.id(), equalTo(1L));
        assertThat(stateProps.single().get("props").asMap().isEmpty(), equalTo(false));
        assertThat(currentResult.single().get("id").asLong(), equalTo(0L));
        assertThat(hasStatusResult.single().get("id").asLong(), equalTo(0L));
        assertThat(state.hasLabel("Error"), equalTo(true));
    }
}
 
Example #13
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 #14
Source File: RelationshipProcedureTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateTheRelationshipAssociatedToANewStateHavingRequestedDate() {

    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {

        // Given
        Node entityA = initEntity(session);
        Node entityB = initEntity(session);
        String testType = "testType";
        Long date = 593920000000L;

        // When
        String query = "MATCH (a:Entity), (b:Entity) WHERE id(a) = %d AND id(b) = %d WITH a, b CALL graph.versioner.relationship.create(a, b, '%s', {}, localdatetime('1988-10-27T02:46:40')) YIELD relationship RETURN relationship";
        session.run(String.format(query, entityA.id(), entityB.id(), testType));

        // Then
        String querySourceCurrent = "MATCH (e:Entity)-[r:CURRENT]->(:State)-[:%s]->(:R) WHERE id(e) = %d RETURN r";
        Relationship currentRelationship = session.run(String.format(querySourceCurrent, testType, entityA.id())).single().get("r").asRelationship();

        assertThat(currentRelationship)
                .matches(rel -> rel.containsKey("date") && rel.get("date").asLocalDateTime().equals(convertEpochToLocalDateTime(date)));
    }
}
 
Example #15
Source File: GetTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetCurrentStateByGivenEntity() {
    // This is in a try-block, to make sure we close the driver after the test
    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {
        // Given
        session.run("CREATE (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'})");
        Node state = session.run("MATCH (s:State) RETURN s").single().get("s").asNode();

        // When
        StatementResult result = session.run("MATCH (e:Entity) WITH e CALL graph.versioner.get.current.state(e) YIELD node RETURN node");

        // Then
        assertThat(result.single().get("node").asNode(), equalTo(state));
    }
}
 
Example #16
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String getFunctionSignature(Node function){
	String signature;
	String returnType = "";
	StatementResult returnTypeNodes =  connector.executeRead(
			 "MATCH (function:Function)-[:RETURNS]->(node) WHERE ID(function) = " + function.id() + " RETURN node");
	if(returnTypeNodes.hasNext()) {
		returnType += returnTypeNodes.single().get("node").asNode().get("name").asString();
	}
	if(!returnType.endsWith("*")){
		returnType += " ";
	}
	String functionName = function.get("name").asString();
	List<Node> parameterList = new ArrayList<>();
	 StatementResult parameters =  connector.executeRead(
			 "MATCH (function:Function)-[:HAS]->(node) WHERE ID(function) = " + function.id() + " RETURN node ORDER BY node.index");
	 while (parameters.hasNext()) {
	 	parameterList.add(parameters.next().get("node").asNode());
	 }
	//var parameterList = function.getRelationships(Direction.OUTGOING, Rels.HAS).map[endNode]
	//sort parameters according to their index
	//parameterList = parameterList.sortBy[p|p.getProperty("index", 0) as Integer]
	String parameter = getFunctionParameters(parameterList);
	signature = returnType + functionName + "(" + parameter + ")";
	return signature;
}
 
Example #17
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataEnumValue(Node enumValue) {
	String belongsTo = "";
	String dependsOn = "";
	StatementResult parent =  connector.executeRead(
			"MATCH (parent)-[:DECLARES]->(enumValue:EnumConstant) WHERE ID(enumValue) = " + enumValue.id() + " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	StatementResult dependent =  connector.executeRead(
			"MATCH (enumValue:EnumConstant)-[:DEPENDS_ON]->(type) WHERE ID(enumValue) = " + enumValue.id() + " RETURN type.hash");
	if(dependent.hasNext()){
		dependsOn = dependent.single().get("type.hash").asString();
	}

	return formatLine("id", enumValue.get("hash").asString()) +
			formatLine("qualifiedName", enumValue.get("fqn").asString()) +
			formatLine("name", enumValue.get("name").asString()) +
			formatLine("type", "EnumValue") +
			formatLine("belongsTo", belongsTo) +
			formatLine(dependsOn, dependsOn) +
			formatLine("filename", enumValue.get("fileName").asString());
}
 
Example #18
Source File: CityUtils.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private static String setMethodColor(Node relatedEntity) {
	String color;
	boolean isStatic = relatedEntity.get("static").asBoolean(false);
	boolean isAbstract = relatedEntity.get("abstract").asBoolean(false);

	if (relatedEntity.hasLabel(Labels.Constructor.name())) {
		color = config.getCityColor("red");
	} else if (relatedEntity.hasLabel(Labels.Getter.name())) {
		color = config.getCityColor("light_green");
	} else if (relatedEntity.hasLabel(Labels.Setter.name())) {
		color = config.getCityColor("dark_green");
	} else if (isStatic) {
		color = config.getCityColor("yellow");
	} else if (isAbstract) {
		color = config.getCityColor("orange");
	} else {
		// Default
		color = config.getCityColor("violet");
	}
	return color;
}
 
Example #19
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataEnum(Node enumNode) {
	String belongsTo = "";
	String dependsOn = "";
	StatementResult parent =  connector.executeRead(
			"MATCH (parent)-[:DECLARES]->(enum:Enum) WHERE ID(enum) = " + enumNode.id() + " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	StatementResult dependent =  connector.executeRead(
			"MATCH (enum:Enum)-[:DEPENDS_ON]->(type) WHERE ID(enum) = " + enumNode.id() + " RETURN type.hash");
	if(dependent.hasNext()){
		dependsOn = dependent.single().get("type.hash").asString();
	}

	return formatLine("id", enumNode.get("hash").asString()) +
			formatLine("qualifiedName", enumNode.get("fqn").asString()) +
			formatLine("name", enumNode.get("name").asString()) +
			formatLine("type", "Enum") +
			formatLine("belongsTo", belongsTo) +
			formatLine(dependsOn, dependsOn) +
			formatLine("filename", enumNode.get("fileName").asString());
}
 
Example #20
Source File: C2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String toMetaDataStruct(Node struct) {
	String belongsTo = "";
	String dependsOn = "";
	StatementResult parent =  connector.executeRead(
			"MATCH (parent)-[:DECLARES]->(struct:Struct) WHERE ID(struct) = " + struct.id() + " RETURN parent.hash");
	if(parent.hasNext()) {
		belongsTo = parent.single().get("parent.hash").asString();
	}
	StatementResult dependent =  connector.executeRead(
			"MATCH (struct:Struct)-[:DEPENDS_ON]->(type) WHERE ID(struct) = " + struct.id() + " RETURN type.hash");
	if(dependent.hasNext()){
		dependsOn = dependent.single().get("type.hash").asString();
	}

	return formatLine("id", struct.get("hash").asString()) +
			formatLine("qualifiedName", struct.get("fqn").asString()) +
			formatLine("name", struct.get("name").asString()) +
			formatLine("type", "Struct") +
			formatLine("belongsTo", belongsTo) +
			formatLine(dependsOn, dependsOn) +
			formatLine("filename", struct.get("fileName").asString());
}
 
Example #21
Source File: JQA2JSON.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private String getModifiers(Node element) {
	ArrayList<String> tmp = new ArrayList<>();
	if (element.containsKey("visibility")) {
		tmp.add(element.get("visibility").asString());
	}
	if (element.containsKey("final")) {
		if (element.get("final").asBoolean()) {
			tmp.add("final");
		}
	}
	if (element.containsKey("abstract")) {
		if (element.get("abstract").asBoolean()) {
			tmp.add("abstract");
		}
	}
	if (element.containsKey("static")) {
		tmp.add("static");
	}
	Collections.sort(tmp);
	return removeBrackets(tmp);
}
 
Example #22
Source File: UpdateTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test (expected = ClientException.class)
public void shouldNotCreateACopyOfTheGivenStateSinceItsADifferentEntityState() throws Throwable {
    // This is in a try-block, to make sure we close the driver after the test
    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {
        // Given
        session.run("CREATE (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'})");
        session.run("MATCH (e:Entity {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'}) CREATE (e)-[:HAS_STATE {startDate:localdatetime('1988-10-27T00:00:00')}]->(s)");
        session.run("MATCH (e:Entity) CREATE (e)-[:HAS_STATE {startDate:localdatetime('1988-10-26T00:00:00'), endDate:localdatetime('1988-10-27T00:00:00')}]->(s:State:Test {key:'initialValue'})");
        session.run("MATCH (sc:State)<-[:CURRENT]-(e:Entity)-[:HAS_STATE]->(s:Test) CREATE (sc)-[:PREVIOUS {date:localdatetime('1988-10-26T00:00:00')}]->(s)");
        session.run("CREATE (e:EntityBis {key:'immutableValue'})-[:CURRENT {date:localdatetime('1988-10-27T00:00:00')}]->(s:State {key:'initialValue'})");
        session.run("MATCH (e:EntityBis)-[:CURRENT]->(s:State) CREATE (e)-[:HAS_STATE {startDate:localdatetime('1988-10-27T00:00:00')}]->(s)");

        StatementResult result = session.run("MATCH (e:Entity), (:EntityBis)-[:HAS_STATE]->(s:State) WITH e, s CALL graph.versioner.patch.from(e, s) YIELD node RETURN node");
        Node currentState = result.single().get("node").asNode();
    }
}
 
Example #23
Source File: BuildingSegmentComparator.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
public BuildingSegmentComparator(final Node segment) {
	this.segment = segment;
	this.relatedEntity = connector.getVisualizedEntity(segment.id());
	setCoarseValue();
	switch (config.getClassElementsSortModeFine()) {
	case ALPHABETICALLY: // names compared directly in compareTo-method
		break;
	case SCHEME:
		switch (config.getScheme()) {
		case VISIBILITY:
			fineValue = getCompValue_Visibility(relatedEntity);
			break;
		case TYPES:
			fineValue = getCompValue_Type(relatedEntity);
			break;
		}
		break;
	case NOS: // numberOfStatements compared directly in compareTo-method
		finerValue = getCompValue_Type(relatedEntity); // If NOS are equal, sort for types
		break;
		case UNSORTED:
		default:
		break;
	}
}
 
Example #24
Source File: RelationshipProcedureTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotCreateTheRelationshipIfDestinationIsNotAnEntity() throws Throwable {

    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {

        // Given
        Node entityA = initEntity(session);
        Node entityB = session.run("CREATE (e:Entity) RETURN e").single().get("e").asNode(); //Not an entity because missing states and R
        String testType = "testType";

        // When
        String query = "MATCH (a:Entity), (b:Entity) WHERE id(a) = %d AND id(b) = %d WITH a, b CALL graph.versioner.relationship.create(a, b, '%s') YIELD relationship RETURN relationship";
        assertThat(session.run(String.format(query, entityA.id(), entityB.id(), testType)));
        Throwable thrown = catchThrowable(() -> session.run(String.format(query, entityA.id(), entityB.id(), testType)));

     //Then
     assertThat(thrown).hasMessageContaining("The given node is not a Versioner Core Entity");
    }
}
 
Example #25
Source File: RelationshipProcedureTest.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateTheRelationshipInANewCurrentStatePreservingTheOldOne() {

    try (Driver driver = GraphDatabase
            .driver(neo4j.boltURI(), Config.build().withEncryption().toConfig()); Session session = driver.session()) {

        // Given
        Node entityA = initEntity(session);
        Node entityB = initEntity(session);
        String testType = "testType";
        Long entityACurrentId = session.run(String.format("MATCH (e:Entity)-[:CURRENT]->(s:State) WHERE id(e) = %d RETURN s", entityA.id())).single().get("s").asNode().id();

        // When
        String query = "MATCH (a:Entity), (b:Entity) WHERE id(a) = %d AND id(b) = %d WITH a, b CALL graph.versioner.relationship.create(a, b, '%s') YIELD relationship RETURN relationship";
        Relationship relationship = session.run(String.format(query, entityA.id(), entityB.id(), testType)).single().get("relationship").asRelationship();

        // Then
        String querySourceStates = "MATCH (:R)<-[r:%s]-(s1:State)-[:PREVIOUS]->(s2:State) WHERE id(r) = %d RETURN s1, s2";
        StatementResult result = session.run(String.format(querySourceStates, testType, relationship.id()));

        assertThat(result)
                .hasSize(1)
                .allMatch(r -> r.get("s1").asNode().id() != r.get("s2").asNode().id() && r.get("s2").asNode().id() == entityACurrentId);
    }
}
 
Example #26
Source File: JQA2JSON.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
private String getAccesses(Node element) {
	ArrayList<String> tmp = new ArrayList<>();
	connector.executeRead("MATCH (access)<-[:WRITES|READS]-(element) WHERE ID(element) = " + element.id() + " RETURN access").forEachRemaining((result) -> {
		Node node = result.get("access").asNode();
		if(node.containsKey("hash")) {
			tmp.add(node.get("hash").asString());
		}			
	});
	Collections.sort(tmp);
	return removeBrackets(tmp);
}
 
Example #27
Source File: JQA2JSON.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
private String getCalledBy(Node element) {
	ArrayList<String> tmp = new ArrayList<>();
	connector.executeRead("MATCH (element)<-[:INVOKES]-(call) WHERE ID(element) = " + element.id() + " RETURN call").forEachRemaining((result) -> {
		Node node = result.get("call").asNode();
		if(node.containsKey("hash")) {
			tmp.add(node.get("hash").asString());
		}
	});
	Collections.sort(tmp);
	return removeBrackets(tmp);
}
 
Example #28
Source File: JQA2JSON.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
private String getAccessedBy(Node element) {
	ArrayList<String> tmp = new ArrayList<>();
	connector.executeRead("MATCH (access)-[:WRITES|READS]->(element) WHERE ID(element) = " + element.id() + " RETURN access").forEachRemaining((result) -> {
		Node node = result.get("access").asNode();
		if(node.containsKey("hash")) {
			tmp.add(node.get("hash").asString());
		}			
	});
	Collections.sort(tmp);
	return removeBrackets(tmp);
}
 
Example #29
Source File: City2City.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
private void setBuildingSegmentAttributesPanels(Long segment) {
	Path path = connector.executeRead(
		"MATCH p = (parent)-[:CONTAINS]->(s)-[:VISUALIZES]->(e) WHERE ID(s) = " + segment + " RETURN p").next().get(
		"p").asPath();
	Node relatedEntity = path.end();
	long parent = path.start().id();
	List<Node> childsM = connector.executeRead(
		"MATCH (s)-[:CONTAINS]->(child)-[r:VISUALIZES]->(e:Method) WHERE ID(s) = " + parent +
			" AND (e:Field OR e:Method)" + " AND NOT (e)<-[:DECLARES]-(:Enum) RETURN e").stream().map(s -> s.get("e").asNode()).collect(Collectors.toList());
	List<Node> childsA = connector.executeRead(
			"MATCH (s)-[:CONTAINS]->(child)-[r:VISUALIZES]->(e:Field) WHERE ID(s) = " + parent +
				" AND NOT (e)<-[:DECLARES]-(:Enum) RETURN e").stream().map(s -> s.get("e").asNode()).collect(Collectors.toList());
	int areaUnit;
	if (classElementsMode == ClassElementsModes.ATTRIBUTES_ONLY) {
		areaUnit = childsM.size();
	} else {
		areaUnit = childsA.size();
	}
	double width;
	double length;
	if (areaUnit <= 1) {
		width = widthMin;
		length = widthMin;
	} else {
		width = widthMin * areaUnit;
		length = widthMin * areaUnit;
	}
	int index = 0;
	int effectiveLineCount = relatedEntity.get("effectiveLineCount").asInt(0);
	while (index < panelHeightTresholdNos.length &&
		effectiveLineCount >= panelHeightTresholdNos[index]) {
		index = index + 1;
	}
	double height = panelHeightUnit * (index + 1);
	connector.executeWrite(
		cypherSetBuildingSegmentAttributes(segment, width, length, height,
			CityUtils.setBuildingSegmentColor(relatedEntity)));
}
 
Example #30
Source File: City2City.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
private void setBuildingAttributes(Node building) {
	int methodCounter = connector.executeRead(
		"MATCH (n)-[:VISUALIZES]->(o)-[:DECLARES]->(m:Method) WHERE ID(n) = " + building.id() +
			" RETURN COUNT(m) AS mCount").single().get("mCount").asInt();
	int dataCounter = connector.executeRead(
		"MATCH (n)-[:VISUALIZES]->(o)-[:DECLARES]->(f:Field) WHERE ID(n) = " + building.id() +
			" AND NOT o:Enum RETURN COUNT(f) AS fCount").single().get("fCount").asInt();
	switch (buildingType) {
		case CITY_ORIGINAL: setBuildingAttributesOriginal(building, methodCounter, dataCounter); break;
		case CITY_PANELS: setBuildingAttributesPanels(building, methodCounter, dataCounter); break;
		case CITY_BRICKS: setBuildingAttributesBricks(building, methodCounter, dataCounter); break;
		case CITY_FLOOR: setBuildingAttributesFloors(building, methodCounter, dataCounter); break;
	}
}