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