Java Code Examples for org.neo4j.graphdb.Relationship#getEndNode()

The following examples show how to use org.neo4j.graphdb.Relationship#getEndNode() . 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: Traversals.java    From EvilCoder with MIT License 6 votes vote down vote up
public static List<Node> getChildrenConnectedBy(Node node, String edgeType)
{
	List<Node> retval = new LinkedList<Node>();

	long nodeId = node.getId();

	Iterable<Relationship> rels = node.getRelationships();
	for (Relationship rel : rels)
	{
		if (!rel.getType().name().equals(edgeType))
			continue;
		Node childNode = rel.getEndNode();
		if (childNode.getId() == nodeId)
			continue;

		retval.add(childNode);
	}
	return retval;
}
 
Example 2
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean removeFriendship(final Node following, final Node followed) {
	// find the replica node of the user followed
	Node followedReplica = null;
	for (Relationship followship : following.getRelationships(
			SocialGraphRelationshipType.FOLLOW, Direction.OUTGOING)) {
		followedReplica = followship.getEndNode();
		if (NeoUtils.getNextSingleNode(followedReplica,
				SocialGraphRelationshipType.REPLICA).equals(followed)) {
			break;
		}
		followedReplica = null;
	}

	// there is no such followship existing
	if (followedReplica == null) {
		return false;
	}

	this.removeFromReplicaLayer(followedReplica);
	return true;
}
 
Example 3
Source File: Neo4JApiQuerySemaphoreNeighborInject.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Collection<Neo4jSemaphoreNeighborInjectMatch> evaluate() {
	final Collection<Neo4jSemaphoreNeighborInjectMatch> matches = new ArrayList<>();

	final GraphDatabaseService graphDb = driver.getGraphDb();
	try (Transaction tx = graphDb.beginTx()) {
		// (route:Route)
		final Iterable<Node> routes = () -> graphDb.findNodes(Neo4jConstants.labelRoute);
		for (final Node route : routes) {
			Iterable<Relationship> entries = route.getRelationships(Direction.OUTGOING, Neo4jConstants.relationshipTypeEntry);

			for (Relationship entry : entries) {
				final Node semaphore = entry.getEndNode();

				final Map<String, Object> match = new HashMap<>();
				match.put(QueryConstants.VAR_ROUTE, route);
				match.put(QueryConstants.VAR_SEMAPHORE, semaphore);
				matches.add(new Neo4jSemaphoreNeighborInjectMatch(match));
			}
		}
	}

	return matches;
}
 
Example 4
Source File: Neo4jUtil.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
public static Iterable<Node> getAdjacentNodes(final Node sourceNode, final RelationshipType relationshipType, final Direction direction, final Label targetNodeLabel) {
	final Collection<Node> nodes = new ArrayList<>();
	
	final Iterable<Relationship> relationships = sourceNode.getRelationships(relationshipType, direction);
	for (final Relationship relationship : relationships) {
		final Node candidate;
		switch (direction) {
		case INCOMING:
			candidate = relationship.getStartNode();
			break;
		case OUTGOING:
			candidate = relationship.getEndNode();			
			break;
		default:
			throw new UnsupportedOperationException("Direction: " + direction + " not supported.");
		}
		if (!candidate.hasLabel(targetNodeLabel)) {
			continue;
		}
		nodes.add(candidate);
	}
	return nodes;
}
 
Example 5
Source File: UniqueRelationshipFactory.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
/**
 * Finds relationship of given type between subject and object nodes.
 * 
 * @return Relationship if exists or null.
 */
public Relationship get(Node subject, RelationshipType type, Node object) {
	try {
		// FIXME Use relationship index instead of iterating over all relationships
		Iterable<Relationship> relations = subject.getRelationships(Direction.OUTGOING, type);
		for(Relationship relation: relations) {
			org.neo4j.graphdb.Node target = relation.getEndNode();
			// Match object with target node in the existing triple
			Iterable<Label> labels = object.getLabels();
			for(Label label:labels) {
				if(label.name().equals(NeoGraph.LABEL_LITERAL)) {
					// Match literal value of object and target in existing triple
					if(object.getProperty(NeoGraph.PROPERTY_VALUE).equals(target.getProperty(NeoGraph.PROPERTY_VALUE)))
						return relation;
					else return null;
				}
			}
			// Now match URI of object and target in existing triple
			// FIXME Blank Nodes?
			if(object.getProperty(NeoGraph.PROPERTY_URI).equals(target.getProperty(NeoGraph.PROPERTY_URI)))
				return relation;
		}
	} catch(RuntimeException exception) { }
	return null;
}
 
Example 6
Source File: Traversals.java    From EvilCoder with MIT License 5 votes vote down vote up
public static String getCalleeFromCall(Long nodeId)
{
	Node node = Neo4JDBInterface.getNodeById(nodeId);
	Iterable<Relationship> rels = node.getRelationships();
	for (Relationship rel : rels)
	{
		if (!rel.getType().name().equals(EdgeTypes.IS_AST_PARENT))
			continue;

		Node endNode = rel.getEndNode();

		if (endNode.getId() == node.getId())
			continue;

		try
		{
			String childNumStr = (String) endNode
					.getProperty(NodeKeys.CHILD_NUMBER);
			if (childNumStr.equals("0"))
				return endNode.getProperty(NodeKeys.CODE).toString();
		}
		catch (RuntimeException ex)
		{
			return endNode.getProperty(NodeKeys.CODE).toString();
		}
	}
	return "";
}
 
Example 7
Source File: SocialGraph.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
/**
 * delete a user removing it from all replica layers of following users
 * 
 * @param user
 *            user that shall be deleted
 */
public void deleteUser(final Node user) {
	Node userReplica, following;
	for (Relationship replica : user.getRelationships(
			SocialGraphRelationshipType.REPLICA, Direction.INCOMING)) {
		userReplica = replica.getEndNode();
		following = NeoUtils.getPrevSingleNode(userReplica,
				SocialGraphRelationshipType.FOLLOW);
		this.removeFriendship(following, user);
	}
}
 
Example 8
Source File: NeoUtils.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
/**
 * find an outgoing relation from the user passed of the specified type
 * 
 * @param user
 *            source user node
 * @param relType
 *            relationship type of the relation being searched
 * @return node targeted by the relation<br>
 *         null - if there is no relation of the type specified
 */
public static Node getNextSingleNode(final Node user,
		RelationshipType relationshipType) {
	// find an outgoing relation of the type specified
	Relationship rel = null;
	try {
		rel = user.getSingleRelationship(relationshipType,
				Direction.OUTGOING);
	} catch (final NonWritableChannelException e) {
		// TODO: why is this here? Bug for read-only databases in previous
		// version?
	}

	return (rel == null) ? (null) : (rel.getEndNode());
}
 
Example 9
Source File: StatusUpdateTemplate.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
/**
 * create a new status update template from a neo4j node
 * 
 * @param templateNode
 *            neo4j template node
 */
public StatusUpdateTemplate(final org.neo4j.graphdb.Node templateNode) {
	// read template information
	this.name = (String) templateNode
			.getProperty(Properties.Templates.IDENTIFIER);
	this.version = (String) templateNode
			.getProperty(Properties.Templates.VERSION);
	this.javaCode = (String) templateNode
			.getProperty(Properties.Templates.CODE);
	this.fields = new HashMap<String, TemplateFieldInfo>();
	this.files = new HashMap<String, TemplateFileInfo>();

	// read template field items
	TemplateFieldInfo fieldInfo;
	for (Relationship field : templateNode
			.getRelationships(SocialGraphRelationshipType.Templates.FIELD,
					Direction.OUTGOING)) {
		fieldInfo = new TemplateFieldInfo(field.getEndNode());
		this.fields.put(fieldInfo.getName(), fieldInfo);
	}

	// read template file items
	TemplateFileInfo fileInfo;
	for (Relationship file : templateNode.getRelationships(
			SocialGraphRelationshipType.Templates.FILE, Direction.OUTGOING)) {
		fileInfo = new TemplateFileInfo(file.getEndNode());
		this.files.put(fileInfo.getName(), fileInfo);
	}
}
 
Example 10
Source File: AbstractEmbeddedDBAccess.java    From jcypher with Apache License 2.0 5 votes vote down vote up
private RelationNodes init(Relationship relation) {
	RelationNodes ret = new RelationNodes();
	JsonObjectBuilder rel = Json.createObjectBuilder();
	rel.add("id", String.valueOf(relation.getId()));
	RelationshipType typ = relation.getType();
	if (typ != null)
		rel.add("type", typ.name());
	Node sn = relation.getStartNode();
	if (sn != null) {
		rel.add("startNode", String.valueOf(sn.getId()));
		ret.startNode = sn;
	}
	Node en = relation.getEndNode();
	if (en != null) {
		rel.add("endNode", String.valueOf(en.getId()));
		ret.endNode = en;
	}
	JsonObjectBuilder props = Json.createObjectBuilder();
	Iterator<String> pit = relation.getPropertyKeys().iterator();
	while (pit.hasNext()) {
		String pKey = pit.next();
		Object pval = relation.getProperty(pKey);
		writeLiteral(pKey, pval, props);
	}
	rel.add("properties", props);
	this.relationObject = rel;
	return ret;
}
 
Example 11
Source File: OwlPostprocessor.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
public void processSomeValuesFrom() {
  logger.info("Processing someValuesFrom classes");
  try (Transaction tx = graphDb.beginTx()) {
    Result results =
        graphDb.execute("MATCH (n)-[relationship]->(svf:someValuesFrom)-[:property]->(p) "
            + "RETURN n, relationship, svf, p");
    while (results.hasNext()) {
      Map<String, Object> result = results.next();
      Node subject = (Node) result.get("n");
      Relationship relationship = (Relationship) result.get("relationship");
      Node svf = (Node) result.get("svf");
      Node property = (Node) result.get("p");
      for (Relationship r : svf.getRelationships(OwlRelationships.FILLER)) {
        Node object = r.getEndNode();
        String relationshipName =
            GraphUtil.getProperty(property, CommonProperties.IRI, String.class).get();
        RelationshipType type = RelationshipType.withName(relationshipName);
        String propertyUri =
            GraphUtil.getProperty(property, CommonProperties.IRI, String.class).get();
        Relationship inferred = subject.createRelationshipTo(object, type);
        inferred.setProperty(CommonProperties.IRI, propertyUri);
        inferred.setProperty(CommonProperties.CONVENIENCE, true);
        inferred.setProperty(CommonProperties.OWL_TYPE, relationship.getType().name());
      }
    }
    tx.success();
    tx.close();
  }
}
 
Example 12
Source File: NodeTransformer.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Override
public Concept apply(Node n) {
  try (Transaction tx = n.getGraphDatabase().beginTx()) {
    Concept concept = new Concept(n.getId());
    concept.setIri((String) n.getProperty(Concept.IRI, null));
    concept.setAnonymous(n.hasLabel(OwlLabels.OWL_ANONYMOUS));
    concept.setDeprecated(isDeprecated(n));

    for (String definition : GraphUtil.getProperties(n, Concept.DEFINITION, String.class)) {
      concept.addDefinition(definition);
    }
    for (String abbreviation : GraphUtil.getProperties(n, Concept.ABREVIATION, String.class)) {
      concept.addAbbreviation(abbreviation);
    }
    for (String acronym : GraphUtil.getProperties(n, Concept.ACRONYM, String.class)) {
      concept.addAcronym(acronym);
    }
    for (String category : GraphUtil.getProperties(n, Concept.CATEGORY, String.class)) {
      concept.addCategory(category);
    }
    for (String label : GraphUtil.getProperties(n, Concept.LABEL, String.class)) {
      concept.addLabel(label);
    }
    for (String synonym : GraphUtil.getProperties(n, Concept.SYNONYM, String.class)) {
      concept.addSynonym(synonym);
    }
    for (Label type : n.getLabels()) {
      concept.addType(type.name());
    }

    for (Relationship r: n.getRelationships(OwlRelationships.OWL_EQUIVALENT_CLASS)) {
      Node equivalence = r.getStartNode().equals(n) ? r.getEndNode() : r.getStartNode();
      concept.getEquivalentClasses().add((String)equivalence.getProperty(CommonProperties.IRI));
    }

    tx.success();
    return concept;
  }
}
 
Example 13
Source File: DirectedModularity.java    From Neo4jSNA with Apache License 2.0 5 votes vote down vote up
@Override
public void compute(Relationship r) {
	Node n1 = r.getStartNode();
	Node n2 = r.getEndNode();
	
	if( n1.getProperty(attName) == n2.getProperty(attName) ) {
		double weight = r.hasProperty("weight") ? (double) r.getProperty("weight") : 1.0;
		eii += weight;
	}
}
 
Example 14
Source File: Neo4JApiQuerySwitchMonitored.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Collection<Neo4jSwitchMonitoredMatch> evaluate() {
	final Collection<Neo4jSwitchMonitoredMatch> matches = new ArrayList<>();

	final GraphDatabaseService graphDb = driver.getGraphDb();
	try (Transaction tx = graphDb.beginTx()) {
		final Iterable<Node> sws = () -> graphDb.findNodes(Neo4jConstants.labelSwitch);
		// (sw:Switch)
		for (final Node sw : sws) {
			// (sw)-[:sensor]->(Sensor) NAC
			final Iterable<Relationship> relationshipSensors = sw.getRelationships(Direction.OUTGOING, Neo4jConstants.relationshipTypeMonitoredBy);

			boolean hasSensor = false;
			for (final Relationship relationshipSensor : relationshipSensors) {
				final Node sensor = relationshipSensor.getEndNode();
				if (sensor.hasLabel(Neo4jConstants.labelSensor)) {
					hasSensor = true;
					break;
				}
			}

			if (!hasSensor) {
				final Map<String, Object> match = new HashMap<>();
				match.put(VAR_SW, sw);
				matches.add(new Neo4jSwitchMonitoredMatch(match));
			}
		}
	}

	return matches;
}
 
Example 15
Source File: TransExtractor.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
private void prepare() {
    List<String> entities = new ArrayList<>();
    List<String> relations = new ArrayList<>();
    List<Triple<String, String, String>> triples = new ArrayList<>();
    try (Transaction tx = db.beginTx()) {
        for (Node node : db.getAllNodes()) {
            if (!node.hasLabel(Label.label(JavaCodeExtractor.CLASS)) &&
                    !node.hasLabel(Label.label(JavaCodeExtractor.INTERFACE)) &&
                    !node.hasLabel(Label.label(JavaCodeExtractor.METHOD)) &&
                    !node.hasLabel(Label.label(JavaCodeExtractor.FIELD)))
                continue;
            entities.add("" + node.getId());
        }

        for (Relationship rel : db.getAllRelationships()) {
            Node node1 = rel.getStartNode();
            if (!node1.hasLabel(Label.label(JavaCodeExtractor.CLASS)) &&
                    !node1.hasLabel(Label.label(JavaCodeExtractor.INTERFACE)) &&
                    !node1.hasLabel(Label.label(JavaCodeExtractor.METHOD)) &&
                    !node1.hasLabel(Label.label(JavaCodeExtractor.FIELD)))
                continue;
            Node node2 = rel.getEndNode();
            if (!node2.hasLabel(Label.label(JavaCodeExtractor.CLASS)) &&
                    !node2.hasLabel(Label.label(JavaCodeExtractor.INTERFACE)) &&
                    !node2.hasLabel(Label.label(JavaCodeExtractor.METHOD)) &&
                    !node2.hasLabel(Label.label(JavaCodeExtractor.FIELD)))
                continue;
            triples.add(new ImmutableTriple<>("" + node1.getId(), "" + node2.getId(), rel.getType().name()));
            if (!relations.contains(rel.getType().name()))
                relations.add(rel.getType().name());
        }
        tx.success();
    }
    transE.prepare(entities, relations, triples);
}
 
Example 16
Source File: EmbeddedRelationship.java    From extended-objects with Apache License 2.0 4 votes vote down vote up
public EmbeddedRelationship(Relationship delegate) {
    super(delegate.getId(), delegate);
    this.startNode = new EmbeddedNode(delegate.getStartNode());
    this.endNode = new EmbeddedNode(delegate.getEndNode());
}
 
Example 17
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 4 votes vote down vote up
@Override
public Node getDestVertexFromEdge(Relationship edge)
{
    return edge.getEndNode();
}
 
Example 18
Source File: WriteOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<JSONObject> readStatusUpdates(final Node poster,
		final Node user, final int numItems, boolean ownUpdates) {
	if (!poster.equals(user)) {
		ownUpdates = true;
	}

	final List<JSONObject> statusUpdates = new LinkedList<JSONObject>();

	// check if ego network stream is being accessed
	if (!ownUpdates) {
		final TreeSet<StatusUpdateUser> users = new TreeSet<StatusUpdateUser>(
				new StatusUpdateUserComparator());

		// loop through users followed
		Node userNode;
		StatusUpdateUser crrUser;
		for (Relationship relationship : poster.getRelationships(
				SocialGraphRelationshipType.FOLLOW, Direction.OUTGOING)) {
			userNode = relationship.getEndNode();

			// add users having status updates
			crrUser = new StatusUpdateUser(userNode);
			if (crrUser.hasStatusUpdate()) {
				users.add(crrUser);
			}
		}

		// handle user queue
		while ((statusUpdates.size() < numItems) && !users.isEmpty()) {
			crrUser = users.pollLast();

			// add last recent status update of current user
			statusUpdates.add(crrUser.getStatusUpdate());

			// re-add current user if more status updates available
			if (crrUser.hasStatusUpdate()) {
				users.add(crrUser);
			}
		}
	} else {
		// access single stream only
		final StatusUpdateUser posterNode = new StatusUpdateUser(poster);
		while ((statusUpdates.size() < numItems)
				&& posterNode.hasStatusUpdate()) {
			statusUpdates.add(posterNode.getStatusUpdate());
		}
	}

	return statusUpdates;
}
 
Example 19
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void createFriendship(final Node following, final Node followed) {
	// try to find the replica node of the user followed
	Node followedReplica = null;
	for (Relationship followship : following.getRelationships(
			SocialGraphRelationshipType.FOLLOW, Direction.OUTGOING)) {
		followedReplica = followship.getEndNode();
		if (NeoUtils.getNextSingleNode(followedReplica,
				SocialGraphRelationshipType.REPLICA).equals(followed)) {
			break;
		}
		followedReplica = null;
	}

	// user is following already
	if (followedReplica != null) {
		return;
	}

	// create replica
	final Node newReplica = this.graph.createNode();
	following.createRelationshipTo(newReplica,
			SocialGraphRelationshipType.FOLLOW);
	newReplica.createRelationshipTo(followed,
			SocialGraphRelationshipType.REPLICA);

	// check if followed user is the first in following's ego network
	if (NeoUtils.getNextSingleNode(following,
			SocialGraphRelationshipType.GRAPHITY) == null) {
		following.createRelationshipTo(newReplica,
				SocialGraphRelationshipType.GRAPHITY);
	} else {
		// search for insertion index within following replica layer
		final long followedTimestamp = getLastUpdateByReplica(newReplica);
		long crrTimestamp;
		Node prevReplica = following;
		Node nextReplica = null;
		while (true) {
			// get next user
			nextReplica = NeoUtils.getNextSingleNode(prevReplica,
					SocialGraphRelationshipType.GRAPHITY);
			if (nextReplica != null) {
				crrTimestamp = getLastUpdateByReplica(nextReplica);

				// step on if current user has newer status updates
				if (crrTimestamp > followedTimestamp) {
					prevReplica = nextReplica;
					continue;
				}
			}

			// insertion position has been found
			break;
		}

		// insert followed user's replica into following's ego network
		if (nextReplica != null) {
			prevReplica.getSingleRelationship(
					SocialGraphRelationshipType.GRAPHITY,
					Direction.OUTGOING).delete();
			newReplica.createRelationshipTo(nextReplica,
					SocialGraphRelationshipType.GRAPHITY);
		}
		prevReplica.createRelationshipTo(newReplica,
				SocialGraphRelationshipType.GRAPHITY);
	}
}
 
Example 20
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 4 votes vote down vote up
/**
 * update the replica layer for status update deletion
 * 
 * @param user
 *            owner of the status update being deleted
 * @param statusUpdate
 *            status update being deleted
 */
private void updateReplicaLayerStatusUpdateDeletion(final Node user,
		final Node statusUpdate) {
	final Node lastUpdate = NeoUtils.getNextSingleNode(user,
			SocialGraphRelationshipType.UPDATE);

	// update the ego network if the removal targets the last recent status
	// update
	if (statusUpdate.equals(lastUpdate)) {
		// get timestamp of the last recent status update in future
		long newTimestamp = 0;
		final Node nextStatusUpdate = NeoUtils.getNextSingleNode(
				statusUpdate, SocialGraphRelationshipType.UPDATE);
		if (nextStatusUpdate != null) {
			newTimestamp = (long) nextStatusUpdate
					.getProperty(Properties.StatusUpdate.TIMESTAMP);
		}

		// loop through followers
		Node replicaNode, following;
		for (Relationship replicated : user.getRelationships(
				SocialGraphRelationshipType.REPLICA, Direction.INCOMING)) {
			replicaNode = replicated.getEndNode();
			following = NeoUtils.getPrevSingleNode(replicaNode,
					SocialGraphRelationshipType.FOLLOW);

			// search for insertion index within following replica layer
			long crrTimestamp;
			Node prevReplica = following;
			Node nextReplica = null;
			while (true) {
				// get next user
				nextReplica = NeoUtils.getNextSingleNode(prevReplica,
						SocialGraphRelationshipType.GRAPHITY);
				if (nextReplica != null) {
					// ignore replica of the status update owner
					if (nextReplica.equals(replicaNode)) {
						prevReplica = nextReplica;
						continue;
					}

					crrTimestamp = getLastUpdateByReplica(nextReplica);

					// step on if current user has newer status updates
					if (crrTimestamp > newTimestamp) {
						prevReplica = nextReplica;
						continue;
					}
				}

				// insertion position has been found
				break;
			}

			// insert the replica
			if (nextReplica != null) {
				// bride the replica node
				final Node oldPrevReplica = NeoUtils.getNextSingleNode(
						replicaNode, SocialGraphRelationshipType.GRAPHITY);
				final Node oldNextReplica = NeoUtils.getNextSingleNode(
						replicaNode, SocialGraphRelationshipType.GRAPHITY);
				replicaNode.getSingleRelationship(
						SocialGraphRelationshipType.GRAPHITY,
						Direction.INCOMING).delete();

				if (oldNextReplica != null) {
					oldNextReplica.getSingleRelationship(
							SocialGraphRelationshipType.GRAPHITY,
							Direction.INCOMING).delete();
					oldPrevReplica.createRelationshipTo(oldNextReplica,
							SocialGraphRelationshipType.GRAPHITY);
				}

				// link to new neighbored nodes
				if (nextReplica != null) {
					replicaNode.createRelationshipTo(nextReplica,
							SocialGraphRelationshipType.GRAPHITY);
					prevReplica.getSingleRelationship(
							SocialGraphRelationshipType.GRAPHITY,
							Direction.OUTGOING);
				}
				prevReplica.createRelationshipTo(replicaNode,
						SocialGraphRelationshipType.GRAPHITY);
			}
		}

	}
}