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