Java Code Examples for org.neo4j.graphdb.Node#getProperty()

The following examples show how to use org.neo4j.graphdb.Node#getProperty() . 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: ReachabilityIndex.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
/**
 * @param startNode
 * @param endNode
 * @return Return true if startNode can reach endNode
 */
public boolean canReach(Node startNode, Node endNode) {
  if (!indexExists()) {
    throw new IllegalStateException("Reachability index must be created first.");
  }

  try (Transaction tx = graphDb.beginTx()) {
    long[] outList = (long[]) startNode.getProperty(OUT_LIST_PROPERTY);
    long[] inList = (long[]) endNode.getProperty(IN_LIST_PROPERTY);
    int i = 0, j = 0;

    while (i < outList.length && j < inList.length) {
      if (outList[i] < inList[j]) {
        i++;
      } else if (inList[j] < outList[i]) {
        j++;
      } else {
        return true;
      }
    }
    return false;
  }
}
 
Example 2
Source File: AbstractEmbeddedDBAccess.java    From jcypher with Apache License 2.0 6 votes vote down vote up
private void init(Node node) {
	JsonObjectBuilder nd = Json.createObjectBuilder();
	nd.add("id", String.valueOf(node.getId()));
	JsonArrayBuilder labels = Json.createArrayBuilder();
	Iterator<Label> lblIter = node.getLabels().iterator();
	boolean hasLabels = false;
	while (lblIter.hasNext()) {
		hasLabels = true;
		Label lab = lblIter.next();
		labels.add(lab.name());
	}
	if (hasLabels)
		nd.add("labels", labels);
	JsonObjectBuilder props = Json.createObjectBuilder();
	Iterator<String> pit = node.getPropertyKeys().iterator();
	while (pit.hasNext()) {
		String pKey = pit.next();
		Object pval = node.getProperty(pKey);
		writeLiteral(pKey, pval, props);
	}
	nd.add("properties", props);
	this.nodeObject = nd;
}
 
Example 3
Source File: Find_all_function_pointers.java    From EvilCoder with MIT License 6 votes vote down vote up
public static void fill_externally_defined_functions(Joern_db joern_db)
   {
// completeType    extern void ( )
// baseType        extern void
// type            Decl
// identifier      extern_func
    if(externally_defined_functions != null) return;

    externally_defined_functions = new HashSet<>();
//    decls = joern_db.runGremlinQuery("queryNodeIndex('type:Decl').filter{it.completeType.startsWith('extern') && it.completeType.endsWith(')')}.identifier")
//    decls = joern_db.runGremlinQuery("g.V.filter{it.type == 'Decl' && it.completeType.startsWith('extern') && it.completeType.endsWith(')')}.identifier")

   List<Node> decl_nodes = Joern_db.queryNodeIndex("type:Decl");
     for(Node d : decl_nodes)
      {
      String completeType = (String)d.getProperty("completeType");
        if(completeType.startsWith("extern") && completeType.endsWith(")"))
         {
         String identifier = (String)d.getProperty("identifier");
          externally_defined_functions.add(identifier);
         }
      }
   }
 
Example 4
Source File: Location.java    From EvilCoder with MIT License 6 votes vote down vote up
public static String get_location_for_node_id(Joern_db joern_db, Long node_id) throws Exception
    {
    Long cur_id = node_id;
    String location = null;
      while(true)
       {
       List<Node> nodes = Pipeline.v(cur_id).to_list();
       Node first = nodes.get(0);
         if(first.hasProperty("location"))
          {
           location = (String)(first.getProperty("location"));
           break;
          }
        cur_id = get_general_parent(joern_db, cur_id);
//        print "cur_id:", cur_id
       }
     return location;
    }
 
Example 5
Source File: Neo4jApiTransformationInjectSwitchSet.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<Neo4jSwitchSetInjectMatch> matches) {
	for (final Neo4jSwitchSetInjectMatch match : matches) {
		final Node sw = match.getSw();
		final String currentPositionString = (String) sw.getProperty(ModelConstants.CURRENTPOSITION);
		final Position currentPosition = Position.valueOf(currentPositionString);
		final Position newCurrentPosition = Position.values()[(currentPosition.ordinal() + 1) % Position.values().length];
		sw.setProperty(ModelConstants.CURRENTPOSITION, newCurrentPosition.toString());
	}
}
 
Example 6
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
/**
 * get a user's last recent status update's time stamp
 * 
 * @param userReplica
 *            replica of the user targeted
 * @return last recent status update's time stamp
 */
private static long getLastUpdateByReplica(final Node userReplica) {
	final Node user = NeoUtils.getNextSingleNode(userReplica,
			SocialGraphRelationshipType.REPLICA);
	if (user.hasProperty(Properties.User.LAST_UPDATE)) {
		return (long) user.getProperty(Properties.User.LAST_UPDATE);
	}
	return 0;
}
 
Example 7
Source File: ConnectedComponents.java    From Neo4jSNA with Apache License 2.0 5 votes vote down vote up
protected long getLowestComponent(Node n) {
	long minComponent = (long) n.getProperty(attName);

	for(Relationship r : n.getRelationships(direction)) {
		long otherComponent = (long) r.getOtherNode(n).getProperty(attName);
		minComponent = minComponent < otherComponent ? minComponent : otherComponent;
	}
	return minComponent;
}
 
Example 8
Source File: Neo4jApiTransformationRepairPosLength.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<Neo4jPosLengthMatch> matches) {
	for (final Neo4jPosLengthMatch match : matches) {
		final Node segment = match.getSegment();
		try {
			final Number lengthNumber = (Number) segment.getProperty(ModelConstants.LENGTH);
			final int length = Neo4jHelper.numberToInt(lengthNumber);

			segment.setProperty(ModelConstants.LENGTH, -length + 1);
		} catch (final NotFoundException e) {
			// do nothing (node has been removed)
		}
	}
}
 
Example 9
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 5 votes vote down vote up
@Override
public Set<Integer> getNeighborsIds(int nodeId)
{
    Set<Integer> neighbors = new HashSet<Integer>();
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            Node n = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, NODE_ID, String.valueOf(nodeId)).iterator()
                .next();
            for (Relationship relationship : n.getRelationships(RelTypes.SIMILAR, Direction.OUTGOING))
            {
                Node neighbour = relationship.getOtherNode(n);
                String neighbourId = (String) neighbour.getProperty(NODE_ID);
                neighbors.add(Integer.valueOf(neighbourId));
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get neighbors ids", e);
        }
    }

    return neighbors;
}
 
Example 10
Source File: Location.java    From EvilCoder with MIT License 5 votes vote down vote up
public static void test_get_location_tuple(Joern_db joern_db) throws Exception
{
// Testing get_location_tuple for libpng, with function "png_do_write_transformations"
List<Node> all_nodes_of_func = Pipeline.Vs().has("functionId", "130007").to_list();
  for(Node a : all_nodes_of_func)
   {
   String its_type = (String)(a.getProperty("type"));
     if(its_type.equals("CFGExitNode") || its_type.equals("Symbol"))
      {
       continue;
      }
    System.out.println(a.getId());
    System.out.println(get_location_tuple(joern_db, new Long(a.getId())).toString());
   }
}
 
Example 11
Source File: PageRank.java    From Neo4jSNA with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(Node node) {
	double secondMember = 0.0;
	for( Relationship rin : node.getRelationships() ) {
		Node neigh = rin.getOtherNode(node);
		
		double neighRank = (double) neigh.getProperty(attName);
		secondMember += neighRank / neigh.getDegree();
	}
	
	secondMember *= this.dampingFactor;
	node.setProperty(attName, firstMember + secondMember);
}
 
Example 12
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 5 votes vote down vote up
@Override
public Map<Integer, List<Integer>> mapCommunities(int numberOfCommunities)
{
    Map<Integer, List<Integer>> communities = new HashMap<Integer, List<Integer>>();

    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            for (int i = 0; i < numberOfCommunities; i++)
            {
                ResourceIterable<Node> nodesIter = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, COMMUNITY, i);
                List<Integer> nodes = new ArrayList<Integer>();
                for (Node n : nodesIter)
                {
                    String nodeIdString = (String) (n.getProperty(NODE_ID));
                    nodes.add(Integer.valueOf(nodeIdString));
                }
                communities.put(i, nodes);
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to map communities", e);
        }
    }

    return communities;
}
 
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: Traversals.java    From EvilCoder with MIT License 5 votes vote down vote up
public static int getNodeChildNum(long nodeId)
{
	Node node = Neo4JDBInterface.getNodeById(nodeId);
	String childNumStr = (String) node.getProperty(NodeKeys.CHILD_NUMBER,
			null);
	if (childNumStr == null)
		return 0;
	return Integer.parseInt(childNumStr);
}
 
Example 15
Source File: Traversals.java    From EvilCoder with MIT License 5 votes vote down vote up
public static Node getStatementForASTNode(Node node)
{
	Node n = node;
	Node parent = node;

	while (true)
	{

		try
		{
			Object property = n.getProperty(NodeKeys.IS_CFG_NODE);
			return n;
		}
		catch (NotFoundException ex)
		{

		}

		Iterable<Relationship> rels = n
				.getRelationships(Direction.INCOMING);
		for (Relationship rel : rels)
		{
			parent = rel.getStartNode();
			break;
		}

		if (n == parent)
			return null;
		n = parent;
	}
}
 
Example 16
Source File: Function_sets_parameter.java    From EvilCoder with MIT License 4 votes vote down vote up
public static String get_function_name_from_function(Joern_db joern_db, Long node_id)
{
Node n = (Node)(Pipeline.v(node_id).to_list().get(0));
 return (String)(n.getProperty("name"));
}
 
Example 17
Source File: GraphManagerTest.java    From graphify with Apache License 2.0 4 votes vote down vote up
@Ignore
@Test
public void testBackwardsPropagation() throws Exception {

    // Invalidate all caches
    NodeManager.globalNodeCache.invalidateAll();
    DataNodeManager.dataCache.invalidateAll();
    ClassNodeManager.classCache.invalidateAll();
    GraphManager.edgeCache.invalidateAll();
    GraphManager.inversePatternCache.invalidateAll();
    GraphManager.patternCache.invalidateAll();
    DataRelationshipManager.relationshipCache.invalidateAll();
    ClassRelationshipCache.relationshipCache.invalidateAll();
    PatternRelationshipCache.relationshipCache.invalidateAll();

    GraphDatabaseService db = setUpDb();
    GraphManager graphManager = new GraphManager("Pattern");
    Node rootNode = getRootPatternNode(db, graphManager);

    Map<String, String> text = new HashMap<>();
    text.put("The first word in a sentence is interesting", "sentence");
    text.put("The second word in a sentence is interesting", "sentence");
    text.put("The third word in a sentence is interesting", "sentence");
    text.put("The fourth word in a paragraph is interesting", "paragraph");
    text.put("The fifth word in a sentence is interesting", "sentence");
    text.put("The sixth word in a paragraph is interesting", "paragraph");
    text.put("The seventh word in a sentence is interesting", "sentence");
    text.put("The eighth word in a document is interesting", "document");
    text.put("The ninth word in a sentence is interesting", "sentence");
    text.put("The tenth word in a paragraph is interesting", "paragraph");
    text.put("The eleventh word in a sentence is interesting", "sentence");
    text.put("The twelfth word in a paragraph is interesting", "paragraph");
    text.put("The thirteenth word in a sentence is interesting", "sentence");
    text.put("The fourteenth word in a document is interesting", "document");
    text.put("The fifteenth word in a sentence is interesting", "sentence");
    text.put("The sixteenth word in a paragraph is interesting", "paragraph");
    text.put("The seventeenth word in a sentence is interesting", "sentence");
    text.put("The nineteenth word in a document is interesting", "document");
    text.put("The twentieth word in a sentence is interesting", "sentence");
    text.put("The twenty-first word in a paragraph is interesting", "paragraph");
    text.put("The twenty-second word in a sentence is interesting", "sentence");
    text.put("The twenty-third word in a document is interesting", "document");
    text.put("The twenty-fourth word in a document is interesting", "document");
    text.put("The twenty-fifth word in a document is interesting", "document");
    text.put("The twenty-sixth word in a document is interesting", "document");

    String rootPattern;

    try (Transaction tx = db.beginTx()) {
        rootPattern = (String) rootNode.getProperty("pattern");
        tx.success();
    }

    String input = "The last word in a document is interesting";
    classifyInput(db, graphManager, rootPattern, input);
    input = "The nineteenth word in a sentence is interesting";
    classifyInput(db, graphManager, rootPattern, input);
    input = "The fiftieth word in a paragraph is interesting";
    classifyInput(db, graphManager, rootPattern, input);


}
 
Example 18
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);
			}
		}

	}
}
 
Example 19
Source File: User.java    From metalcon with GNU General Public License v3.0 2 votes vote down vote up
/**
 * create a new user instance from Neo4j user node
 * 
 * @param userNode
 *            Neo4j node representing the creator
 */
public User(final Node userNode) {
	this.id = (String) userNode.getProperty(Properties.User.IDENTIFIER);
	this.displayName = (String) userNode
			.getProperty(Properties.User.DISPLAY_NAME);
}
 
Example 20
Source File: TemplateItemInfo.java    From metalcon with GNU General Public License v3.0 2 votes vote down vote up
/**
 * create basic status update item information from a neo4j node
 * 
 * @param node
 *            neo4j template item node
 */
public TemplateItemInfo(final Node node) {
	this.name = (String) node.getProperty(Properties.Templates.ITEM_NAME);
}