1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package net.sf.stax;
25
26 import org.xml.sax.Attributes;
27 import org.xml.sax.SAXException;
28 import org.xml.sax.SAXParseException;
29
30 /***
31 * StAX handler for any element which just contains a string
32 * representation of a long. The long value, returned by
33 * the <code>endTree(StAXContext)</code> method, is available
34 * to a parent handler via its <code>endElement(String, String,
35 * String, Object, StAXContext)</code> method.
36 *
37 * <p>Ex.
38 * <pre>
39 * class MyHandler
40 * extends StAXContentHandlerBase
41 * {
42 * private Long longValue;
43 * private LongElementHandler longHandler = new LongElementHandler();
44 *
45 * public void startElement(..., StAXDelegationContext dctx)
46 * {
47 * // ...
48 * dctx.delegate(longHandler);
49 * }
50 *
51 * public void endElement(..., Object result, ...)
52 * {
53 * this.longValue = (Long) result;
54 * }
55 * }
56 * </pre>
57 * </p>
58 * @see StAXContentHandlers#getLongElementHandler
59 *
60 * @author Matthew Pocock
61 * @author Michael Heuer
62 * @version $Revision: 1.7 $ $Date: 2006/01/02 20:37:34 $
63 */
64 public final class LongElementHandler
65 extends StAXContentHandlerBase
66 {
67 /*** Nesting level. */
68 private int level = 0;
69
70 /*** Buffer to hold character data. */
71 private StringBuffer data = new StringBuffer();
72
73
74 /*** @see StAXContentHandler */
75 public void startElement(final String nsURI,
76 final String localName,
77 final String qName,
78 final Attributes attrs,
79 final StAXDelegationContext dctx)
80 throws SAXException
81 {
82 level++;
83 if (level > 1)
84 {
85 throw new SAXParseException("found child element when expecting character data",
86 dctx.getLocator());
87 }
88 data.delete(0, data.length());
89 }
90
91 /*** @see StAXContentHandler */
92 public void endElement(final String nsURI,
93 final String localName,
94 final String qName,
95 final Object result,
96 final StAXContext ctx)
97 throws SAXException
98 {
99 level--;
100 }
101
102 /*** @see StAXContentHandler */
103 public void characters(final char[] ch,
104 final int start,
105 final int length,
106 final StAXContext ctx)
107 throws SAXException
108 {
109 data.append(ch, start, length);
110 }
111
112 /*** @see StAXContentHandler */
113 public Object endTree(final StAXContext ctx)
114 throws SAXException
115 {
116 try
117 {
118 return Long.valueOf(data.substring(0));
119 }
120 catch (NumberFormatException e)
121 {
122 throw new SAXParseException(e.getMessage(), ctx.getLocator(), e);
123 }
124 }
125 }