1 29 package jegg.type; 30 31 import java.util.Collection ; 32 import java.util.HashSet ; 33 import java.util.Iterator ; 34 35 import org.apache.commons.logging.Log; 36 import org.apache.commons.logging.LogFactory; 37 38 41 public class Node 42 { 43 private static final Log LOG = LogFactory.getLog(Node.class); 44 45 private Class type; 46 private Object cookie; 47 private Collection branches = new HashSet (); 48 49 public Node(Class t) 50 { 51 super(); 52 type = t; 53 } 54 public Node(Class t, Object c) 55 { 56 this(t); 57 cookie = c; 58 } 59 public Class getType() 60 { 61 return type; 62 } 63 public Object getCookie() 64 { 65 return cookie; 66 } 67 68 public void setCookie(Object o) 69 { 70 cookie = o; 71 } 72 73 public boolean insert(Node nd) 74 { 75 Class nd_type = nd.getType(); 76 Class this_type = getType(); 77 78 if (this_type.isAssignableFrom(nd_type)) 79 { 80 if (!this_type.equals(nd_type)) 81 { 82 for (Iterator it = branches.iterator(); it.hasNext(); ) 83 { 84 Node cn = (Node) it.next(); 85 Class cn_type = cn.getType(); 86 if (cn_type.isAssignableFrom(nd_type)) 87 { 88 if (LOG.isDebugEnabled()) 89 LOG.debug("Inserting "+nd_type.getName()+" under node "+cn_type.getName()); 90 if (cn.insert(nd)) 91 { 92 return true; 93 } 94 } 95 else 96 if (nd_type.isAssignableFrom(cn_type)) 97 { 98 if (LOG.isDebugEnabled()) 99 LOG.debug("Moving node "+cn_type.getName()+" from node "+this_type.getName()+" to node "+nd_type.getName()); 100 if (nd.insert(cn)) 101 { 102 it.remove(); 103 } 105 } 106 } 107 addChild(nd); 108 } 109 else 110 { 111 setCookie(nd.getCookie()); 112 } 113 return true; 114 } 115 return false; 116 } 117 118 protected Collection getBranches() 119 { 120 return branches; 121 } 122 123 protected void addChild(Node nd) 124 { 125 branches.add(nd); 127 } 128 129 protected void removeChild(Node nd) 130 { 131 branches.remove(nd); 132 } 133 134 public Node findNearest(Class c) 135 { 136 Class this_type = getType(); 137 if (this_type.equals(c)) 138 { 139 return this; 140 } 141 if (getType().isAssignableFrom(c)) 142 { 143 for (Iterator it = branches.iterator(); it.hasNext(); ) 144 { 145 Node cn = (Node) it.next(); 146 Node fn = cn.findNearest(c); 147 if (null != fn) 148 { 149 return fn; 150 } 151 } 152 return this; 153 } 154 return null; 155 } 156 } 157 | Popular Tags |