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

Last change on this file since 11216 was 10627, checked in by Don-vip, 8 years ago

sonar - squid:S1166 - Exception handlers should preserve the original exceptions

  • Property svn:eol-style set to native
File size: 11.6 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.InputStream;
8import java.io.Reader;
9import java.lang.reflect.Field;
10import java.lang.reflect.InvocationTargetException;
11import java.lang.reflect.Method;
12import java.lang.reflect.Modifier;
13import java.util.HashMap;
14import java.util.Iterator;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.Locale;
18import java.util.Map;
19import java.util.Stack;
20
21import javax.xml.XMLConstants;
22import javax.xml.parsers.ParserConfigurationException;
23import javax.xml.transform.stream.StreamSource;
24import javax.xml.validation.Schema;
25import javax.xml.validation.SchemaFactory;
26import javax.xml.validation.ValidatorHandler;
27
28import org.openstreetmap.josm.Main;
29import org.openstreetmap.josm.io.CachedFile;
30import org.xml.sax.Attributes;
31import org.xml.sax.ContentHandler;
32import org.xml.sax.InputSource;
33import org.xml.sax.Locator;
34import org.xml.sax.SAXException;
35import org.xml.sax.SAXParseException;
36import org.xml.sax.XMLReader;
37import org.xml.sax.helpers.DefaultHandler;
38import org.xml.sax.helpers.XMLFilterImpl;
39
40/**
41 * An helper class that reads from a XML stream into specific objects.
42 *
43 * @author Imi
44 */
45public class XmlObjectParser implements Iterable<Object> {
46 public static final String lang = LanguageInfo.getLanguageCodeXML();
47
48 private static class AddNamespaceFilter extends XMLFilterImpl {
49
50 private final String namespace;
51
52 AddNamespaceFilter(String namespace) {
53 this.namespace = namespace;
54 }
55
56 @Override
57 public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
58 if ("".equals(uri)) {
59 super.startElement(namespace, localName, qName, atts);
60 } else {
61 super.startElement(uri, localName, qName, atts);
62 }
63 }
64 }
65
66 private class Parser extends DefaultHandler {
67 private final Stack<Object> current = new Stack<>();
68 private StringBuilder characters = new StringBuilder(64);
69
70 private Locator locator;
71
72 @Override
73 public void setDocumentLocator(Locator locator) {
74 this.locator = locator;
75 }
76
77 protected void throwException(Exception e) throws XmlParsingException {
78 throw new XmlParsingException(e).rememberLocation(locator);
79 }
80
81 @Override
82 public void startElement(String ns, String lname, String qname, Attributes a) throws SAXException {
83 if (mapping.containsKey(qname)) {
84 Class<?> klass = mapping.get(qname).klass;
85 try {
86 current.push(klass.getConstructor().newInstance());
87 } catch (ReflectiveOperationException e) {
88 throwException(e);
89 }
90 for (int i = 0; i < a.getLength(); ++i) {
91 setValue(mapping.get(qname), a.getQName(i), a.getValue(i));
92 }
93 if (mapping.get(qname).onStart) {
94 report();
95 }
96 if (mapping.get(qname).both) {
97 queue.add(current.peek());
98 }
99 }
100 }
101
102 @Override
103 public void endElement(String ns, String lname, String qname) throws SAXException {
104 if (mapping.containsKey(qname) && !mapping.get(qname).onStart) {
105 report();
106 } else if (mapping.containsKey(qname) && characters != null && !current.isEmpty()) {
107 setValue(mapping.get(qname), qname, characters.toString().trim());
108 characters = new StringBuilder(64);
109 }
110 }
111
112 @Override
113 public void characters(char[] ch, int start, int length) {
114 characters.append(ch, start, length);
115 }
116
117 private void report() {
118 queue.add(current.pop());
119 characters = new StringBuilder(64);
120 }
121
122 private Object getValueForClass(Class<?> klass, String value) {
123 if (klass == Boolean.TYPE)
124 return parseBoolean(value);
125 else if (klass == Integer.TYPE || klass == Long.TYPE)
126 return Long.valueOf(value);
127 else if (klass == Float.TYPE || klass == Double.TYPE)
128 return Double.valueOf(value);
129 return value;
130 }
131
132 private void setValue(Entry entry, String fieldName, String value) throws SAXException {
133 CheckParameterUtil.ensureParameterNotNull(entry, "entry");
134 if ("class".equals(fieldName) || "default".equals(fieldName) || "throw".equals(fieldName) ||
135 "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 (IllegalAccessException | IllegalArgumentException | InvocationTargetException 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 private final Class<?> klass;
186 private final boolean onStart;
187 private final boolean both;
188 private final Map<String, Field> fields = new HashMap<>();
189 private final Map<String, Method> methods = new HashMap<>();
190
191 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 Main.trace(ex);
207 fields.put(s, null);
208 return null;
209 }
210 }
211 }
212
213 Method getMethod(String s) {
214 if (methods.containsKey(s)) {
215 return methods.get(s);
216 } else {
217 for (Method m : klass.getMethods()) {
218 if (m.getName().equals(s) && m.getParameterTypes().length == 1) {
219 methods.put(s, m);
220 return m;
221 }
222 }
223 methods.put(s, null);
224 return null;
225 }
226 }
227 }
228
229 private final Map<String, Entry> mapping = new HashMap<>();
230 private final DefaultHandler parser;
231
232 /**
233 * The queue of already parsed items from the parsing thread.
234 */
235 private final List<Object> queue = new LinkedList<>();
236 private Iterator<Object> queueIterator;
237
238 /**
239 * Constructs a new {@code XmlObjectParser}.
240 */
241 public XmlObjectParser() {
242 parser = new Parser();
243 }
244
245 private Iterable<Object> start(final Reader in, final ContentHandler contentHandler) throws SAXException, IOException {
246 try {
247 XMLReader reader = Utils.newSafeSAXParser().getXMLReader();
248 reader.setContentHandler(contentHandler);
249 try {
250 // Do not load external DTDs (fix #8191)
251 reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
252 } catch (SAXException e) {
253 // Exception very unlikely to happen, so no need to translate this
254 Main.error(e, "Cannot disable 'load-external-dtd' feature:");
255 }
256 reader.parse(new InputSource(in));
257 queueIterator = queue.iterator();
258 return this;
259 } catch (ParserConfigurationException e) {
260 // This should never happen ;-)
261 throw new RuntimeException(e);
262 }
263 }
264
265 /**
266 * Starts parsing from the given input reader, without validation.
267 * @param in The input reader
268 * @return iterable collection of objects
269 * @throws SAXException if any XML or I/O error occurs
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 /**
280 * Starts parsing from the given input reader, with XSD validation.
281 * @param in The input reader
282 * @param namespace default namespace
283 * @param schemaSource XSD schema
284 * @return iterable collection of objects
285 * @throws SAXException if any XML or I/O error occurs
286 */
287 public Iterable<Object> startWithValidation(final Reader in, String namespace, String schemaSource) throws SAXException {
288 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
289 try (CachedFile cf = new CachedFile(schemaSource); InputStream mis = cf.getInputStream()) {
290 Schema schema = factory.newSchema(new StreamSource(mis));
291 ValidatorHandler validator = schema.newValidatorHandler();
292 validator.setContentHandler(parser);
293 validator.setErrorHandler(parser);
294
295 AddNamespaceFilter filter = new AddNamespaceFilter(namespace);
296 filter.setContentHandler(validator);
297 return start(in, filter);
298 } catch (IOException e) {
299 throw new SAXException(tr("Failed to load XML schema."), e);
300 }
301 }
302
303 public void map(String tagName, Class<?> klass) {
304 mapping.put(tagName, new Entry(klass, false, false));
305 }
306
307 public void mapOnStart(String tagName, Class<?> klass) {
308 mapping.put(tagName, new Entry(klass, true, false));
309 }
310
311 public void mapBoth(String tagName, Class<?> klass) {
312 mapping.put(tagName, new Entry(klass, false, true));
313 }
314
315 public Object next() {
316 return queueIterator.next();
317 }
318
319 public boolean hasNext() {
320 return queueIterator.hasNext();
321 }
322
323 @Override
324 public Iterator<Object> iterator() {
325 return queue.iterator();
326 }
327}
Note: See TracBrowser for help on using the repository browser.