1 25 package org.snipsnap.graph; 26 27 import org.snipsnap.container.Components; 28 import org.snipsnap.graph.builder.TreeBuilder; 29 import org.snipsnap.graph.graph.Tree; 30 import org.snipsnap.graph.graph.TreeNode; 31 import org.snipsnap.snip.Snip; 32 import org.snipsnap.snip.SnipSpace; 33 34 public class NameSpaceTreeBuilder implements TreeBuilder { 35 private String root; 36 37 public NameSpaceTreeBuilder(String root) { 38 this.root = root; 39 } 40 41 public Tree build() { 42 SnipSpace space = (SnipSpace) Components.getComponent(SnipSpace.class); 43 44 Snip[] snips = space.match(root); 45 46 if (root.endsWith("/")) { 47 root = root.substring(0, root.length() - 1); 48 } 49 50 TreeNode parent = new TreeNode(root); 51 TreeNode lastNode = parent; 52 Tree tree = new Tree(parent); 53 54 int depth = -1; 55 int currentDepth = -1; 56 for (int i = 0; i < snips.length; i++) { 57 Snip snip = snips[i]; 58 String elements[] = snip.getName().split("/"); 59 currentDepth = elements.length - 1; 60 String element = elements[currentDepth]; 61 62 if (-1 == depth) { 63 depth = currentDepth; 64 } 65 if (currentDepth > depth) { 66 depth = currentDepth; 67 TreeNode child = new TreeNode(element, lastNode); 68 parent = lastNode; 69 parent.addChild(child); 70 lastNode = child; 71 } else if (currentDepth < depth) { 72 depth = currentDepth; 73 parent = parent.getParent(); 74 TreeNode child = new TreeNode(element, parent); 75 parent.addChild(child); 76 lastNode = child; 77 } else { 78 TreeNode child = new TreeNode(element, parent); 79 parent.addChild(child); 80 lastNode = child; 81 } 82 } 83 89 System.err.println("Tree=" + tree); 90 System.err.println("Tree depth=" + tree.getDepth()); 91 return tree; 92 } 93 } 94 | Popular Tags |