Breadth First Neo4j tree traversal and TreeNode creation - java

I have a Neo4j graph database which maps a file system structure consisting of nodes representing folders and files.
Each node has a FATHER_OF and a CHILD_OF relationship.
Now I need to create a TreeNode structure in Java starting from the Neo4j graph: currently I implemented a breadth first print of the NEO4J structure as follows:
public Traverser getTraverser()
{
Transaction tx = graphDb.beginTx();
Traverser traverser = traverseStorage(rootNode);
return traverser;
}
private static Traverser traverseStorage(final Node startNode) {
TraversalDescription td = Traversal.description()
.breadthFirst()
.relationships(GraphStorage.RelTypes.FATHER_OF, Direction.OUTGOING);
return td.traverse(startNode);
}
Now I'm trying to create a Tree using the above breadth-first traverser but can't figure out how to properly assign the correct parent to each node.
TreeNode root = new DefaultTreeNode("root", null);
Traverser traverser = graphStorage.getTraverser();
TreeNode parent = root;
for (Path directoryPath : traverser) {
DefaultTreeNode tmp1 = new DefaultTreeNode((String)directoryPath.endNode().getProperty("name"), parent);
}
I hoped there was something like directoryPath.endNode().getParent() but apparently there isn't.
I'm searching for a solution which doesn't require me to use Cypher query language, any help?

Ok found out, just need a HashMap to map Neo4j node id's to TreeNode objects:
HashMap<Long, TreeNode> treeNodeMap = new HashMap();
then the rest becomes:
TreeNode root = new DefaultTreeNode("root", null);
Traverser traverser = graphStorage.getTraverser();
TreeNode parent = root;
Relationship parentRelationship = directoryPath.endNode().getSingleRelationship(
GraphStorage.RelTypes.CHILD_OF, Direction.OUTGOING);
if (parentRelationship != null) {
Node parentFileNode = parentRelationship.getEndNode();
if (parentFileNode != null) {
long parentId = parentFileNode.getId();
parent = treeNodeMap.get(new Long(parentId));
}
DefaultTreeNode tmp1 = new DefaultTreeNode((String)directoryPath.endNode().getProperty("name"), parent);
treeNodeMap.put(new Long(directoryPath.endNode().getId()), tmp1);
}
The above correctly works.

Related

Selecting the leaf of jtree that will open another jrame in netbeans

Good day,
I am trying to create a tree view in order to display for the user the other j Frames in Netbeans.
When the user select a leaf, it will display for him the required forum.
What I am facing right now that when selecting the other leaves, it is display for me all forums.
Here is my codes
private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
jTree1.getLastSelectedPathComponent();
if (node == null) return;
Object nodeInfo = node.getUserObject();
jTree1.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
JTree tree = new JTree();
Employee emp = new Employee();
rectutment rec = new rectutment();
interview inter = new interview();
DefaultMutableTreeNode firstLeaf = ((DefaultMutableTreeNode)tree.getModel().getRoot()).getFirstLeaf();
tree.setSelectionPath(new TreePath(firstLeaf.getPath()));
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
root.add(firstLeaf);
firstLeaf.add(new DefaultMutableTreeNode("firstleaf"));
model.reload();
emp.add(tree);
emp.pack();
emp.setVisible(true);
if ( emp.isActive()&& rec.isActive()){
emp.dispose();
}
else{
rec.dispose();
}
rec.setDefaultCloseOperation(emp.EXIT_ON_CLOSE);
rec.setLocationRelativeTo(emp);
rec.add(tree);
rec.pack();
rec.setVisible(true);
}
Any ideas?

Unable to delete a Node in jackrabbit

I am trying to delete a Node which I have saved using jackrabbit but I get this error.
Failed to delete file
! javax.jcr.nodetype.ConstraintViolationException: Unable to perform operation. Node is protected.
Here is the code I have used to save it:
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
Node parent = (Node) itemAtPath(parentPath, session);
Node newNode = parent.addNode(nodeName);
newNode.addMixin("mix:versionable");
session.save(); // Create Root Node
VersionableChanges changes = new VersionableChanges(newNode.getSession());
changes.checkout(newNode);
Binary binary = session.getValueFactory().createBinary(in);
newNode.setProperty(PROPERTY_DATA, binary);
newNode.setProperty(PROPERTY_NAME, fileName + System.currentTimeMillis());
newNode.setProperty(PROPERTY_CREATEDBY, createdBy);
newNode.setProperty(PROPERTY_CREATEDDATE, createdDate);
newNode.setProperty(PROPERTY_COMMENT, comment);
Value value = session.getValueFactory().createValue(binary);
changes.checkin();
session.save();
Here is the code I am using to delete it:
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
Version fileVersion = null;
Node fileNode = null;
if (version != null && !version.isEmpty()) {
fileVersion = session.getWorkspace().getVersionManager().getVersionHistory(path).getVersion(version);
} else {
fileVersion = session.getWorkspace().getVersionManager().getBaseVersion(path);
}
fileNode = fileVersion.getFrozenNode();
fileNode.remove();
//need to save session to persist the remove operation
session.save();
How can I overcome this error?
Frozen nodes are protected because deleting them would (maybe) put the version store in a corrupted state. In order to remove a "complete" version from the history, you have to something like this:
VersionHistory history = session.getWorkspace().getVersionManager()
.getVersionHistory(info.getVersionedNodePath());
history.removeVersion(info.getVersionName());
session.save();

Call graphs in Soot

How do I use SOOT to build at Call graph? Or are there any better programs for this? I have been sent around the same five pages looking for answers and I can't find what I am looking for. There are also a problem with the plugin version to Eclipse. It is installed correct but I cant choose it when I want to run the code.
Small modification to previous answer
private static void visit(CallGraph cg, SootMethod method) {
String identifier = method.getSignature();
visited.put(method.getSignature(), true);
dot.drawNode(identifier);
// iterate over unvisited parents
Iterator<MethodOrMethodContext> ptargets = new Sources(cg.edgesInto(method));
if (ptargets != null) {
while (ptargets.hasNext()) {
SootMethod parent = (SootMethod) ptargets.next();
if (!visited.containsKey(parent.getSignature())) visit(cg, parent);
}
}
Here are some examples include call graph for Java. http://www.brics.dk/SootGuide/
And call graph for apk.
https://github.com/secure-software-engineering/soot-infoflow/issues/38
If you want to get the dot file, you can iterate over the callgraph and write the contents out in dot format like this.
private static void visit(CallGraph cg, SootMethod method) {
String identifier = method.getSignature();
visited.put(method.getSignature(), true);
dot.drawNode(identifier);
// iterate over unvisited parents
Iterator<MethodOrMethodContext> ptargets = new Targets(cg.edgesInto(method));
if (ptargets != null) {
while (ptargets.hasNext()) {
SootMethod parent = (SootMethod) ptargets.next();
if (!visited.containsKey(parent.getSignature())) visit(cg, parent);
}
}
// iterate over unvisited children
Iterator<MethodOrMethodContext> ctargets = new Targets(cg.edgesOutOf(method));
if (ctargets != null) {
while (ctargets.hasNext()) {
SootMethod child = (SootMethod) ctargets.next();
dot.drawEdge(identifier, child.getSignature());
System.out.println(method + " may call " + child);
if (!visited.containsKey(child.getSignature())) visit(cg, child);
}
}
}

Groovy could not find matching constructor

Could somebody explain to me why this simple piece of code will not compile?
Node.groovy
class Node{
Integer key
String value
Node leftNode
Node rightNode
Node(){}
Node(Integer k, String v){
this.key = k
this.value = v
}
}
BinaryTree.groovy
class BinaryTree{
Node root;
def addNode(k, v){
def newNode = new Node(k,v)
if(!root){
root = newNode
}else{
Node currentNode = root
Node parent
while(true){
parent = currentNode
if(k < currentNode.key) {
currentNode = currentNode.leftNode
if(!currentNode){
parent.leftNode = newNode
return
}
} else {
currentNode = currentNode.rightNode
if(!currentNode){
parent.rightNode = newNode
return
}
}
}
}
}
def inOrderTraversal(def node, def silent){
if(node){
inOrderTraversal(node.leftNode)
!silent ?: println("Node ${node.dump()}")
inOrderTraversal(node.rightNode)
}
}
}
Main.groovy
//Test the binaryTree Project
binaryTree = new BinaryTree();
binaryTree.addNode(45, "v1")
binaryTree.addNode(60, "v4")
binaryTree.addNode(12, "v3")
binaryTree.addNode(32, "v9")
binaryTree.addNode(415, "v7")
binaryTree.inOrderTraversal(binaryTree.root, false)
3 simple files. This is that I get when I press play in intellij, or when I try to run this: groovy -cp ./src src/Main.groovy
Caught: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: groovy.util.Node(java.lang.Integer, java.lang.String)
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: groovy.util.Node(java.lang.Integer, java.lang.String)
at BinaryTree.addNode(BinaryTree.groovy:7)
at BinaryTree$addNode.call(Unknown Source)
at Main.run(Main.groovy:4)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
The constructor in Node looks fine to me.
I am using Java 8 and groovy 2.4
Thanks

JSF/ICEfaces Dynamic hierarchy tree example

i have list of departments and each department might have a parent or not,department domain object is as follows:
- departmentId
- parentDepartmentId (null if current department has no parent i,e should be under root directly, and have value if current department have parent).
.
.
.
looking at icefaces tutorial code for creating basic tree:
// create root node with its children expanded
DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
IceUserObject rootObject = new IceUserObject(rootTreeNode);
rootObject.setText("Root Node");
rootObject.setExpanded(true);
rootTreeNode.setUserObject(rootObject);
// model is accessed by by the ice:tree component via a getter method, this object is what's needed in the view to display the tree
model = new DefaultTreeModel(rootTreeNode);
// add some child nodes
for (int i = 0; i <3; i++) {
DefaultMutableTreeNode branchNode = new DefaultMutableTreeNode();
IceUserObject branchObject = new IceUserObject(branchNode);
branchObject.setText("node-" + i);
branchNode.setUserObject(branchObject);
rootTreeNode.add(branchNode);
}
it's all about constructing basic node, and adding childs.
my case is complex that child A which is under root may have child nodes B,C,D and D have for example child nodes and so on so on.
so i am thinking of a best practice about how to accomplish something like that, i need a sample code or hints if anyone can help.
You would need a recursive method to construct the tree from your model.
public void buildRecursiveTreeNode(DefaultMutableTreeNode parentTreeNode,
String treeId, String treeName, GenericTreeVo modelVo)
{
// if the database model contains more children.
// add the current nodes first and pass in this nodes tree id and name to construct the children for this parent nodes.
}
Updated answer to include recursion example.
http://www.danzig.us/java_class/recursion.html
just added a recursion link, all I am saying is when you iterate the data from the database, you would see if you have any child records, if you have child records you would call the same method by passing the DefaultMutableTreeNode and that would become the parent.
finally i was able to do it as follows:
List<Department> departmentList = getAllDepartments();
// create root node with its children expanded
DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
IceUserObject rootObject = new IceUserObject(rootTreeNode);
rootObject.setText("Root");
rootObject.setExpanded(true);
rootTreeNode.setUserObject(rootObject);
HashMap<Department, DefaultMutableTreeNode> createdNodesMap = new HashMap<Department, DefaultMutableTreeNode>(
0);
for (Department department : departmentList) {
DefaultMutableTreeNode currentNode = null;
if (createdNodesMap.get(department) == null) {
log.debug("############ CREATING NODE "
+ department.getName());
currentNode = new DefaultMutableTreeNode();
IceUserObject currentObject = new IceUserObject(currentNode);
currentObject.setText(department.getName());
currentObject.setExpanded(true);
currentNode.setUserObject(currentObject);
if (department.getParentDepartment() == null) {
rootTreeNode.add(currentNode);
log.debug("######### NODE " + department.getName()
+ " ADDED UNDER ROOT");
}
createdNodesMap.put(department, currentNode);
} else {
log.debug("############ GETTING CREATED NODE "
+ department.getName());
currentNode = createdNodesMap.get(department);
}
if (department.getChildren().size() > 0)
log.debug("############ NODE " + department.getName()
+ " HAVE " + department.getChildren().size()
+ " CHILDREN");
else
log.debug("############ NODE " + department.getName()
+ " DOES NOT HAVE CHILDREN");
for (Department department2 : department.getChildren()) {
log.debug("############ CREATING CHILD "
+ department2.getName() + " FOR PARENT "
+ department.getName());
DefaultMutableTreeNode branchNode;
if (createdNodesMap.get(department2) == null) {
branchNode = new DefaultMutableTreeNode();
IceUserObject branchObject = new IceUserObject(
branchNode);
branchObject.setText(department2.getName());
branchObject.setExpanded(true);
branchNode.setUserObject(branchObject);
} else
branchNode = createdNodesMap.get(department2);
createdNodesMap.put(department2, branchNode);
currentNode.add(branchNode);
}
}
model = new DefaultTreeModel(rootTreeNode);
Check http://click.avoka.com/click-examples/tree/checkbox-tree-page.htm
The latter is done via the Apache Click framework. Right now I'm developing a project where this data structure (hierarchy tree) is heavily used. You can set the root node or if you need to have several starting points, you can create a wildcard root node that won't affect the functionality, the subclasses, like others have commented, need to be created recursively.

Categories

Resources