source: josm/trunk/src/org/openstreetmap/josm/tools/XmlObjectParser.java@ 7012

Last change on this file since 7012 was 7012, checked in by Don-vip, 10 years ago

see #8465 - use String switch/case where applicable

  • Property svn:eol-style set to native
File size: 11.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.IOException;
7import java.io.Reader;
8import java.lang.reflect.Field;
9import java.lang.reflect.Method;
10import java.lang.reflect.Modifier;
11import java.util.HashMap;
12import java.util.Iterator;
13import java.util.LinkedList;
14import java.util.List;
15import java.util.Locale;
16import java.util.Map;
17import java.util.Stack;
18
19import javax.xml.parsers.ParserConfigurationException;
20import javax.xml.parsers.SAXParser;
21import javax.xml.parsers.SAXParserFactory;
22import javax.xml.transform.stream.StreamSource;
23import javax.xml.validation.Schema;
24import javax.xml.validation.SchemaFactory;
25import javax.xml.validation.ValidatorHandler;
26
27import org.openstreetmap.josm.Main;
28import org.openstreetmap.josm.io.MirroredInputStream;
29import org.xml.sax.Attributes;
30import org.xml.sax.ContentHandler;
31import org.xml.sax.InputSource;
32import org.xml.sax.Locator;
33import org.xml.sax.SAXException;
34import org.xml.sax.SAXParseException;
35import org.xml.sax.XMLReader;
36import org.xml.sax.helpers.DefaultHandler;
37import org.xml.sax.helpers.XMLFilterImpl;
38
39/**
40 * An helper class that reads from a XML stream into specific objects.
41 *
42 * @author Imi
43 */
44public class XmlObjectParser implements Iterable<Object> {
45 public static final String lang = LanguageInfo.getLanguageCodeXML();
46
47 private static class AddNamespaceFilter extends XMLFilterImpl {
48
49 private final String namespace;
50
51 public AddNamespaceFilter(String namespace) {
52 this.namespace = namespace;
53 }
54
55 @Override
56 public void startElement (String uri, String localName, String qName, Attributes atts) throws SAXException {
57 if ("".equals(uri)) {
58 super.startElement(namespace, localName, qName, atts);
59 } else {
60 super.startElement(uri, localName, qName, atts);
61 }
62
63 }
64
65 }
66
67 private class Parser extends DefaultHandler {
68 Stack<Object> current = new Stack<>();
69 StringBuilder characters = new StringBuilder(64);
70
71 private Locator locator;
72
73 @Override
74 public void setDocumentLocator(Locator locator) {
75 this.locator = locator;
76 }
77
78 protected void throwException(Exception e) throws XmlParsingException {
79 throw new XmlParsingException(e).rememberLocation(locator);
80 }
81
82 @Override
83 public void startElement(String ns, String lname, String qname, Attributes a) throws SAXException {
84 if (mapping.containsKey(qname)) {
85 Class<?> klass = mapping.get(qname).klass;
86 try {
87 current.push(klass.newInstance());
88 } catch (Exception e) {
89 throwException(e);
90 }
91 for (int i = 0; i < a.getLength(); ++i) {
92 setValue(mapping.get(qname), a.getQName(i), a.getValue(i));
93 }
94 if (mapping.get(qname).onStart) {
95 report();
96 }
97 if (mapping.get(qname).both) {
98 queue.add(current.peek());
99 }
100 }
101 }
102
103 @Override
104 public void endElement(String ns, String lname, String qname) throws SAXException {
105 if (mapping.containsKey(qname) && !mapping.get(qname).onStart) {
106 report();
107 } else if (mapping.containsKey(qname) && characters != null && !current.isEmpty()) {
108 setValue(mapping.get(qname), qname, characters.toString().trim());
109 characters = new StringBuilder(64);
110 }
111 }
112
113 @Override
114 public void characters(char[] ch, int start, int length) {
115 characters.append(ch, start, length);
116 }
117
118 private void report() {
119 queue.add(current.pop());
120 characters = new StringBuilder(64);
121 }
122
123 private Object getValueForClass(Class<?> klass, String value) {
124 if (klass == Boolean.TYPE)
125 return parseBoolean(value);
126 else if (klass == Integer.TYPE || klass == Long.TYPE)
127 return Long.parseLong(value);
128 else if (klass == Float.TYPE || klass == Double.TYPE)
129 return Double.parseDouble(value);
130 return value;
131 }
132
133 private void setValue(Entry entry, String fieldName, String value) throws SAXException {
134 CheckParameterUtil.ensureParameterNotNull(entry, "entry");
135 if ("class".equals(fieldName) || "default".equals(fieldName) || "throw".equals(fieldName) || "new".equals(fieldName) || "null".equals(fieldName)) {
136 fieldName += "_";
137 }
138 try {
139 Object c = current.peek();
140 Field f = entry.getField(fieldName);
141 if (f == null && fieldName.startsWith(lang)) {
142 f = entry.getField("locale_" + fieldName.substring(lang.length()));
143 }
144 if (f != null && Modifier.isPublic(f.getModifiers()) && (
145 String.class.equals(f.getType()) || boolean.class.equals(f.getType()))) {
146 f.set(c, getValueForClass(f.getType(), value));
147 } else {
148 if (fieldName.startsWith(lang)) {
149 int l = lang.length();
150 fieldName = "set" + fieldName.substring(l, l + 1).toUpperCase(Locale.ENGLISH) + fieldName.substring(l + 1);
151 } else {
152 fieldName = "set" + fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH) + fieldName.substring(1);
153 }
154 Method m = entry.getMethod(fieldName);
155 if (m != null) {
156 m.invoke(c, new Object[]{getValueForClass(m.getParameterTypes()[0], value)});
157 }
158 }
159 } catch (Exception e) {
160 Main.error(e); // SAXException does not dump inner exceptions.
161 throwException(e);
162 }
163 }
164
165 private boolean parseBoolean(String s) {
166 return s != null
167 && !"0".equals(s)
168 && !s.startsWith("off")
169 && !s.startsWith("false")
170 && !s.startsWith("no");
171 }
172
173 @Override
174 public void error(SAXParseException e) throws SAXException {
175 throwException(e);
176 }
177
178 @Override
179 public void fatalError(SAXParseException e) throws SAXException {
180 throwException(e);
181 }
182 }
183
184 private static class Entry {
185 Class<?> klass;
186 boolean onStart;
187 boolean both;
188 private final Map<String, Field> fields = new HashMap<>();
189 private final Map<String, Method> methods = new HashMap<>();
190
191 public Entry(Class<?> klass, boolean onStart, boolean both) {
192 this.klass = klass;
193 this.onStart = onStart;
194 this.both = both;
195 }
196
197 Field getField(String s) {
198 if (fields.containsKey(s)) {
199 return fields.get(s);
200 } else {
201 try {
202 Field f = klass.getField(s);
203 fields.put(s, f);
204 return f;
205 } catch (NoSuchFieldException ex) {
206 fields.put(s, null);
207 return null;
208 }
209 }
210 }
211
212 Method getMethod(String s) {
213 if (methods.containsKey(s)) {
214 return methods.get(s);
215 } else {
216 for (Method m : klass.getMethods()) {
217 if (m.getName().equals(s) && m.getParameterTypes().length == 1) {
218 methods.put(s, m);
219 return m;
220 }
221 }
222 methods.put(s, null);
223 return null;
224 }
225 }
226 }
227
228 private Map<String, Entry> mapping = new HashMap<>();
229 private DefaultHandler parser;
230
231 /**
232 * The queue of already parsed items from the parsing thread.
233 */
234 private List<Object> queue = new LinkedList<>();
235 private Iterator<Object> queueIterator = null;
236
237 /**
238 * Constructs a new {@code XmlObjectParser}.
239 */
240 public XmlObjectParser() {
241 parser = new Parser();
242 }
243
244 public XmlObjectParser(DefaultHandler handler) {
245 parser = handler;
246 }
247
248 private Iterable<Object> start(final Reader in, final ContentHandler contentHandler) throws SAXException, IOException {
249 try {
250 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
251 parserFactory.setNamespaceAware(true);
252 SAXParser saxParser = parserFactory.newSAXParser();
253 XMLReader reader = saxParser.getXMLReader();
254 reader.setContentHandler(contentHandler);
255 try {
256 // Do not load external DTDs (fix #8191)
257 reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
258 } catch (SAXException e) {
259 // Exception very unlikely to happen, so no need to translate this
260 Main.error("Cannot disable 'load-external-dtd' feature: "+e.getMessage());
261 }
262 reader.parse(new InputSource(in));
263 queueIterator = queue.iterator();
264 return this;
265 } catch (ParserConfigurationException e) {
266 // This should never happen ;-)
267 throw new RuntimeException(e);
268 }
269 }
270
271 public Iterable<Object> start(final Reader in) throws SAXException {
272 try {
273 return start(in, parser);
274 } catch (IOException e) {
275 throw new SAXException(e);
276 }
277 }
278
279 public Iterable<Object> startWithValidation(final Reader in, String namespace, String schemaSource) throws SAXException {
280 try {
281 SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
282 Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream(schemaSource)));
283 ValidatorHandler validator = schema.newValidatorHandler();
284 validator.setContentHandler(parser);
285 validator.setErrorHandler(parser);
286
287 AddNamespaceFilter filter = new AddNamespaceFilter(namespace);
288 filter.setContentHandler(validator);
289 return start(in, filter);
290 } catch(IOException e) {
291 throw new SAXException(tr("Failed to load XML schema."), e);
292 }
293 }
294
295 public void map(String tagName, Class<?> klass) {
296 mapping.put(tagName, new Entry(klass,false,false));
297 }
298
299 public void mapOnStart(String tagName, Class<?> klass) {
300 mapping.put(tagName, new Entry(klass,true,false));
301 }
302
303 public void mapBoth(String tagName, Class<?> klass) {
304 mapping.put(tagName, new Entry(klass,false,true));
305 }
306
307 public Object next() {
308 return queueIterator.next();
309 }
310
311 public boolean hasNext() {
312 return queueIterator.hasNext();
313 }
314
315 @Override
316 public Iterator<Object> iterator() {
317 return queue.iterator();
318 }
319}
Note: See TracBrowser for help on using the repository browser.