1 7 8 package org.dom4j.io; 9 10 import java.util.ArrayList ; 11 import java.util.HashMap ; 12 13 import org.dom4j.Element; 14 import org.dom4j.ElementHandler; 15 import org.dom4j.ElementPath; 16 17 32 class DispatchHandler implements ElementHandler { 33 34 private boolean atRoot; 35 36 37 private String path; 38 39 40 private ArrayList pathStack; 41 42 43 private ArrayList handlerStack; 44 45 49 private HashMap handlers; 50 51 55 private ElementHandler defaultHandler; 56 57 public DispatchHandler() { 58 atRoot = true; 59 path = "/"; 60 pathStack = new ArrayList (); 61 handlerStack = new ArrayList (); 62 handlers = new HashMap (); 63 } 64 65 75 public void addHandler(String handlerPath, ElementHandler handler) { 76 handlers.put(handlerPath, handler); 77 } 78 79 88 public ElementHandler removeHandler(String handlerPath) { 89 return (ElementHandler) handlers.remove(handlerPath); 90 } 91 92 101 public boolean containsHandler(String handlerPath) { 102 return handlers.containsKey(handlerPath); 103 } 104 105 113 public ElementHandler getHandler(String handlerPath) { 114 return (ElementHandler) handlers.get(handlerPath); 115 } 116 117 123 public int getActiveHandlerCount() { 124 return handlerStack.size(); 125 } 126 127 136 public void setDefaultHandler(ElementHandler handler) { 137 defaultHandler = handler; 138 } 139 140 144 public void resetHandlers() { 145 atRoot = true; 146 path = "/"; 147 pathStack.clear(); 148 handlerStack.clear(); 149 handlers.clear(); 150 defaultHandler = null; 151 } 152 153 158 public String getPath() { 159 return path; 160 } 161 162 public void onStart(ElementPath elementPath) { 164 Element element = elementPath.getCurrent(); 165 166 pathStack.add(path); 168 169 if (atRoot) { 171 path = path + element.getName(); 172 atRoot = false; 173 } else { 174 path = path + "/" + element.getName(); 175 } 176 177 if ((handlers != null) && (handlers.containsKey(path))) { 178 ElementHandler handler = (ElementHandler) handlers.get(path); 181 handlerStack.add(handler); 182 183 handler.onStart(elementPath); 185 } else { 186 if (handlerStack.isEmpty() && (defaultHandler != null)) { 189 defaultHandler.onStart(elementPath); 190 } 191 } 192 } 193 194 public void onEnd(ElementPath elementPath) { 195 if ((handlers != null) && (handlers.containsKey(path))) { 196 ElementHandler handler = (ElementHandler) handlers.get(path); 199 handlerStack.remove(handlerStack.size() - 1); 200 201 handler.onEnd(elementPath); 203 } else { 204 if (handlerStack.isEmpty() && (defaultHandler != null)) { 207 defaultHandler.onEnd(elementPath); 208 } 209 } 210 211 path = (String ) pathStack.remove(pathStack.size() - 1); 213 214 if (pathStack.size() == 0) { 215 atRoot = true; 216 } 217 } 218 } 219 220 256 | Popular Tags |