Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm facing the following issue and I've been racking my brain looking for a solution, but nothing comes to my mind by now:

I have a file system hierarchy, something like:

/HANDLERS/HANDLER1
/HANDLERS/HANDLER2
/HANDLERS/HANDLER3

and

/MODULES/PROGRAMMING/PROGRAMMER1
/MODULES/PROGRAMMING/PROGRAMMER2
/MODULES/PROGRAMMING/PROGRAMMER3

/MODULES/TESTING/TESTING1
/MODULES/TESTING/TESTING2

and so on.

I want to create a "tree" assuming "/" which is the root is already created. And the structure shown in the image I attach is the goal.

enter image description here

I need a method called

void createNode(String path){

}

In my requirements, this method will always receive the full path and do something like the following:

void create(String fullPath){
 //Here I use a method which splits the fullPath into a String array to get every part that will represent a node, for example, if the fullPath is /MODULE/PROGRAMMING/PROHRAMMER1 I use:
String[] singleNodes = separateNodes(fullPath);//I get:MODULE,PROGRAMMING AND PROGRAMMER
//Then I use a loop to iterate the elements

for (String s : singleNodes) {
}
//WHAT CAN I DO HERE?
}

But I don't have idea on how to work inside the loop, I need to check if the node exists, if it exists, I just have to add the missing part, for instance, if I send /MODULES/PROGRAMMING/PROGRAMMER1, if I send for the very first time, it will create the whole thing, but if then I send /MODULES/PROGRAMMING/PROGRAMMER2, it just have to add PROGRAMMER2.

If somebody could help me I will really appretiate it, thanks in advance.

share|improve this question
You have the logic, just put it into code. – Sotirios Delimanolis Apr 24 at 14:23
There are numerous scripts around for generating hierarchy trees or family trees. I think you'd be best off using one of these scripts, why reinvent the wheel, right? – Aquillo Apr 24 at 14:24
I know that there are many scripts, but I'm facing an issue related with zookeeper, which is strict with nodes and trees. – Marcelo Tataje Apr 24 at 14:28

4 Answers

How to convert a filepath into a hierarchy in Java

Node createNode(String path) {
    File location = new File(path);
    File[] children = file.listFiles();
    Node node = new Node(location.getName());

    if(location.isDirectory()) {
        List<Node> children = new ArrayList();
        for(File child : children) {
            children.add(createNode(child.getPath()));
        }
        node.setChildren(children);
    }
    return node;
}

class Node {
    String name;
    List<Node> children;
}

You could call this by createNode(myRoot)

share|improve this answer
pretty cool code, but, actually it does not fits what I want to do, I keep on working in the logic. Thanks anyway, this can help me a clue on how to work the new logic I'm implementing. – Marcelo Tataje Apr 24 at 14:43
What are you looking for? A way to directly display this hierarchy? – Aquillo Apr 24 at 14:46
I was looking for a way just to create the tree structure, it does not matter if works with files or not, I was just focusing on how can I implement the structure of the tree with the validations I mentioned in the question. – Marcelo Tataje Apr 24 at 15:01
Well, depends...what's your frontend? A website or a desktop application or an android app or... – Aquillo Apr 24 at 15:15

disclaimer: not tested, no error checking, no getters/setters.

package com.jorge.teste;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static class Tree<T> {
        Node<T> root;

        public static class Node<T> {
            T data;

            Node<T> parent;

            List<Node<T>> children = new ArrayList<Main.Tree.Node<T>>();

            public Node(final T data, final Node<T> parent) {
                this.data = data;
                this.parent = parent;
            }
        }
    }

    public static Tree<String> tree = new Tree<String>();

    public static void createNode(final String path) {
        String[] parts = path.split("/");
        Tree.Node<String> parent = null;
        for (String part : parts) {
            if (parent == null) {
                if (tree.root == null) {
                    tree.root = new Tree.Node<String>(part, null);
                }
                parent = tree.root;
            } else {
                Tree.Node<String> found = null;
                for (Tree.Node<String> child : parent.children) {
                    if (child.data.equals(part)) {
                        found = child;
                        break;
                    }
                }

                if (found == null) {
                    parent.children.add(found = new Tree.Node<String>(part, parent));
                }

                parent = found;
            }
        }
    }

    public static void main(final String[] args) {
        createNode("/a/b/c");
        createNode("/a/b/c/d");
    }
}
share|improve this answer

If you want to stick with the loop you have currently then you should try something like this (i am assuming you already have the root node as you stated above)

Node currentNode = rootNode; 
for (String s : singleNodes) {
     if( currentNode.hasChild(s) ) currentNode = currentNode.getChild(s);
     else currentNode = currentNode.createChild(s);
}

assuming here that createChild(s) returns the created Node which maybe it shouldn't. but that's not really the problem

but in all honesty I dont think this should be done using a loop, Trees are usually better handled using recursion.

share|improve this answer
up vote 0 down vote accepted

I managed to do it finally and it fits my requirements, it is related to a question I asked for zookeeper.

Best regards.

public void createNode(NodePath nodePath, NodeData nodeData, NodeRights nodeRights, NodeCreationHandler nodeCreationHandler) throws KeeperException, InterruptedException, ZookeeperCreationException {

        if (zk == null) {
            throw new ZookeeperCreationException("The zookeeper client has not been instanced.");
        }       
        String targetPath = nodePath.getFullNodePath();
        logger.warn("full path: " + targetPath);
        targetPath = targetPath.substring(1, targetPath.length());
        logger.warn("full path mod: " + targetPath);
        byte[] serializedData = nodeData.serialize(new Object());
        String[] array = targetPath.split(ICoordinationConstants.BASE_ROOT_SPTR);
        String acum="";
        for (int i = 0; i < array.length-1; i++) {
            acum+=(ICoordinationConstants.BASE_ROOT_SPTR+array[i]);
            logger.warn("acum: " + acum);
            if (zk.exists(acum, null) == null) {
                logger.warn("It does not exists, proceed to create it...");
                zk.create(acum, serializedData, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        }
        zk.create(acum+ICoordinationConstants.BASE_ROOT_SPTR+array[array.length-1], serializedData, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);             
    }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.