001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.IOException;
007import java.io.InputStream;
008import java.io.Reader;
009import java.lang.reflect.Field;
010import java.lang.reflect.Method;
011import java.lang.reflect.Modifier;
012import java.util.HashMap;
013import java.util.Iterator;
014import java.util.LinkedList;
015import java.util.List;
016import java.util.Locale;
017import java.util.Map;
018import java.util.Optional;
019import java.util.Stack;
020
021import javax.xml.parsers.ParserConfigurationException;
022import javax.xml.transform.stream.StreamSource;
023import javax.xml.validation.Schema;
024import javax.xml.validation.SchemaFactory;
025import javax.xml.validation.ValidatorHandler;
026
027import org.openstreetmap.josm.io.CachedFile;
028import org.xml.sax.Attributes;
029import org.xml.sax.ContentHandler;
030import org.xml.sax.InputSource;
031import org.xml.sax.Locator;
032import org.xml.sax.SAXException;
033import org.xml.sax.SAXParseException;
034import org.xml.sax.XMLReader;
035import org.xml.sax.helpers.DefaultHandler;
036import org.xml.sax.helpers.XMLFilterImpl;
037
038/**
039 * An helper class that reads from a XML stream into specific objects.
040 *
041 * @author Imi
042 */
043public class XmlObjectParser implements Iterable<Object> {
044    /**
045     * The language prefix to use
046     */
047    public static final String lang = LanguageInfo.getLanguageCodeXML();
048
049    private static class AddNamespaceFilter extends XMLFilterImpl {
050
051        private final String namespace;
052
053        AddNamespaceFilter(String namespace) {
054            this.namespace = namespace;
055        }
056
057        @Override
058        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
059            if ("".equals(uri)) {
060                super.startElement(namespace, localName, qName, atts);
061            } else {
062                super.startElement(uri, localName, qName, atts);
063            }
064        }
065    }
066
067    private final class Parser extends DefaultHandler {
068        private final Stack<Object> current = new Stack<>();
069        private StringBuilder characters = new StringBuilder(64);
070        private Locator locator;
071        private final StringParser primitiveParsers = new StringParser(StringParser.DEFAULT)
072                .registerParser(boolean.class, this::parseBoolean)
073                .registerParser(Boolean.class, this::parseBoolean);
074
075        @Override
076        public void setDocumentLocator(Locator locator) {
077            this.locator = locator;
078        }
079
080        void throwException(Exception e) throws XmlParsingException {
081            throw new XmlParsingException(e).rememberLocation(locator);
082        }
083
084        @Override
085        public void startElement(String ns, String lname, String qname, Attributes a) throws SAXException {
086            final Entry entry = mapping.get(qname);
087            if (entry != null) {
088                Class<?> klass = entry.klass;
089                try {
090                    current.push(klass.getConstructor().newInstance());
091                } catch (ReflectiveOperationException e) {
092                    throwException(e);
093                }
094                for (int i = 0; i < a.getLength(); ++i) {
095                    setValue(entry, a.getQName(i), a.getValue(i));
096                }
097                if (entry.onStart) {
098                    report();
099                }
100                if (entry.both) {
101                    queue.add(current.peek());
102                }
103            }
104        }
105
106        @Override
107        public void endElement(String ns, String lname, String qname) throws SAXException {
108            final Entry entry = mapping.get(qname);
109            if (entry != null && !entry.onStart) {
110                report();
111            } else if (entry != null && characters != null && !current.isEmpty()) {
112                setValue(entry, qname, characters.toString().trim());
113                characters = new StringBuilder(64);
114            }
115        }
116
117        @Override
118        public void characters(char[] ch, int start, int length) {
119            characters.append(ch, start, length);
120        }
121
122        private void report() {
123            queue.add(current.pop());
124            characters = new StringBuilder(64);
125        }
126
127        private void setValue(Entry entry, String fieldName, String value0) throws SAXException {
128            final String value = value0 != null ? value0.intern() : null;
129            CheckParameterUtil.ensureParameterNotNull(entry, "entry");
130            if ("class".equals(fieldName) || "default".equals(fieldName) || "throw".equals(fieldName) ||
131                    "new".equals(fieldName) || "null".equals(fieldName)) {
132                fieldName += '_';
133            }
134            fieldName = fieldName.replace(':', '_');
135            try {
136                Object c = current.peek();
137                Field f = entry.getField(fieldName);
138                if (f == null && fieldName.startsWith(lang)) {
139                    f = entry.getField("locale_" + fieldName.substring(lang.length()));
140                }
141                Optional<?> parsed = Optional.ofNullable(f)
142                        .filter(field -> Modifier.isPublic(field.getModifiers()))
143                        .flatMap(field -> primitiveParsers.tryParse(field.getType(), value));
144                if (parsed.isPresent()) {
145                    f.set(c, parsed.get());
146                } else {
147                    String setter;
148                    if (fieldName.startsWith(lang)) {
149                        int l = lang.length();
150                        setter = "set" + fieldName.substring(l, l + 1).toUpperCase(Locale.ENGLISH) + fieldName.substring(l + 1);
151                    } else {
152                        setter = "set" + fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH) + fieldName.substring(1);
153                    }
154                    Method m = entry.getMethod(setter);
155                    if (m != null) {
156                        parsed = primitiveParsers.tryParse(m.getParameterTypes()[0], value);
157                        m.invoke(c, parsed.isPresent() ? parsed.get() : value);
158                    }
159                }
160            } catch (ReflectiveOperationException | IllegalArgumentException e) {
161                Logging.error(e); // SAXException does not dump inner exceptions.
162                throwException(e);
163            }
164        }
165
166        private boolean parseBoolean(String s) {
167            return s != null
168                    && !"0".equals(s)
169                    && !s.startsWith("off")
170                    && !s.startsWith("false")
171                    && !s.startsWith("no");
172        }
173
174        @Override
175        public void error(SAXParseException e) throws SAXException {
176            throwException(e);
177        }
178
179        @Override
180        public void fatalError(SAXParseException e) throws SAXException {
181            throwException(e);
182        }
183    }
184
185    private static class Entry {
186        private final Class<?> klass;
187        private final boolean onStart;
188        private final boolean both;
189        private final Map<String, Field> fields = new HashMap<>();
190        private final Map<String, Method> methods = new HashMap<>();
191        /** This is used to avoid array copies in {@link #getUncachedMethod(String)}. Do not modify. */
192        private Method[] cachedKlassMethods;
193        /** This is used to avoid array copies in {@link #getUncachedField(String)}. Do not modify. */
194        private Field[] cachedKlassFields;
195
196        Entry(Class<?> klass, boolean onStart, boolean both) {
197            this.klass = klass;
198            this.onStart = onStart;
199            this.both = both;
200        }
201
202        Field getField(String s) {
203            return fields.computeIfAbsent(s, this::getUncachedField);
204        }
205
206        /**
207         * Get a field (uncached in {@link #fields})
208         * Please profile startup when changing
209         * @param s The field to get
210         * @return The field, or {@code null}.
211         */
212        private Field getUncachedField(String s) {
213            if (this.cachedKlassFields == null) {
214                this.cachedKlassFields = klass.getFields();
215            }
216            for (Field field : this.cachedKlassFields) {
217                if (field.getName().equals(s)) {
218                    return field;
219                }
220            }
221            return null;
222        }
223
224        Method getMethod(String s) {
225            return methods.computeIfAbsent(s, this::getUncachedMethod);
226        }
227
228        /**
229         * Get an uncached method (in {@link #methods})
230         * Please profile startup when changing
231         * @param s The method to find
232         * @return The method or {@code null}.
233         */
234        private Method getUncachedMethod(String s) {
235            if (cachedKlassMethods == null) {
236                cachedKlassMethods = klass.getMethods();
237            }
238            for (Method method : cachedKlassMethods) {
239                if (method.getParameterCount() == 1 && method.getName().equals(s)) {
240                    return method;
241                }
242            }
243            return null;
244        }
245    }
246
247    private final Map<String, Entry> mapping = new HashMap<>();
248    private final DefaultHandler parser;
249
250    /**
251     * The queue of already parsed items from the parsing thread.
252     */
253    private final List<Object> queue = new LinkedList<>();
254    private Iterator<Object> queueIterator;
255
256    /**
257     * Constructs a new {@code XmlObjectParser}.
258     */
259    public XmlObjectParser() {
260        parser = new Parser();
261    }
262
263    private Iterable<Object> start(final Reader in, final ContentHandler contentHandler) throws SAXException, IOException {
264        try {
265            XMLReader reader = XmlUtils.newSafeSAXParser().getXMLReader();
266            reader.setContentHandler(contentHandler);
267            try {
268                // Do not load external DTDs (fix #8191)
269                reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
270            } catch (SAXException e) {
271                // Exception very unlikely to happen, so no need to translate this
272                Logging.log(Logging.LEVEL_ERROR, "Cannot disable 'load-external-dtd' feature:", e);
273            }
274            reader.parse(new InputSource(in));
275            queueIterator = queue.iterator();
276            return this;
277        } catch (ParserConfigurationException e) {
278            throw new JosmRuntimeException(e);
279        }
280    }
281
282    /**
283     * Starts parsing from the given input reader, without validation.
284     * @param in The input reader
285     * @return iterable collection of objects
286     * @throws SAXException if any XML or I/O error occurs
287     */
288    public Iterable<Object> start(final Reader in) throws SAXException {
289        try {
290            return start(in, parser);
291        } catch (IOException e) {
292            throw new SAXException(e);
293        }
294    }
295
296    /**
297     * Starts parsing from the given input reader, with XSD validation.
298     * @param in The input reader
299     * @param namespace default namespace
300     * @param schemaSource XSD schema
301     * @return iterable collection of objects
302     * @throws SAXException if any XML or I/O error occurs
303     */
304    public Iterable<Object> startWithValidation(final Reader in, String namespace, String schemaSource) throws SAXException {
305        SchemaFactory factory = XmlUtils.newXmlSchemaFactory();
306        try (CachedFile cf = new CachedFile(schemaSource); InputStream mis = cf.getInputStream()) {
307            Schema schema = factory.newSchema(new StreamSource(mis));
308            ValidatorHandler validator = schema.newValidatorHandler();
309            validator.setContentHandler(parser);
310            validator.setErrorHandler(parser);
311
312            AddNamespaceFilter filter = new AddNamespaceFilter(namespace);
313            filter.setContentHandler(validator);
314            return start(in, filter);
315        } catch (IOException e) {
316            throw new SAXException(tr("Failed to load XML schema."), e);
317        }
318    }
319
320    /**
321     * Add a new tag name to class type mapping
322     * @param tagName The tag name that should be converted to that class
323     * @param klass The class the XML elements should be converted to.
324     */
325    public void map(String tagName, Class<?> klass) {
326        mapping.put(tagName, new Entry(klass, false, false));
327    }
328
329    public void mapOnStart(String tagName, Class<?> klass) {
330        mapping.put(tagName, new Entry(klass, true, false));
331    }
332
333    public void mapBoth(String tagName, Class<?> klass) {
334        mapping.put(tagName, new Entry(klass, false, true));
335    }
336
337    /**
338     * Get the next element that was parsed
339     * @return The next object
340     */
341    public Object next() {
342        return queueIterator.next();
343    }
344
345    /**
346     * Check if there is a next parsed object available
347     * @return <code>true</code> if there is a next object
348     */
349    public boolean hasNext() {
350        return queueIterator.hasNext();
351    }
352
353    @Override
354    public Iterator<Object> iterator() {
355        return queue.iterator();
356    }
357}