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