1 16 package org.apache.myfaces.custom.tree2; 17 18 import javax.faces.component.NamingContainer; 19 20 import java.util.StringTokenizer ; 21 import java.util.ArrayList ; 22 23 31 public class TreeModel 32 { 33 private final static String SEPARATOR = String.valueOf(NamingContainer.SEPARATOR_CHAR); 34 35 private TreeNode root; 36 private TreeNode currentNode; 37 38 42 public TreeModel(TreeNode root) 43 { 44 this.root = root; 45 } 46 47 51 public TreeNode getNode() 52 { 53 return currentNode; 54 } 55 56 63 public void setNodeId(String nodeId) 64 { 65 if (nodeId == null) 66 { 67 currentNode = null; 68 return; 69 } 70 71 currentNode = getNodeById(nodeId); 72 } 73 74 83 public String [] getPathInformation(String nodeId) 84 { 85 if (nodeId == null) 86 { 87 throw new IllegalArgumentException ("Cannot determine parents for a null node."); 88 } 89 90 ArrayList pathList = new ArrayList (); 91 pathList.add(nodeId); 92 93 while (nodeId.lastIndexOf(SEPARATOR) != -1) 94 { 95 nodeId = nodeId.substring(0, nodeId.lastIndexOf(SEPARATOR)); 96 pathList.add(nodeId); 97 } 98 99 String [] pathInfo = new String [pathList.size()]; 100 101 for (int i=0; i < pathInfo.length; i++) 102 { 103 pathInfo[i] = (String )pathList.get(pathInfo.length - i - 1); 104 } 105 106 return pathInfo; 107 } 108 109 116 public boolean isLastChild(String nodeId) 117 { 118 if (nodeId.lastIndexOf(SEPARATOR) == -1) 119 { 120 return true; 122 } 123 124 String parentId = nodeId.substring(0, nodeId.lastIndexOf(SEPARATOR)); 126 String childString = nodeId.substring(nodeId.lastIndexOf(SEPARATOR) + 1); 127 int childId = Integer.parseInt(childString); 128 TreeNode parentNode = getNodeById(parentId); 129 130 return childId + 1== parentNode.getChildCount(); 131 } 132 133 private TreeNode getNodeById(String nodeId) 134 { 135 TreeNode node = root; 136 137 StringBuffer sb = new StringBuffer (); 138 StringTokenizer st = new StringTokenizer (nodeId, SEPARATOR); 139 sb.append(st.nextToken()).append(SEPARATOR); 140 141 while (st.hasMoreTokens()) 142 { 143 int nodeIndex = Integer.parseInt(st.nextToken()); 144 sb.append(nodeIndex); 145 146 try 147 { 148 node = (TreeNode)node.getChildren().get(nodeIndex); 149 } 150 catch (IndexOutOfBoundsException e) 151 { 152 String msg = "Node with id " + sb.toString() + ". Failed to parse " + nodeId; 153 throw new IllegalArgumentException (msg); 154 } 155 sb.append(SEPARATOR); 156 } 157 158 return node; 159 } 160 } 161 | Popular Tags |