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