Add convenience methods for XML codec
[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             String xmlElementName = in.getLocalName();
477             while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
478                 read(in, newEntryNode(parent), rootElement);
479                 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
480                         || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
481                     break;
482                 }
483                 xmlElementName = in.getLocalName();
484             }
485
486             return;
487         }
488
489         if (parent instanceof AnyXmlNodeDataWithSchema) {
490             setValue((AnyXmlNodeDataWithSchema) parent, readAnyXmlValue(in), in.getNamespaceContext());
491             if (isNextEndDocument(in)) {
492                 return;
493             }
494
495             if (!isAtElement(in)) {
496                 in.nextTag();
497             }
498
499             return;
500         }
501
502         if (parent instanceof AnydataNodeDataWithSchema) {
503             final AnydataNodeDataWithSchema anydata = (AnydataNodeDataWithSchema) parent;
504             anydata.setObjectModel(DOMSourceAnydata.class);
505             anydata.setAttributes(getElementAttributes(in));
506             setValue(anydata, readAnyXmlValue(in), in.getNamespaceContext());
507             if (isNextEndDocument(in)) {
508                 return;
509             }
510
511             if (!isAtElement(in)) {
512                 in.nextTag();
513             }
514
515             return;
516         }
517
518         switch (in.nextTag()) {
519             case XMLStreamConstants.START_ELEMENT:
520                 // FIXME: 7.0.0: why do we even need this tracker? either document it or remove it.
521                 //               it looks like it is a crude duplicate finder, which should really be handled via
522                 //               ChildReusePolicy.REJECT
523                 final Set<Entry<String, String>> namesakes = new HashSet<>();
524                 while (in.hasNext()) {
525                     final String xmlElementName = in.getLocalName();
526                     final DataSchemaNode parentSchema = parent.getSchema();
527
528                     final String parentSchemaName = parentSchema.getQName().getLocalName();
529                     if (parentSchemaName.equals(xmlElementName)
530                             && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
531                         if (isNextEndDocument(in)) {
532                             break;
533                         }
534
535                         if (!isAtElement(in)) {
536                             in.nextTag();
537                         }
538                         break;
539                     }
540
541                     if (in.isEndElement() && rootElement.equals(xmlElementName)) {
542                         break;
543                     }
544
545                     final String elementNS = in.getNamespaceURI();
546                     final boolean added = namesakes.add(new SimpleImmutableEntry<>(elementNS, xmlElementName));
547
548                     final XMLNamespace nsUri;
549                     try {
550                         nsUri = rawXmlNamespace(elementNS).getNamespace();
551                     } catch (IllegalArgumentException e) {
552                         throw new XMLStreamException("Failed to convert namespace " + xmlElementName, in.getLocation(),
553                             e);
554                     }
555
556                     final Deque<DataSchemaNode> childDataSchemaNodes =
557                             ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName, nsUri);
558                     if (!childDataSchemaNodes.isEmpty()) {
559                         final boolean elementList = isElementList(childDataSchemaNodes);
560                         if (!added && !elementList) {
561                             throw new XMLStreamException(String.format(
562                                 "Duplicate element \"%s\" in namespace \"%s\" with parent \"%s\" in XML input",
563                                 xmlElementName, elementNS, parentSchema), in.getLocation());
564                         }
565
566                         // We have a match, proceed with it
567                         final QName qname = childDataSchemaNodes.peekLast().getQName();
568                         final AbstractNodeDataWithSchema<?> child = ((CompositeNodeDataWithSchema<?>) parent).addChild(
569                             childDataSchemaNodes, elementList ? ChildReusePolicy.REUSE : ChildReusePolicy.NOOP);
570                         stack.enterDataTree(qname);
571                         read(in, child, rootElement);
572                         stack.exit();
573                         continue;
574                     }
575
576                     if (parent instanceof AbstractMountPointDataWithSchema) {
577                         // Parent can potentially hold a mount point, let's see if there is a label present
578                         final Optional<MountPointSchemaNode> optMount;
579                         if (parentSchema instanceof ContainerSchemaNode) {
580                             optMount = MountPointSchemaNode.streamAll((ContainerSchemaNode) parentSchema).findFirst();
581                         } else if (parentSchema instanceof ListSchemaNode) {
582                             optMount = MountPointSchemaNode.streamAll((ListSchemaNode) parentSchema).findFirst();
583                         } else {
584                             throw new XMLStreamException("Unhandled mount-aware schema " + parentSchema,
585                                 in.getLocation());
586                         }
587
588                         if (optMount.isPresent()) {
589                             final MountPointIdentifier mountId = MountPointIdentifier.of(optMount.get().getQName());
590                             LOG.debug("Assuming node {} and namespace {} belongs to mount point {}", xmlElementName,
591                                 nsUri, mountId);
592
593                             final Optional<MountPointContextFactory> optFactory = codecs.mountPointContext()
594                                     .findMountPoint(mountId);
595                             if (optFactory.isPresent()) {
596                                 final MountPointData mountData = ((AbstractMountPointDataWithSchema<?>) parent)
597                                         .getMountPointData(mountId, optFactory.get());
598                                 addMountPointChild(mountData, nsUri, xmlElementName,
599                                     new DOMSource(readAnyXmlValue(in).getDocumentElement()));
600                                 continue;
601                             }
602
603                             LOG.debug("Mount point {} not attached", mountId);
604                         }
605                     }
606
607                     // We have not handled the node -- let's decide what to do about that
608                     if (strictParsing) {
609                         throw new XMLStreamException(String.format(
610                             "Schema for node with name %s and namespace %s does not exist in parent %s", xmlElementName,
611                             elementNS, parentSchema), in.getLocation());
612                     }
613
614                     LOG.debug("Skipping unknown node ns=\"{}\" localName=\"{}\" in parent {}", elementNS,
615                         xmlElementName, parentSchema);
616                     skipUnknownNode(in);
617                 }
618                 break;
619             case XMLStreamConstants.END_ELEMENT:
620                 if (isNextEndDocument(in)) {
621                     break;
622                 }
623
624                 if (!isAtElement(in)) {
625                     in.nextTag();
626                 }
627                 break;
628             default:
629                 break;
630         }
631     }
632
633     // Return true if schema represents a construct which uses multiple sibling elements to represent its content. The
634     // siblings MAY be interleaved as per RFC7950.
635     private static boolean isElementList(final Deque<DataSchemaNode> childDataSchemaNodes) {
636         final DataSchemaNode last = childDataSchemaNodes.getLast();
637         return last instanceof ListSchemaNode || last instanceof LeafListSchemaNode;
638     }
639
640     private static void addMountPointChild(final MountPointData mount, final XMLNamespace namespace,
641             final String localName, final DOMSource source) {
642         final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
643         if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
644             final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
645             if (optName.isPresent()) {
646                 mount.setContainer(optName.get(), child);
647                 return;
648             }
649
650             LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
651         } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
652             mount.setSchemaMounts(child);
653             return;
654         }
655
656         mount.addChild(child);
657     }
658
659     private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
660         return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
661     }
662
663     private static boolean isAtElement(final XMLStreamReader in) {
664         return in.getEventType() == XMLStreamConstants.START_ELEMENT
665                 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
666     }
667
668     private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
669         // in case when the unknown node and at least one of its descendant nodes have the same name
670         // we cannot properly reach the end just by checking if the current node is an end element and has the same name
671         // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
672         int levelOfNesting = 0;
673         while (in.hasNext()) {
674             // in case there are text characters in an element, we cannot skip them by calling nextTag()
675             // therefore we skip them by calling next(), and then proceed to next element
676             in.next();
677             if (!isAtElement(in)) {
678                 in.nextTag();
679             }
680             if (in.isStartElement()) {
681                 levelOfNesting++;
682             }
683
684             if (in.isEndElement()) {
685                 if (levelOfNesting == 0) {
686                     break;
687                 }
688
689                 levelOfNesting--;
690             }
691         }
692
693         in.nextTag();
694     }
695
696     private void setValue(final SimpleNodeDataWithSchema<?> parent, final Object value,
697             final NamespaceContext nsContext) {
698         final DataSchemaNode schema = parent.getSchema();
699         final Object prev = parent.getValue();
700         checkArgument(prev == null, "Node '%s' has already set its value to '%s'", schema.getQName(), prev);
701         parent.setValue(translateValueByType(value, schema, nsContext));
702     }
703
704     private Object translateValueByType(final Object value, final DataSchemaNode node,
705             final NamespaceContext namespaceCtx) {
706         if (node instanceof AnyxmlSchemaNode) {
707             checkArgument(value instanceof Document);
708             /*
709              * FIXME: Figure out some YANG extension dispatch, which will reuse JSON parsing or XML parsing -
710              *        anyxml is not well-defined in JSON.
711              */
712             return new DOMSource(((Document) value).getDocumentElement());
713         }
714         if (node instanceof AnydataSchemaNode) {
715             checkArgument(value instanceof Document);
716             return new DOMSourceAnydata(new DOMSource(((Document) value).getDocumentElement()));
717         }
718
719         checkArgument(node instanceof TypedDataSchemaNode);
720         checkArgument(value instanceof String);
721         return codecs.codecFor((TypedDataSchemaNode) node, stack).parseValue(namespaceCtx, (String) value);
722     }
723
724     private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
725         verify(parent instanceof MultipleEntryDataWithSchema, "Unexpected parent %s", parent);
726         return ((MultipleEntryDataWithSchema<?>) parent).newChildEntry();
727     }
728
729     @Override
730     public void close() throws IOException {
731         writer.flush();
732         writer.close();
733     }
734
735     @Override
736     public void flush() throws IOException {
737         writer.flush();
738     }
739
740     private Optional<QNameModule> resolveXmlNamespace(final String xmlNamespace) {
741         return resolvedNamespaces.computeIfAbsent(xmlNamespace, nsUri -> {
742             final Iterator<? extends Module> it = codecs.getEffectiveModelContext().findModules(XMLNamespace.of(nsUri))
743                     .iterator();
744             return it.hasNext() ? Optional.of(it.next().getQNameModule()) : Optional.empty();
745         });
746     }
747
748     private QNameModule rawXmlNamespace(final String xmlNamespace) {
749         return rawNamespaces.computeIfAbsent(xmlNamespace, nsUri -> QNameModule.create(XMLNamespace.of(nsUri)));
750     }
751 }