1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.onemind.commons.java.xml.digest;
22
23 import java.io.InputStream;
24 import javax.xml.parsers.SAXParser;
25 import javax.xml.parsers.SAXParserFactory;
26 import junit.framework.TestCase;
27 import org.xml.sax.Attributes;
28 import org.xml.sax.SAXException;
29 /***
30 * SaxDigester test. The model is with exactly one "RootElement" which can have 0-1 "Element" that can any random "SubElement1" and
31 * "SubElement2"
32 * @author TiongHiang Lee (thlee@thinklient.org)
33 * @version $Id: SaxDigesterTest.java,v 1.4 2005/04/26 17:46:39 thlee Exp $ $Name: $
34 */
35 public class SaxDigesterTest extends TestCase
36 {
37
38 /***
39 * Root element digester
40 */
41 public class TestElementDigester extends DefaultDigester
42 {
43
44 /*** the count start is called**/
45 int startCount;
46
47 /*** the count end is called **/
48 int endCount;
49
50 /*** the count characters is called **/
51 int charCount;
52
53 /***
54 * {@inheritDoc}
55 */
56 public TestElementDigester(String str)
57 {
58 super(str);
59 }
60
61 /***
62 * {@inheritDoc}
63 */
64 public void startDigest(SaxDigesterHandler handler, Attributes attrs) throws SAXException
65 {
66 startCount++;
67
68 }
69
70 /***
71 * {@inheritDoc}
72 */
73 public void endDigest(SaxDigesterHandler handler) throws SAXException
74 {
75 endCount++;
76
77 }
78
79 /***
80 * {@inheritDoc}
81 */
82 public void characters(SaxDigesterHandler handler, char[] chars, int offset, int length) throws SAXException
83 {
84 charCount++;
85
86 }
87 }
88
89 /***
90 * parse the file with the handler
91 * @throws Exception
92 */
93 private void _testHandler(InputStream in, SaxDigesterHandler handler) throws Exception
94 {
95 SAXParserFactory factory = SAXParserFactory.newInstance();
96
97 SAXParser saxParser = factory.newSAXParser();
98 saxParser.parse(in, handler);
99 }
100
101 /***
102 * Test when there's one element
103 * @throws Exception if there's exception
104 */
105 public void testOneElement() throws Exception
106 {
107 SaxDigesterHandler handler = new SaxDigesterHandler();
108 TestElementDigester rootElement = new TestElementDigester("RootElement");
109 TestElementDigester rootElement1 = new TestElementDigester("RootElment1");
110 TestElementDigester subElement1 = new TestElementDigester("SubElement1");
111 handler.addDigester(rootElement);
112 handler.addDigester(rootElement1);
113 handler.addDigester("RootElement/Element1", subElement1);
114 _testHandler(getClass().getResourceAsStream("SaxDigesterTest.xml"), handler);
115 assertTrue(rootElement.startCount == 1);
116 assertTrue(rootElement.endCount == 1);
117 assertTrue(rootElement1.startCount == 0);
118 assertTrue(rootElement1.endCount == 0);
119 assertTrue(subElement1.startCount == 2);
120 assertTrue(subElement1.endCount == 2);
121 }
122 }