/Users/lyon/j4p/src/classUtils/pack/util/xml/configuration/BaseConfigurator.java
|
1 package classUtils.pack.util.xml.configuration;
2
3 import org.xml.sax.SAXException;
4 import org.xml.sax.helpers.DefaultHandler;
5
6 /**
7 * A base {@link Configurator Configurator}.
8 * <p>
9 * This class extends SAX's <tt>DefaultHandler</tt> and provides support
10 * for:
11 * <p>
12 * <ul>
13 * <li> collecting text (via the {@link #characters(char[], int, int)
14 * characters()} method);
15 * <li> ensuring that {@link #getConfiguredObject() getConfiguredObject()}
16 * throws an exception if parsing hasn't completed yet (via the
17 * {@link #checkCompleted() checkCompleted()} method).
18 * </ul>
19 * <p>
20 * Subclasses which override {@link #endElement(java.lang.String,
21 * java.lang.String, java.lang.String) endElement()} should either invoke
22 * this class' implementation or set to <b>true</b> the protected
23 * <b>{@link #completed completed}</b> field when the configured object
24 * is complete.
25 *
26 * @author Cristiano Sadun
27 */
28 public abstract class BaseConfigurator extends DefaultHandler implements Configurator {
29
30 /**
31 * The buffer collecting text received by {@link #characters(char[], int, int)
32 * characters()}.
33 */
34 protected StringBuffer buffer;
35
36 /**
37 * Indicate that the object built from the XML is ready.
38 */
39 protected boolean completed;
40
41 /**
42 * Constructor for BaseConfigurator.
43 */
44 public BaseConfigurator() {
45 this.buffer = new StringBuffer();
46 this.completed = false;
47 }
48
49 /**
50 * Set {@link #completed completed} to true.
51 *
52 *
53 */
54 public void endElement(
55 String namespaceURI,
56 String localName,
57 String qName) {
58 completed = true;
59 }
60
61 /**
62 * @see Configurator#getConfiguredObject()
63 */
64 public final Object getConfiguredObject() {
65 checkCompleted();
66 return doGetConfiguredObject();
67 }
68
69 /**
70 * Throw an IllegalStateException if {@link #completed completed} is not <b>true</b>.
71 */
72 protected void checkCompleted() {
73 if (!completed)
74 throw new IllegalStateException("The object(s) under configuration are not completed yet (possibly endElement has been overriden without invoking its super implementation)");
75 }
76
77 protected abstract Object doGetConfiguredObject();
78
79 /**
80 * @see Configurator#characters(char[], int, int)
81 */
82 public void characters(char[] ch, int start, int length)
83 throws SAXException {
84 buffer.append(ch, start, length);
85 }
86
87 /**
88 * Returns the completed.
89 * @return boolean
90 */
91 public boolean isCompleted() {
92 return completed;
93 }
94
95 /**
96 * @see Configurator#getText()
97 */
98 public final String getText() {
99 return buffer.toString();
100 }
101
102 }
103