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