1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.digester3;
20
21 import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25
26 import java.io.StringReader;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30
31 import org.apache.commons.digester3.Digester;
32 import org.apache.commons.digester3.StackAction;
33 import org.apache.commons.digester3.binder.AbstractRulesModule;
34 import org.junit.Test;
35 import org.xml.sax.Locator;
36
37
38
39
40
41 public class LocationTrackerTestCase
42 {
43
44 private static class LocationTracker
45 implements StackAction
46 {
47 public Map<Object, String> locations = new HashMap<Object, String>();
48
49 public <T> T onPush( Digester d, String stackName, T o )
50 {
51 if ( stackName == null )
52 {
53
54
55
56
57 Locator l = d.getDocumentLocator();
58 StringBuilder locn = new StringBuilder();
59 locn.append( "line=" );
60 locn.append( l.getLineNumber() );
61 locations.put( o, locn.toString() );
62 }
63 return o;
64 }
65
66 public <T> T onPop( Digester d, String stackName, T o )
67 {
68 return o;
69 }
70 }
71
72 @Test
73 public void testAll()
74 throws Exception
75 {
76 final String TEST_XML =
77 "<?xml version='1.0'?>\n" + "<box id='root'>\n" + " <subBox id='box1'/>\n" + " <ignoreme/>\n"
78 + " <subBox id='box2'/> <subBox id='box3'/>\n" + "</box>";
79
80 LocationTracker locnTracker = new LocationTracker();
81
82 Digester digester = newLoader( new AbstractRulesModule()
83 {
84
85 @Override
86 protected void configure()
87 {
88 forPattern( "box" ).createObject().ofType( Box.class )
89 .then()
90 .setProperties();
91 forPattern( "box/subBox" ).createObject().ofType( Box.class )
92 .then()
93 .setProperties()
94 .then()
95 .setNext( "addChild" );
96 }
97
98 })
99 .setStackAction( locnTracker )
100 .newDigester();
101
102 Box root = digester.parse( new StringReader( TEST_XML ) );
103 assertNotNull( root );
104 List<Box> children = root.getChildren();
105 assertEquals( 3, children.size() );
106 Box box1 = children.get( 0 );
107 Box box2 = children.get( 1 );
108 Box box3 = children.get( 2 );
109
110 assertEquals( "line=2", locnTracker.locations.get( root ) );
111 assertEquals( "line=3", locnTracker.locations.get( box1 ) );
112 assertEquals( "line=5", locnTracker.locations.get( box2 ) );
113 assertEquals( "line=5", locnTracker.locations.get( box3 ) );
114 }
115 }