1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.io.IOException;
|
---|
7 | import java.io.InputStream;
|
---|
8 | import java.io.Reader;
|
---|
9 | import java.lang.reflect.Field;
|
---|
10 | import java.lang.reflect.InvocationTargetException;
|
---|
11 | import java.lang.reflect.Method;
|
---|
12 | import java.lang.reflect.Modifier;
|
---|
13 | import java.util.HashMap;
|
---|
14 | import java.util.Iterator;
|
---|
15 | import java.util.LinkedList;
|
---|
16 | import java.util.List;
|
---|
17 | import java.util.Locale;
|
---|
18 | import java.util.Map;
|
---|
19 | import java.util.Stack;
|
---|
20 |
|
---|
21 | import javax.xml.XMLConstants;
|
---|
22 | import javax.xml.parsers.ParserConfigurationException;
|
---|
23 | import javax.xml.transform.stream.StreamSource;
|
---|
24 | import javax.xml.validation.Schema;
|
---|
25 | import javax.xml.validation.SchemaFactory;
|
---|
26 | import javax.xml.validation.ValidatorHandler;
|
---|
27 |
|
---|
28 | import org.openstreetmap.josm.Main;
|
---|
29 | import org.openstreetmap.josm.io.CachedFile;
|
---|
30 | import org.xml.sax.Attributes;
|
---|
31 | import org.xml.sax.ContentHandler;
|
---|
32 | import org.xml.sax.InputSource;
|
---|
33 | import org.xml.sax.Locator;
|
---|
34 | import org.xml.sax.SAXException;
|
---|
35 | import org.xml.sax.SAXParseException;
|
---|
36 | import org.xml.sax.XMLReader;
|
---|
37 | import org.xml.sax.helpers.DefaultHandler;
|
---|
38 | import 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 | */
|
---|
45 | public 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 | throw new JosmRuntimeException(e);
|
---|
261 | }
|
---|
262 | }
|
---|
263 |
|
---|
264 | /**
|
---|
265 | * Starts parsing from the given input reader, without validation.
|
---|
266 | * @param in The input reader
|
---|
267 | * @return iterable collection of objects
|
---|
268 | * @throws SAXException if any XML or I/O error occurs
|
---|
269 | */
|
---|
270 | public Iterable<Object> start(final Reader in) throws SAXException {
|
---|
271 | try {
|
---|
272 | return start(in, parser);
|
---|
273 | } catch (IOException e) {
|
---|
274 | throw new SAXException(e);
|
---|
275 | }
|
---|
276 | }
|
---|
277 |
|
---|
278 | /**
|
---|
279 | * Starts parsing from the given input reader, with XSD validation.
|
---|
280 | * @param in The input reader
|
---|
281 | * @param namespace default namespace
|
---|
282 | * @param schemaSource XSD schema
|
---|
283 | * @return iterable collection of objects
|
---|
284 | * @throws SAXException if any XML or I/O error occurs
|
---|
285 | */
|
---|
286 | public Iterable<Object> startWithValidation(final Reader in, String namespace, String schemaSource) throws SAXException {
|
---|
287 | SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
|
---|
288 | try (CachedFile cf = new CachedFile(schemaSource); InputStream mis = cf.getInputStream()) {
|
---|
289 | Schema schema = factory.newSchema(new StreamSource(mis));
|
---|
290 | ValidatorHandler validator = schema.newValidatorHandler();
|
---|
291 | validator.setContentHandler(parser);
|
---|
292 | validator.setErrorHandler(parser);
|
---|
293 |
|
---|
294 | AddNamespaceFilter filter = new AddNamespaceFilter(namespace);
|
---|
295 | filter.setContentHandler(validator);
|
---|
296 | return start(in, filter);
|
---|
297 | } catch (IOException e) {
|
---|
298 | throw new SAXException(tr("Failed to load XML schema."), e);
|
---|
299 | }
|
---|
300 | }
|
---|
301 |
|
---|
302 | public void map(String tagName, Class<?> klass) {
|
---|
303 | mapping.put(tagName, new Entry(klass, false, false));
|
---|
304 | }
|
---|
305 |
|
---|
306 | public void mapOnStart(String tagName, Class<?> klass) {
|
---|
307 | mapping.put(tagName, new Entry(klass, true, false));
|
---|
308 | }
|
---|
309 |
|
---|
310 | public void mapBoth(String tagName, Class<?> klass) {
|
---|
311 | mapping.put(tagName, new Entry(klass, false, true));
|
---|
312 | }
|
---|
313 |
|
---|
314 | public Object next() {
|
---|
315 | return queueIterator.next();
|
---|
316 | }
|
---|
317 |
|
---|
318 | public boolean hasNext() {
|
---|
319 | return queueIterator.hasNext();
|
---|
320 | }
|
---|
321 |
|
---|
322 | @Override
|
---|
323 | public Iterator<Object> iterator() {
|
---|
324 | return queue.iterator();
|
---|
325 | }
|
---|
326 | }
|
---|