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