1
2
3
4
5
6
7
8 package org.dom4j.bean;
9
10 import org.dom4j.Attribute;
11 import org.dom4j.DocumentFactory;
12 import org.dom4j.Element;
13 import org.dom4j.QName;
14 import org.dom4j.tree.DefaultAttribute;
15
16 import org.xml.sax.Attributes;
17
18 /***
19 * <p>
20 * <code>BeanDocumentFactory</code> is a factory of DOM4J objects which may be
21 * BeanElements which are backed by JavaBeans and their properties.
22 * </p>
23 *
24 * <p>
25 * The tree built allows full XPath expressions from anywhere on the tree.
26 * </p>
27 *
28 * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
29 * @version $Revision: 1.14 $
30 */
31 public class BeanDocumentFactory extends DocumentFactory {
32 /*** The Singleton instance */
33 private static BeanDocumentFactory singleton = new BeanDocumentFactory();
34
35 /***
36 * <p>
37 * Access to the singleton instance of this factory.
38 * </p>
39 *
40 * @return the default singleon instance
41 */
42 public static DocumentFactory getInstance() {
43 return singleton;
44 }
45
46
47 public Element createElement(QName qname) {
48 Object bean = createBean(qname);
49
50 if (bean == null) {
51 return new BeanElement(qname);
52 } else {
53 return new BeanElement(qname, bean);
54 }
55 }
56
57 public Element createElement(QName qname, Attributes attributes) {
58 Object bean = createBean(qname, attributes);
59
60 if (bean == null) {
61 return new BeanElement(qname);
62 } else {
63 return new BeanElement(qname, bean);
64 }
65 }
66
67 public Attribute createAttribute(Element owner, QName qname, String value) {
68 return new DefaultAttribute(qname, value);
69 }
70
71
72 protected Object createBean(QName qname) {
73 return null;
74 }
75
76 protected Object createBean(QName qname, Attributes attributes) {
77 String value = attributes.getValue("class");
78
79 if (value != null) {
80 try {
81 Class beanClass = Class.forName(value, true,
82 BeanDocumentFactory.class.getClassLoader());
83
84 return beanClass.newInstance();
85 } catch (Exception e) {
86 handleException(e);
87 }
88 }
89
90 return null;
91 }
92
93 protected void handleException(Exception e) {
94
95 System.out.println("#### Warning: couldn't create bean: " + e);
96 }
97 }
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134