1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.eos.trie;
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
20 import org.xml.sax.Attributes;
21 import org.xml.sax.helpers.DefaultHandler;
22
23 import java.util.HashSet;
24 import java.util.Set;
25
26 public class TrieHandler extends DefaultHandler implements TrieSource {
27
28 static final Log LOG = LogFactory.getLog(TrieHandler.class.getName());
29
30 private enum Xml {trie, entry, key, value}
31
32 private boolean inEntry = false;
33 private boolean inKey = false;
34 private boolean inValue = false;
35 private StringBuilder sb = null;
36 private String key = null;
37 private String value = null;
38
39 private final Set<TrieEntryListener> listeners =
40 new HashSet<TrieEntryListener>();
41
42 @Override
43 public void startDocument() {
44 }
45
46 @Override
47 public void endDocument() {
48 }
49
50 @Override
51 public void startElement(final String uri,
52 final String localName,
53 final String qName,
54 final Attributes attributes) {
55 if (Xml.entry.name().equals(qName)) {
56 assert this.inEntry == false;
57 this.inEntry = true;
58 this.key = null;
59 this.value = null;
60 } else if (Xml.key.name().equals(qName)) {
61 assert this.inKey == false;
62 this.inKey = true;
63 this.sb = new StringBuilder();
64 } else if (Xml.value.name().equals(qName)) {
65 assert this.inValue == false;
66 this.inValue = true;
67 this.sb = new StringBuilder();
68 }
69 }
70
71 @Override
72 public void endElement(final String uri,
73 final String localName,
74 final String qName) {
75 if (Xml.key.name().equals(qName)) {
76 assert this.inKey == true;
77 this.inKey = false;
78 assert this.key == null;
79 assert this.sb != null;
80 this.key = this.sb.toString();
81 } else if (Xml.value.name().equals(qName)) {
82 assert this.inValue == true;
83 this.inValue = false;
84 assert this.value == null;
85 assert this.sb != null;
86 this.value = this.sb.toString();
87 } else if (Xml.entry.name().equals(qName)) {
88 assert this.inEntry == true;
89 this.inEntry = false;
90 assert this.key != null;
91 assert this.value != null;
92
93 final TrieEntry entry = new TrieEntry(this.key, this.value);
94 final TrieEntryEvent evt = new TrieEntryEvent(entry);
95 assert this.listeners != null;
96 for (final TrieEntryListener l : this.listeners) {
97 l.onEntry(evt);
98 }
99 }
100 }
101
102 @Override
103 public void characters(final char[] ch,
104 final int start,
105 final int length) {
106 if (this.sb != null) {
107 this.sb.append(ch, start, length);
108 }
109 }
110
111 public void addTrieEntryListener(final TrieEntryListener listener) {
112 this.listeners.add(listener);
113 }
114
115 public void removeTrieEntryListener(final TrieEntryListener listener) {
116 this.listeners.remove(listener);
117 }
118 }