01: package net.sourceforge.jaxor.parser;
02:
03: import org.xml.sax.Attributes;
04: import org.xml.sax.Locator;
05: import org.xml.sax.SAXException;
06: import org.xml.sax.helpers.DefaultHandler;
07: import org.xml.sax.helpers.LocatorImpl;
08:
09: import java.lang.reflect.Method;
10: import java.util.HashMap;
11: import java.util.Map;
12: import java.util.Stack;
13:
14: /*
15: * User: Mike
16: * Date: Oct 21, 2002
17: * Time: 11:31:37 PM
18: */
19:
20: public class DynamicParser extends DefaultHandler {
21:
22: private final Stack _stack = new Stack();
23: private Map _aliasMap = new HashMap();
24: private XmlProxy _root;
25: private Locator _locator = new LocatorImpl();
26:
27: public DynamicParser(Object root) {
28: _root = new XmlProxy(root, _locator);
29: _stack.push(_root);
30: }
31:
32: public void setDocumentLocator(Locator locator) {
33: super .setDocumentLocator(locator);
34: _locator = locator;
35: }
36:
37: public void addAlias(String alias, Class cl) {
38: _aliasMap.put(alias.toLowerCase(), cl);
39: }
40:
41: public void startElement(String s, String s1, String name,
42: Attributes attributes) throws SAXException {
43: Object object = findObject(name);
44: XmlProxy proxy = new XmlProxy(object, _locator);
45: proxy.setAll(attributes);
46: _stack.push(proxy);
47: }
48:
49: public void characters(char[] chars, int i, int i1)
50: throws SAXException {
51: String s = new String(chars, i, i1).trim();
52: if (s.length() == 0) {
53: return;
54: }
55: XmlProxy proxy = (XmlProxy) _stack.peek();
56: proxy.add("CharacterData", new String(chars, i, i1));
57: }
58:
59: public void endElement(String s, String s1, String name)
60: throws SAXException {
61: XmlProxy xmlElement = (XmlProxy) _stack.pop();
62: XmlProxy xml = (XmlProxy) _stack.peek();
63: xml.setElement(xmlElement.getObject(), name);
64: }
65:
66: private Object findObject(String s) {
67: Class toker = (Class) _aliasMap.get(s.toLowerCase());
68: if (toker != null)
69: return createInstance(toker);
70: XmlProxy xmlProxy = ((XmlProxy) _stack.peek());
71: Object object = xmlProxy.getObject();
72: Method[] methods = object.getClass().getMethods();
73: for (int i = 0; i < methods.length; i++) {
74: Method method = methods[i];
75: Class[] params = method.getParameterTypes();
76: if (params.length == 1) {
77: String name = getNameFromClass(params[0]);
78: if (name.equalsIgnoreCase(s))
79: return createInstance(params[0]);
80: }
81: }
82: throw new ParseException("Unknown Element: " + s, _locator);
83: }
84:
85: private Object createInstance(Class clazz) {
86: try {
87: return clazz.newInstance();
88: } catch (InstantiationException e) {
89: throw new ParseException(e, _locator);
90: } catch (IllegalAccessException e) {
91: throw new ParseException(e, _locator);
92: }
93: }
94:
95: public static String getNameFromClass(Class clazz) {
96: return clazz.getName().substring(
97: clazz.getName().lastIndexOf(".") + 1);
98: }
99: }
|