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

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

Sonar - Avoid throwing NullPointerException

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