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