Allow list elements to be interleaved
[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 com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.annotations.Beta;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableMap;
18 import java.io.Closeable;
19 import java.io.Flushable;
20 import java.io.IOException;
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.HashMap;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.LinkedHashMap;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.Set;
33 import javax.xml.XMLConstants;
34 import javax.xml.namespace.NamespaceContext;
35 import javax.xml.stream.XMLStreamConstants;
36 import javax.xml.stream.XMLStreamException;
37 import javax.xml.stream.XMLStreamReader;
38 import javax.xml.stream.util.StreamReaderDelegate;
39 import javax.xml.transform.TransformerException;
40 import javax.xml.transform.TransformerFactory;
41 import javax.xml.transform.TransformerFactoryConfigurationError;
42 import javax.xml.transform.dom.DOMResult;
43 import javax.xml.transform.dom.DOMSource;
44 import javax.xml.transform.stax.StAXSource;
45 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyxmlSchemaNode;
46 import org.opendaylight.yangtools.rfc7952.model.api.AnnotationSchemaNode;
47 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
48 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContextFactory;
49 import org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier;
50 import org.opendaylight.yangtools.rfc8528.data.api.YangLibraryConstants;
51 import org.opendaylight.yangtools.rfc8528.data.api.YangLibraryConstants.ContainerName;
52 import org.opendaylight.yangtools.rfc8528.model.api.MountPointSchemaNode;
53 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.QNameModule;
56 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
57 import org.opendaylight.yangtools.yang.data.util.AbstractMountPointDataWithSchema;
58 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
59 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
60 import org.opendaylight.yangtools.yang.data.util.AnydataNodeDataWithSchema;
61 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
62 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema.ChildReusePolicy;
63 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
64 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
65 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
66 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
67 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
68 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
69 import org.opendaylight.yangtools.yang.data.util.MountPointData;
70 import org.opendaylight.yangtools.yang.data.util.MultipleEntryDataWithSchema;
71 import org.opendaylight.yangtools.yang.data.util.OperationAsContainer;
72 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
73 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
74 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
75 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
80 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.Module;
84 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
85 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89 import org.w3c.dom.Document;
90 import org.xml.sax.SAXException;
91
92 /**
93  * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
94  * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
95  * the XML source are wrapped in a root element. This class is NOT thread-safe.
96  *
97  * <p>
98  * Due to backwards compatibility reasons, RFC7952 metadata emitted by this parser may include key QNames with empty URI
99  * (as exposed via {@link #LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an unqualified XML
100  * attribute and their value can be assumed to be a String. Furthermore, this extends to qualified attributes, which
101  * uses the proper namespace, but will not bind to a proper module revision -- these need to be reconciled with a
102  * particular SchemaContext and are expected to either be fully decoded, or contain a String value. Handling of such
103  * annotations is at the discretion of the user encountering it: preferred way of handling is to either filter or
104  * normalize them to proper QNames/values when encountered. This caveat will be removed in a future version.
105  */
106 @Beta
107 public final class XmlParserStream implements Closeable, Flushable {
108     /**
109      * {@link QNameModule} for use with legacy XML attributes.
110      * @deprecated The use on this namespace is discouraged and users are strongly encouraged to proper RFC7952 metadata
111      *             annotations.
112      */
113     @Deprecated
114     public static final QNameModule LEGACY_ATTRIBUTE_NAMESPACE = QNameModule.create(URI.create("")).intern();
115
116     private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
117     private static final String XML_STANDARD_VERSION = "1.0";
118     private static final String COM_SUN_TRANSFORMER =
119             "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
120
121     private static final TransformerFactory TRANSFORMER_FACTORY;
122
123     static {
124         TransformerFactory fa = TransformerFactory.newInstance();
125         if (!fa.getFeature(StAXSource.FEATURE)) {
126             LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
127                     fa, COM_SUN_TRANSFORMER);
128             fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
129             if (!fa.getFeature(StAXSource.FEATURE)) {
130                 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
131             }
132         }
133
134         TRANSFORMER_FACTORY = fa;
135     }
136
137     // Cache of nsUri Strings to QNameModules, as resolved in context
138     private final Map<String, Optional<QNameModule>> resolvedNamespaces = new HashMap<>();
139     // Cache of nsUri Strings to QNameModules, as inferred from document
140     private final Map<String, QNameModule> rawNamespaces = new HashMap<>();
141     private final NormalizedNodeStreamWriter writer;
142     private final XmlCodecFactory codecs;
143     private final DataSchemaNode parentNode;
144     private final boolean strictParsing;
145
146     private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
147             final DataSchemaNode parentNode, final boolean strictParsing) {
148         this.writer = requireNonNull(writer);
149         this.codecs = requireNonNull(codecs);
150         this.parentNode = parentNode;
151         this.strictParsing = strictParsing;
152     }
153
154     /**
155      * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
156      *
157      * @param writer Output writer
158      * @param codecs Shared codecs
159      * @param parentNode Parent root node
160      * @return A new stream instance
161      */
162     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
163             final SchemaNode parentNode) {
164         return create(writer, codecs, parentNode, true);
165     }
166
167     /**
168      * Construct a new {@link XmlParserStream}.
169      *
170      * @param writer Output writer
171      * @param codecs Shared codecs
172      * @param parentNode Parent root node
173      * @param strictParsing parsing mode
174      *            if set to true, the parser will throw an exception if it encounters unknown child nodes
175      *            (nodes, that are not defined in the provided SchemaContext) in containers and lists
176      *            if set to false, the parser will skip unknown child nodes
177      * @return A new stream instance
178      */
179     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
180             final SchemaNode parentNode, final boolean strictParsing) {
181         final DataSchemaNode parent;
182         if (parentNode instanceof DataSchemaNode) {
183             parent = (DataSchemaNode) parentNode;
184         } else if (parentNode instanceof OperationDefinition) {
185             parent = OperationAsContainer.of((OperationDefinition) parentNode);
186         } else {
187             throw new IllegalArgumentException("Illegal parent node " + parentNode);
188         }
189         return new XmlParserStream(writer, codecs, parent, strictParsing);
190     }
191
192     /**
193      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
194      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
195      * maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
196      */
197     public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
198             final EffectiveModelContext schemaContext, final SchemaNode parentNode) {
199         return create(writer, schemaContext, parentNode, true);
200     }
201
202     /**
203      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
204      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
205      * maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
206      */
207     public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
208             final EffectiveModelContext schemaContext, final SchemaNode parentNode, final boolean strictParsing) {
209         return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
210     }
211
212     /**
213      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
214      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
215      * maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
216      */
217     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
218             final SchemaNode parentNode) {
219         return create(writer, mountCtx, parentNode, true);
220     }
221
222     /**
223      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
224      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
225      * maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
226      */
227     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
228             final SchemaNode parentNode, final boolean strictParsing) {
229         return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
230     }
231
232     /**
233      * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
234      * YANG-modeled data contained in the XML source.
235      *
236      * @param reader
237      *              StAX reader which is to used to walk through the XML source
238      * @return
239      *              instance of XmlParserStream
240      * @throws XMLStreamException
241      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
242      * @throws URISyntaxException
243      *              if the namespace URI of an XML element contains a syntax error
244      * @throws IOException
245      *              if an error occurs while parsing the value of an anyxml node
246      * @throws SAXException
247      *              if an error occurs while parsing the value of an anyxml node
248      */
249     public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
250             IOException, SAXException {
251         if (reader.hasNext()) {
252             reader.nextTag();
253             final AbstractNodeDataWithSchema<?> nodeDataWithSchema;
254             if (parentNode instanceof ContainerSchemaNode) {
255                 nodeDataWithSchema = new ContainerNodeDataWithSchema((ContainerSchemaNode) parentNode);
256             } else if (parentNode instanceof ListSchemaNode) {
257                 nodeDataWithSchema = new ListNodeDataWithSchema((ListSchemaNode) parentNode);
258             } else if (parentNode instanceof YangModeledAnyxmlSchemaNode) {
259                 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyxmlSchemaNode) parentNode);
260             } else if (parentNode instanceof AnyxmlSchemaNode) {
261                 nodeDataWithSchema = new AnyXmlNodeDataWithSchema((AnyxmlSchemaNode) parentNode);
262             } else if (parentNode instanceof LeafSchemaNode) {
263                 nodeDataWithSchema = new LeafNodeDataWithSchema((LeafSchemaNode) parentNode);
264             } else if (parentNode instanceof LeafListSchemaNode) {
265                 nodeDataWithSchema = new LeafListNodeDataWithSchema((LeafListSchemaNode) parentNode);
266             } else if (parentNode instanceof AnydataSchemaNode) {
267                 nodeDataWithSchema = new AnydataNodeDataWithSchema((AnydataSchemaNode) parentNode);
268             } else {
269                 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
270             }
271
272             read(reader, nodeDataWithSchema, reader.getLocalName());
273             nodeDataWithSchema.write(writer);
274         }
275
276         return this;
277     }
278
279     /**
280      * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
281      * YANG-modeled data contained in the source.
282      *
283      * @param src
284      *              {@link DOMSource} to be traversed
285      * @return
286      *              instance of XmlParserStream
287      * @throws XMLStreamException
288      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
289      * @throws URISyntaxException
290      *              if the namespace URI of an XML element contains a syntax error
291      * @throws IOException
292      *              if an error occurs while parsing the value of an anyxml node
293      * @throws SAXException
294      *              if an error occurs while parsing the value of an anyxml node
295      */
296     @Beta
297     public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
298             SAXException {
299         return parse(new DOMSourceXMLStreamReader(src));
300     }
301
302     private ImmutableMap<QName, Object> getElementAttributes(final XMLStreamReader in) {
303         checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
304         final Map<QName, Object> attributes = new LinkedHashMap<>();
305
306         for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
307             final String attributeNS = in.getAttributeNamespace(attrIndex);
308
309             // Skip namespace definitions
310             if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
311                 continue;
312             }
313
314             final String localName = in.getAttributeLocalName(attrIndex);
315             final String attrValue = in.getAttributeValue(attrIndex);
316             if (Strings.isNullOrEmpty(attributeNS)) {
317                 StreamWriterFacade.warnLegacyAttribute(localName);
318                 attributes.put(QName.create(LEGACY_ATTRIBUTE_NAMESPACE, localName), attrValue);
319                 continue;
320             }
321
322             // Cross-relate attribute namespace to the module
323             final Optional<QNameModule> optModule = resolveXmlNamespace(attributeNS);
324             if (optModule.isPresent()) {
325                 final QName qname = QName.create(optModule.get(), localName);
326                 final Optional<AnnotationSchemaNode> optAnnotation = AnnotationSchemaNode.find(
327                     codecs.getSchemaContext(), qname);
328                 if (optAnnotation.isPresent()) {
329                     final AnnotationSchemaNode schema = optAnnotation.get();
330                     final Object value = codecs.codecFor(schema).parseValue(in.getNamespaceContext(), attrValue);
331                     attributes.put(schema.getQName(), value);
332                     continue;
333                 }
334
335                 LOG.debug("Annotation for {} not found, using legacy QName", qname);
336             }
337
338             attributes.put(QName.create(rawXmlNamespace(attributeNS), localName), attrValue);
339         }
340
341         return ImmutableMap.copyOf(attributes);
342     }
343
344     private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
345         // Underlying reader might return null when asked for version, however when such reader is plugged into
346         // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
347         final XMLStreamReader inWrapper;
348         if (in.getVersion() == null) {
349             inWrapper = new StreamReaderDelegate(in) {
350                 @Override
351                 public String getVersion() {
352                     final String ver = super.getVersion();
353                     return ver != null ? ver : XML_STANDARD_VERSION;
354                 }
355             };
356         } else {
357             inWrapper = in;
358         }
359
360         final DOMResult result = new DOMResult();
361         try {
362             TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
363         } catch (final TransformerException e) {
364             throw new XMLStreamException("Unable to read anyxml value", e);
365         }
366         return (Document) result.getNode();
367     }
368
369     private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
370             throws XMLStreamException {
371         if (!in.hasNext()) {
372             return;
373         }
374
375         if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
376             parent.setAttributes(getElementAttributes(in));
377             setValue((SimpleNodeDataWithSchema<?>) parent, in.getElementText().trim(), in.getNamespaceContext());
378             if (isNextEndDocument(in)) {
379                 return;
380             }
381
382             if (!isAtElement(in)) {
383                 in.nextTag();
384             }
385             return;
386         }
387
388         if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
389             parent.setAttributes(getElementAttributes(in));
390         }
391
392         if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
393             String xmlElementName = in.getLocalName();
394             while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
395                 read(in, newEntryNode(parent), rootElement);
396                 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
397                         || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
398                     break;
399                 }
400                 xmlElementName = in.getLocalName();
401             }
402
403             return;
404         }
405
406         if (parent instanceof AnyXmlNodeDataWithSchema) {
407             setValue((AnyXmlNodeDataWithSchema) parent, readAnyXmlValue(in), in.getNamespaceContext());
408             if (isNextEndDocument(in)) {
409                 return;
410             }
411
412             if (!isAtElement(in)) {
413                 in.nextTag();
414             }
415
416             return;
417         }
418
419         if (parent instanceof AnydataNodeDataWithSchema) {
420             final AnydataNodeDataWithSchema anydata = (AnydataNodeDataWithSchema) parent;
421             anydata.setObjectModel(DOMSourceAnydata.class);
422             anydata.setAttributes(getElementAttributes(in));
423             setValue(anydata, readAnyXmlValue(in), in.getNamespaceContext());
424             if (isNextEndDocument(in)) {
425                 return;
426             }
427
428             if (!isAtElement(in)) {
429                 in.nextTag();
430             }
431
432             return;
433         }
434
435         if (parent instanceof YangModeledAnyxmlSchemaNode) {
436             parent.setAttributes(getElementAttributes(in));
437         }
438
439         switch (in.nextTag()) {
440             case XMLStreamConstants.START_ELEMENT:
441                 // FIXME: 6.0.0: why do we even need this tracker? either document it or remove it.
442                 //               it looks like it is a crude duplicate finder, which should really be handled via
443                 //               ChildReusePolicy.REJECT
444                 final Set<Entry<String, String>> namesakes = new HashSet<>();
445                 while (in.hasNext()) {
446                     final String xmlElementName = in.getLocalName();
447
448                     DataSchemaNode parentSchema = parent.getSchema();
449
450                     final String parentSchemaName = parentSchema.getQName().getLocalName();
451                     if (parentSchemaName.equals(xmlElementName)
452                             && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
453                         if (isNextEndDocument(in)) {
454                             break;
455                         }
456
457                         if (!isAtElement(in)) {
458                             in.nextTag();
459                         }
460                         break;
461                     }
462
463                     if (in.isEndElement() && rootElement.equals(xmlElementName)) {
464                         break;
465                     }
466
467                     if (parentSchema instanceof YangModeledAnyxmlSchemaNode) {
468                         parentSchema = ((YangModeledAnyxmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
469                     }
470
471                     final String elementNS = in.getNamespaceURI();
472                     final boolean added = namesakes.add(new SimpleImmutableEntry<>(elementNS, xmlElementName));
473
474                     final URI nsUri;
475                     try {
476                         nsUri = rawXmlNamespace(elementNS).getNamespace();
477                     } catch (IllegalArgumentException e) {
478                         throw new XMLStreamException("Failed to convert namespace " + xmlElementName, in.getLocation(),
479                             e);
480                     }
481
482                     final Deque<DataSchemaNode> childDataSchemaNodes =
483                             ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName, nsUri);
484                     if (!childDataSchemaNodes.isEmpty()) {
485                         final boolean elementList = isElementList(childDataSchemaNodes);
486                         if (!added && !elementList) {
487                             throw new XMLStreamException(String.format(
488                                 "Duplicate element \"%s\" in namespace \"%s\" with parent \"%s\" in XML input",
489                                 xmlElementName, elementNS, parent.getSchema()), in.getLocation());
490                         }
491
492                         // We have a match, proceed with it
493                         read(in, ((CompositeNodeDataWithSchema<?>) parent).addChild(childDataSchemaNodes,
494                             elementList ? ChildReusePolicy.REUSE : ChildReusePolicy.NOOP), rootElement);
495                         continue;
496                     }
497
498                     if (parent instanceof AbstractMountPointDataWithSchema) {
499                         // Parent can potentially hold a mount point, let's see if there is a label present
500                         final Optional<MountPointSchemaNode> optMount;
501                         if (parentSchema instanceof ContainerSchemaNode) {
502                             optMount = MountPointSchemaNode.streamAll((ContainerSchemaNode) parentSchema).findFirst();
503                         } else if (parentSchema instanceof ListSchemaNode) {
504                             optMount = MountPointSchemaNode.streamAll((ListSchemaNode) parentSchema).findFirst();
505                         } else {
506                             throw new XMLStreamException("Unhandled mount-aware schema " + parentSchema);
507                         }
508
509                         if (optMount.isPresent()) {
510                             final MountPointIdentifier mountId = MountPointIdentifier.of(optMount.get().getQName());
511                             LOG.debug("Assuming node {} and namespace {} belongs to mount point {}", xmlElementName,
512                                 nsUri, mountId);
513
514                             final Optional<MountPointContextFactory> optFactory = codecs.mountPointContext()
515                                     .findMountPoint(mountId);
516                             if (optFactory.isPresent()) {
517                                 final MountPointData mountData = ((AbstractMountPointDataWithSchema<?>) parent)
518                                         .getMountPointData(mountId, optFactory.get());
519                                 addMountPointChild(mountData, nsUri, xmlElementName,
520                                     new DOMSource(readAnyXmlValue(in).getDocumentElement()));
521                                 continue;
522                             }
523
524                             LOG.debug("Mount point {} not attached", mountId);
525                         }
526                     }
527
528                     // We have not handled the node -- let's decide what to do about that
529                     if (strictParsing) {
530                         throw new XMLStreamException(String.format(
531                             "Schema for node with name %s and namespace %s does not exist at %s", xmlElementName,
532                             elementNS, parentSchema.getPath(), in.getLocation()));
533                     }
534
535                     LOG.debug("Skipping unknown node ns=\"{}\" localName=\"{}\" at path {}", elementNS, xmlElementName,
536                         parentSchema.getPath());
537                     skipUnknownNode(in);
538                 }
539                 break;
540             case XMLStreamConstants.END_ELEMENT:
541                 if (isNextEndDocument(in)) {
542                     break;
543                 }
544
545                 if (!isAtElement(in)) {
546                     in.nextTag();
547                 }
548                 break;
549             default:
550                 break;
551         }
552     }
553
554     // Return true if schema represents a construct which uses multiple sibling elements to represent its content. The
555     // siblings MAY be interleaved as per RFC7950.
556     private static boolean isElementList(final Deque<DataSchemaNode> childDataSchemaNodes) {
557         final DataSchemaNode last = childDataSchemaNodes.getLast();
558         return last instanceof ListSchemaNode || last instanceof LeafListSchemaNode;
559     }
560
561     private static void addMountPointChild(final MountPointData mount, final URI namespace, final String localName,
562             final DOMSource source) {
563         final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
564         if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
565             final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
566             if (optName.isPresent()) {
567                 mount.setContainer(optName.get(), child);
568                 return;
569             }
570
571             LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
572         } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
573             mount.setSchemaMounts(child);
574             return;
575         }
576
577         mount.addChild(child);
578     }
579
580     private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
581         return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
582     }
583
584     private static boolean isAtElement(final XMLStreamReader in) {
585         return in.getEventType() == XMLStreamConstants.START_ELEMENT
586                 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
587     }
588
589     private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
590         // in case when the unknown node and at least one of its descendant nodes have the same name
591         // we cannot properly reach the end just by checking if the current node is an end element and has the same name
592         // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
593         int levelOfNesting = 0;
594         while (in.hasNext()) {
595             // in case there are text characters in an element, we cannot skip them by calling nextTag()
596             // therefore we skip them by calling next(), and then proceed to next element
597             in.next();
598             if (!isAtElement(in)) {
599                 in.nextTag();
600             }
601             if (in.isStartElement()) {
602                 levelOfNesting++;
603             }
604
605             if (in.isEndElement()) {
606                 if (levelOfNesting == 0) {
607                     break;
608                 }
609
610                 levelOfNesting--;
611             }
612         }
613
614         in.nextTag();
615     }
616
617     private void setValue(final SimpleNodeDataWithSchema<?> parent, final Object value,
618             final NamespaceContext nsContext) {
619         final DataSchemaNode schema = parent.getSchema();
620         final Object prev = parent.getValue();
621         checkArgument(prev == null, "Node '%s' has already set its value to '%s'", schema.getQName(), prev);
622         parent.setValue(translateValueByType(value, schema, nsContext));
623     }
624
625     private Object translateValueByType(final Object value, final DataSchemaNode node,
626             final NamespaceContext namespaceCtx) {
627         if (node instanceof AnyxmlSchemaNode) {
628             checkArgument(value instanceof Document);
629             /*
630              * FIXME: Figure out some YANG extension dispatch, which will reuse JSON parsing or XML parsing -
631              *        anyxml is not well-defined in JSON.
632              */
633             return new DOMSource(((Document) value).getDocumentElement());
634         }
635         if (node instanceof AnydataSchemaNode) {
636             checkArgument(value instanceof Document);
637             return new DOMSourceAnydata(new DOMSource(((Document) value).getDocumentElement()));
638         }
639
640         checkArgument(node instanceof TypedDataSchemaNode);
641         checkArgument(value instanceof String);
642         return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
643     }
644
645     private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
646         verify(parent instanceof MultipleEntryDataWithSchema, "Unexpected parent %s", parent);
647         return ((MultipleEntryDataWithSchema<?>) parent).newChildEntry();
648     }
649
650     @Override
651     public void close() throws IOException {
652         writer.flush();
653         writer.close();
654     }
655
656     @Override
657     public void flush() throws IOException {
658         writer.flush();
659     }
660
661     private Optional<QNameModule> resolveXmlNamespace(final String xmlNamespace) {
662         return resolvedNamespaces.computeIfAbsent(xmlNamespace, nsUri -> {
663             final Iterator<? extends Module> it = codecs.getSchemaContext().findModules(URI.create(nsUri)).iterator();
664             return it.hasNext() ? Optional.of(it.next().getQNameModule()) : Optional.empty();
665         });
666     }
667
668     private QNameModule rawXmlNamespace(final String xmlNamespace) {
669         return rawNamespaces.computeIfAbsent(xmlNamespace, nsUri -> QNameModule.create(URI.create(nsUri)));
670     }
671 }