YANGTOOLS-890 - Fix XML parser bug
[yangtools.git] / yang / yang-data-codec-xml / src / main / java / org / opendaylight / yangtools / yang / data / codec / xml / XmlParserStream.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.codec.xml;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.xml.XmlEscapers;
17 import java.io.Closeable;
18 import java.io.Flushable;
19 import java.io.IOException;
20 import java.io.StringReader;
21 import java.net.URI;
22 import java.net.URISyntaxException;
23 import java.util.Deque;
24 import java.util.HashSet;
25 import java.util.LinkedHashMap;
26 import java.util.Map;
27 import java.util.Set;
28 import javax.annotation.concurrent.NotThreadSafe;
29 import javax.xml.XMLConstants;
30 import javax.xml.namespace.NamespaceContext;
31 import javax.xml.parsers.ParserConfigurationException;
32 import javax.xml.stream.Location;
33 import javax.xml.stream.XMLStreamConstants;
34 import javax.xml.stream.XMLStreamException;
35 import javax.xml.stream.XMLStreamReader;
36 import javax.xml.transform.dom.DOMSource;
37 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyXmlSchemaNode;
38 import org.opendaylight.yangtools.util.xml.UntrustedXML;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
42 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
43 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
44 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
45 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
46 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
47 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
48 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
49 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
51 import org.opendaylight.yangtools.yang.data.util.RpcAsContainer;
52 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
53 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
54 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
64 import org.w3c.dom.Document;
65 import org.xml.sax.InputSource;
66 import org.xml.sax.SAXException;
67
68 /**
69  * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
70  * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
71  * the XML source are wrapped in a root element.
72  */
73 @Beta
74 @NotThreadSafe
75 public final class XmlParserStream implements Closeable, Flushable {
76     private final NormalizedNodeStreamWriter writer;
77     private final XmlCodecFactory codecs;
78     private final DataSchemaNode parentNode;
79     private final boolean strictParsing;
80
81     private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
82             final DataSchemaNode parentNode, final boolean strictParsing) {
83         this.writer = requireNonNull(writer);
84         this.codecs = requireNonNull(codecs);
85         this.parentNode = parentNode;
86         this.strictParsing = strictParsing;
87     }
88
89     /**
90      * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
91      *
92      * @param writer Output writer
93      * @param codecs Shared codecs
94      * @param parentNode Parent root node
95      * @return A new stream instance
96      */
97     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
98             final SchemaNode parentNode) {
99         return create(writer, codecs, parentNode, true);
100     }
101
102     /**
103      * Construct a new {@link XmlParserStream}.
104      *
105      * @param writer Output writer
106      * @param codecs Shared codecs
107      * @param parentNode Parent root node
108      * @param strictParsing parsing mode
109      *            if set to true, the parser will throw an exception if it encounters unknown child nodes
110      *            (nodes, that are not defined in the provided SchemaContext) in containers and lists
111      *            if set to false, the parser will skip unknown child nodes
112      * @return A new stream instance
113      */
114     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
115             final SchemaNode parentNode, final boolean strictParsing) {
116         if (parentNode instanceof RpcDefinition) {
117             return new XmlParserStream(writer, codecs, new RpcAsContainer((RpcDefinition) parentNode), strictParsing);
118         }
119         checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
120         return new XmlParserStream(writer, codecs, (DataSchemaNode) parentNode, strictParsing);
121     }
122
123     /**
124      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
125      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
126      * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
127      */
128     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
129             final SchemaNode parentNode) {
130         return create(writer, schemaContext, parentNode, true);
131     }
132
133     /**
134      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
135      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
136      * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
137      */
138     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
139             final SchemaNode parentNode, final boolean strictParsing) {
140         return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
141     }
142
143     /**
144      * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
145      * YANG-modeled data contained in the XML source.
146      *
147      * @param reader
148      *              StAX reader which is to used to walk through the XML source
149      * @return
150      *              instance of XmlParserStream
151      * @throws XMLStreamException
152      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
153      * @throws URISyntaxException
154      *              if the namespace URI of an XML element contains a syntax error
155      * @throws IOException
156      *              if an error occurs while parsing the value of an anyxml node
157      * @throws ParserConfigurationException
158      *              if an error occurs while parsing the value of an anyxml node
159      * @throws SAXException
160      *              if an error occurs while parsing the value of an anyxml node
161      */
162     // FIXME: 3.0.0 remove ParserConfigurationException
163     public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
164             IOException, ParserConfigurationException, SAXException {
165         if (reader.hasNext()) {
166             reader.nextTag();
167             final AbstractNodeDataWithSchema nodeDataWithSchema;
168             if (parentNode instanceof ContainerSchemaNode) {
169                 nodeDataWithSchema = new ContainerNodeDataWithSchema(parentNode);
170             } else if (parentNode instanceof ListSchemaNode) {
171                 nodeDataWithSchema = new ListNodeDataWithSchema(parentNode);
172             } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
173                 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
174             } else if (parentNode instanceof AnyXmlSchemaNode) {
175                 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(parentNode);
176             } else if (parentNode instanceof LeafSchemaNode) {
177                 nodeDataWithSchema = new LeafNodeDataWithSchema(parentNode);
178             } else if (parentNode instanceof LeafListSchemaNode) {
179                 nodeDataWithSchema = new LeafListNodeDataWithSchema(parentNode);
180             } else {
181                 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
182             }
183
184             read(reader, nodeDataWithSchema, reader.getLocalName());
185             nodeDataWithSchema.write(writer);
186         }
187
188         return this;
189     }
190
191     /**
192      * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
193      * YANG-modeled data contained in the source.
194      *
195      * @param src
196      *              {@link DOMSource} to be traversed
197      * @return
198      *              instance of XmlParserStream
199      * @throws XMLStreamException
200      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
201      * @throws URISyntaxException
202      *              if the namespace URI of an XML element contains a syntax error
203      * @throws IOException
204      *              if an error occurs while parsing the value of an anyxml node
205      * @throws ParserConfigurationException
206      *              if an error occurs while parsing the value of an anyxml node
207      * @throws SAXException
208      *              if an error occurs while parsing the value of an anyxml node
209      */
210     @Beta
211     // FIXME: 3.0.0 remove ParserConfigurationException
212     public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException,
213         IOException, ParserConfigurationException, SAXException {
214         return parse(new DOMSourceXMLStreamReader(src));
215     }
216
217     private static Map<QName, String> getElementAttributes(final XMLStreamReader in) {
218         checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
219         final Map<QName, String> attributes = new LinkedHashMap<>();
220
221         for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
222             String attributeNS = in.getAttributeNamespace(attrIndex);
223
224             if (attributeNS == null) {
225                 attributeNS = "";
226             }
227
228             // Skip namespace definitions
229             if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
230                 continue;
231             }
232
233             final QName qName = QName.create(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
234             attributes.put(qName, in.getAttributeValue(attrIndex));
235         }
236
237         return ImmutableMap.copyOf(attributes);
238     }
239
240     private static String readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
241         final StringBuilder sb = new StringBuilder();
242         final String anyXmlElementName = in.getLocalName();
243         sb.append('<').append(anyXmlElementName).append(" xmlns=\"").append(in.getNamespaceURI()).append("\">");
244
245         while (in.hasNext()) {
246             final int eventType = in.next();
247
248             if (eventType == XMLStreamConstants.START_ELEMENT) {
249                 sb.append('<').append(in.getLocalName()).append('>');
250             } else if (eventType == XMLStreamConstants.END_ELEMENT) {
251                 sb.append("</").append(in.getLocalName()).append('>');
252
253                 if (in.getLocalName().equals(anyXmlElementName)) {
254                     break;
255                 }
256
257             } else if (eventType == XMLStreamConstants.CHARACTERS) {
258                 sb.append(XmlEscapers.xmlContentEscaper().escape(in.getText()));
259             }
260         }
261
262         return sb.toString();
263     }
264
265     private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent, final String rootElement)
266             throws XMLStreamException, URISyntaxException, SAXException, IOException {
267         if (!in.hasNext()) {
268             return;
269         }
270
271         if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
272             parent.setAttributes(getElementAttributes(in));
273             setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
274             if (isNextEndDocument(in)) {
275                 return;
276             }
277
278             if (!isAtElement(in)) {
279                 in.nextTag();
280             }
281             return;
282         }
283
284         if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
285             parent.setAttributes(getElementAttributes(in));
286         }
287
288         if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
289             String xmlElementName = in.getLocalName();
290             while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
291                 read(in, newEntryNode(parent), rootElement);
292                 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
293                         || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
294                     break;
295                 }
296                 xmlElementName = in.getLocalName();
297             }
298
299             return;
300         }
301
302         if (parent instanceof AnyXmlNodeDataWithSchema) {
303             setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
304             if (isNextEndDocument(in)) {
305                 return;
306             }
307
308             if (!isAtElement(in)) {
309                 in.nextTag();
310             }
311
312             return;
313         }
314
315         if (parent instanceof YangModeledAnyXmlSchemaNode) {
316             parent.setAttributes(getElementAttributes(in));
317         }
318
319         switch (in.nextTag()) {
320             case XMLStreamConstants.START_ELEMENT:
321                 final Set<String> namesakes = new HashSet<>();
322                 while (in.hasNext()) {
323                     final String xmlElementName = in.getLocalName();
324
325                     DataSchemaNode parentSchema = parent.getSchema();
326
327                     final String parentSchemaName = parentSchema.getQName().getLocalName();
328                     if (parentSchemaName.equals(xmlElementName)
329                             && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
330                         if (isNextEndDocument(in)) {
331                             break;
332                         }
333
334                         if (!isAtElement(in)) {
335                             in.nextTag();
336                         }
337                         break;
338                     }
339
340                     if (in.isEndElement() && rootElement.equals(xmlElementName)) {
341                         break;
342                     }
343
344                     if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
345                         parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
346                     }
347
348                     if (!namesakes.add(xmlElementName)) {
349                         final Location loc = in.getLocation();
350                         throw new IllegalStateException(String.format(
351                                 "Duplicate element \"%s\" in XML input at: line %s column %s", xmlElementName,
352                                 loc.getLineNumber(), loc.getColumnNumber()));
353                     }
354
355                     final String xmlElementNamespace = in.getNamespaceURI();
356                     final Deque<DataSchemaNode> childDataSchemaNodes =
357                             ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
358                                     new URI(xmlElementNamespace));
359
360                     if (childDataSchemaNodes.isEmpty()) {
361                         checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
362                             xmlElementName, xmlElementNamespace, parentSchema.getPath());
363                         skipUnknownNode(in);
364                         continue;
365                     }
366
367                     read(in, ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes), rootElement);
368                 }
369                 break;
370             case XMLStreamConstants.END_ELEMENT:
371                 if (isNextEndDocument(in)) {
372                     break;
373                 }
374
375                 if (!isAtElement(in)) {
376                     in.nextTag();
377                 }
378                 break;
379             default:
380                 break;
381         }
382     }
383
384     private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
385         return in.next() == XMLStreamConstants.END_DOCUMENT;
386     }
387
388     private static boolean isAtElement(final XMLStreamReader in) {
389         return in.getEventType() == XMLStreamConstants.START_ELEMENT
390                 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
391     }
392
393     private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
394         // in case when the unknown node and at least one of its descendant nodes have the same name
395         // we cannot properly reach the end just by checking if the current node is an end element and has the same name
396         // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
397         int levelOfNesting = 0;
398         while (in.hasNext()) {
399             // in case there are text characters in an element, we cannot skip them by calling nextTag()
400             // therefore we skip them by calling next(), and then proceed to next element
401             in.next();
402             if (!isAtElement(in)) {
403                 in.nextTag();
404             }
405             if (in.isStartElement()) {
406                 levelOfNesting++;
407             }
408
409             if (in.isEndElement()) {
410                 if (levelOfNesting == 0) {
411                     break;
412                 }
413
414                 levelOfNesting--;
415             }
416         }
417
418         in.nextTag();
419     }
420
421     private void setValue(final AbstractNodeDataWithSchema parent, final String value, final NamespaceContext nsContext)
422             throws SAXException, IOException {
423         checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
424                 parent.getSchema().getQName());
425         final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
426         checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
427                 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
428
429         parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
430     }
431
432     private Object translateValueByType(final String value, final DataSchemaNode node,
433             final NamespaceContext namespaceCtx) throws IOException, SAXException {
434         if (node instanceof AnyXmlSchemaNode) {
435             /*
436              *  FIXME: Figure out some YANG extension dispatch, which will
437              *  reuse JSON parsing or XML parsing - anyxml is not well-defined in
438              * JSON.
439              */
440             final Document doc = UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(value)));
441             doc.normalize();
442
443             return new DOMSource(doc.getDocumentElement());
444         }
445
446         checkArgument(node instanceof TypedDataSchemaNode);
447         return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, value);
448     }
449
450     private static AbstractNodeDataWithSchema newEntryNode(final AbstractNodeDataWithSchema parent) {
451         final AbstractNodeDataWithSchema newChild;
452         if (parent instanceof ListNodeDataWithSchema) {
453             newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
454         } else {
455             newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
456         }
457         ((CompositeNodeDataWithSchema) parent).addChild(newChild);
458         return newChild;
459     }
460
461     @Override
462     public void close() throws IOException {
463         writer.flush();
464         writer.close();
465     }
466
467     @Override
468     public void flush() throws IOException {
469         writer.flush();
470     }
471 }