Reduce use of yang.model.api
[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.create(XMLNamespace.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.getEffectiveModelContext();
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.getEffectiveModelContext()), 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.getEffectiveModelContext()).toInference(),
246             true);
247     }
248
249     /**
250      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
251      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
252      * instead and maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
253      */
254     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
255             final EffectiveStatementInference parentNode) {
256         return create(writer, mountCtx, parentNode, true);
257     }
258
259     @Beta
260     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
261             final Absolute parentNode) {
262         return create(writer, mountCtx, parentNode, true);
263     }
264
265     @Beta
266     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
267             final Absolute parentNode, final boolean strictParsing) {
268         return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
269     }
270
271     @Beta
272     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
273             final Absolute parentNode) {
274         return create(writer, codecs, parentNode, true);
275     }
276
277     @Beta
278     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
279             final Absolute parentNode, final boolean strictParsing) {
280         return new XmlParserStream(writer, codecs,
281             SchemaInferenceStack.of(codecs.getEffectiveModelContext(), parentNode), strictParsing);
282     }
283
284     @Beta
285     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
286             final YangInstanceIdentifier parentNode) {
287         return create(writer, mountCtx, parentNode, true);
288     }
289
290     @Beta
291     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
292             final YangInstanceIdentifier parentNode, final boolean strictParsing) {
293         final var init = DataSchemaContextTree.from(mountCtx.getEffectiveModelContext())
294             .enterPath(parentNode)
295             .orElseThrow();
296         return new XmlParserStream(writer, XmlCodecFactory.create(mountCtx), init.stack(), strictParsing);
297     }
298
299     /**
300      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
301      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
302      * instead and maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
303      */
304     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
305             final EffectiveStatementInference parentNode, final boolean strictParsing) {
306         return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
307     }
308
309     /**
310      * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
311      * YANG-modeled data contained in the XML source.
312      *
313      * @param reader
314      *              StAX reader which is to used to walk through the XML source
315      * @return
316      *              instance of XmlParserStream
317      * @throws XMLStreamException
318      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
319      * @throws IOException
320      *              if an error occurs while parsing the value of an anyxml node
321      */
322     public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, IOException {
323         if (reader.hasNext()) {
324             reader.nextTag();
325             final var nodeDataWithSchema = AbstractNodeDataWithSchema.of(parentNode);
326             read(reader, nodeDataWithSchema, reader.getLocalName());
327             nodeDataWithSchema.write(writer);
328         }
329
330         return this;
331     }
332
333     /**
334      * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
335      * YANG-modeled data contained in the source.
336      *
337      * @param src
338      *              {@link DOMSource} to be traversed
339      * @return
340      *              instance of XmlParserStream
341      * @throws XMLStreamException
342      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
343      * @throws IOException
344      *              if an error occurs while parsing the value of an anyxml node
345      */
346     @Beta
347     public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, IOException {
348         return parse(new DOMSourceXMLStreamReader(src));
349     }
350
351     private ImmutableMap<QName, Object> getElementAttributes(final XMLStreamReader in) {
352         checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
353         final var attributes = new LinkedHashMap<QName, Object>();
354
355         for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
356             final String attributeNS = in.getAttributeNamespace(attrIndex);
357
358             // Skip namespace definitions
359             if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
360                 continue;
361             }
362
363             final String localName = in.getAttributeLocalName(attrIndex);
364             final String attrValue = in.getAttributeValue(attrIndex);
365             if (Strings.isNullOrEmpty(attributeNS)) {
366                 StreamWriterFacade.warnLegacyAttribute(localName);
367                 attributes.put(QName.create(LEGACY_ATTRIBUTE_NAMESPACE, localName), attrValue);
368                 continue;
369             }
370
371             // Cross-relate attribute namespace to the module
372             final Optional<QNameModule> optModule = resolveXmlNamespace(attributeNS);
373             if (optModule.isPresent()) {
374                 final QName qname = QName.create(optModule.orElseThrow(), localName);
375                 final var optAnnotation = AnnotationSchemaNode.find(codecs.getEffectiveModelContext(),
376                     new AnnotationName(qname));
377                 if (optAnnotation.isPresent()) {
378                     final AnnotationSchemaNode schema = optAnnotation.orElseThrow();
379                     final Object value = codecs.codecFor(schema, stack)
380                         .parseValue(in.getNamespaceContext(), attrValue);
381                     attributes.put(schema.getQName(), value);
382                     continue;
383                 }
384
385                 LOG.debug("Annotation for {} not found, using legacy QName", qname);
386             }
387
388             attributes.put(QName.create(rawXmlNamespace(attributeNS), localName), attrValue);
389         }
390
391         return ImmutableMap.copyOf(attributes);
392     }
393
394     private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
395         // Underlying reader might return null when asked for version, however when such reader is plugged into
396         // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
397         final XMLStreamReader inWrapper;
398         if (in.getVersion() == null) {
399             inWrapper = new StreamReaderDelegate(in) {
400                 @Override
401                 public String getVersion() {
402                     final String ver = super.getVersion();
403                     return ver != null ? ver : XML_STANDARD_VERSION;
404                 }
405             };
406         } else {
407             inWrapper = in;
408         }
409
410         final DOMResult result = new DOMResult();
411         try {
412             TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
413         } catch (final TransformerException e) {
414             throw new XMLStreamException("Unable to read anyxml value", e);
415         }
416         return (Document) result.getNode();
417     }
418
419     private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
420             throws XMLStreamException {
421         if (!in.hasNext()) {
422             return;
423         }
424
425         if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
426             parent.setAttributes(getElementAttributes(in));
427             setValue((SimpleNodeDataWithSchema<?>) parent, in.getElementText(), in.getNamespaceContext());
428             if (isNextEndDocument(in)) {
429                 return;
430             }
431
432             if (!isAtElement(in)) {
433                 in.nextTag();
434             }
435             return;
436         }
437
438         if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
439             parent.setAttributes(getElementAttributes(in));
440         }
441
442         if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
443             final String localName = in.getLocalName();
444             final String namespaceURI = in.getNamespaceURI();
445             // aggregate current and subsequent nodes having same localName and namespace
446             // into set of entries belonging to current parent node
447             while (localName.equals(in.getLocalName()) && namespaceURI.equals(in.getNamespaceURI())) {
448                 read(in, newEntryNode(parent), rootElement);
449                 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
450                         || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
451                     break;
452                 }
453             }
454             return;
455         }
456
457         if (parent instanceof AnyXmlNodeDataWithSchema anyxml) {
458             setValue(anyxml, readAnyXmlValue(in), in.getNamespaceContext());
459             if (isNextEndDocument(in)) {
460                 return;
461             }
462
463             if (!isAtElement(in)) {
464                 in.nextTag();
465             }
466
467             return;
468         }
469
470         if (parent instanceof AnydataNodeDataWithSchema anydata) {
471             anydata.setObjectModel(DOMSourceAnydata.class);
472             anydata.setAttributes(getElementAttributes(in));
473             setValue(anydata, readAnyXmlValue(in), in.getNamespaceContext());
474             if (isNextEndDocument(in)) {
475                 return;
476             }
477
478             if (!isAtElement(in)) {
479                 in.nextTag();
480             }
481
482             return;
483         }
484
485         switch (in.nextTag()) {
486             case XMLStreamConstants.START_ELEMENT:
487                 // FIXME: 7.0.0: why do we even need this tracker? either document it or remove it.
488                 //               it looks like it is a crude duplicate finder, which should really be handled via
489                 //               ChildReusePolicy.REJECT
490                 final var namesakes = new HashSet<Entry<String, String>>();
491                 while (in.hasNext()) {
492                     final String xmlElementName = in.getLocalName();
493                     final DataSchemaNode parentSchema = parent.getSchema();
494
495                     final String parentSchemaName = parentSchema.getQName().getLocalName();
496                     if (parentSchemaName.equals(xmlElementName)
497                             && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
498                         if (isNextEndDocument(in)) {
499                             break;
500                         }
501
502                         if (!isAtElement(in)) {
503                             in.nextTag();
504                         }
505                         break;
506                     }
507
508                     if (in.isEndElement() && rootElement.equals(xmlElementName)) {
509                         break;
510                     }
511
512                     final String elementNS = in.getNamespaceURI();
513                     final boolean added = namesakes.add(new SimpleImmutableEntry<>(elementNS, xmlElementName));
514
515                     final XMLNamespace nsUri;
516                     try {
517                         nsUri = rawXmlNamespace(elementNS).getNamespace();
518                     } catch (IllegalArgumentException e) {
519                         throw new XMLStreamException("Failed to convert namespace " + xmlElementName, in.getLocation(),
520                             e);
521                     }
522
523                     final Deque<DataSchemaNode> childDataSchemaNodes =
524                             ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName, nsUri);
525                     if (!childDataSchemaNodes.isEmpty()) {
526                         final boolean elementList = isElementList(childDataSchemaNodes);
527                         if (!added && !elementList) {
528                             throw new XMLStreamException(String.format(
529                                 "Duplicate element \"%s\" in namespace \"%s\" with parent \"%s\" in XML input",
530                                 xmlElementName, elementNS, parentSchema), in.getLocation());
531                         }
532
533                         // We have a match, proceed with it
534                         final QName qname = childDataSchemaNodes.peekLast().getQName();
535                         final AbstractNodeDataWithSchema<?> child = ((CompositeNodeDataWithSchema<?>) parent).addChild(
536                             childDataSchemaNodes, elementList ? ChildReusePolicy.REUSE : ChildReusePolicy.NOOP);
537                         stack.enterDataTree(qname);
538                         read(in, child, rootElement);
539                         stack.exit();
540                         continue;
541                     }
542
543                     if (parent instanceof AbstractMountPointDataWithSchema<?> mountParent) {
544                         // Parent can potentially hold a mount point, let's see if there is a label present. We
545                         // explicitly unmask Optional to null so as to not to lead us on to functional programming,
546                         // because ...
547                         final MountPointSchemaNode mount;
548                         if (parentSchema instanceof ContainerSchemaNode container) {
549                             mount = MountPointSchemaNode.streamAll(container).findFirst().orElse(null);
550                         } else if (parentSchema instanceof ListSchemaNode list) {
551                             mount = MountPointSchemaNode.streamAll(list).findFirst().orElse(null);
552                         } else if (parentSchema instanceof ContainerLike) {
553                             mount = null;
554                         } else {
555                             throw new XMLStreamException("Unhandled mount-aware schema " + parentSchema,
556                                 in.getLocation());
557                         }
558
559                         if (mount != null) {
560                             final var label = mount.asEffectiveStatement().argument();
561                             LOG.debug("Assuming node {} and namespace {} belongs to mount point {}", xmlElementName,
562                                 nsUri, label);
563
564                             final var optFactory = codecs.mountPointContext().findMountPoint(label);
565                             if (optFactory.isPresent()) {
566                                 final var mountData = mountParent.getMountPointData(label, optFactory.orElseThrow());
567                                 addMountPointChild(mountData, nsUri, xmlElementName,
568                                     new DOMSource(readAnyXmlValue(in).getDocumentElement()));
569                                 // ... this call does not work with functional programming
570                                 continue;
571                             }
572
573                             LOG.debug("Mount point {} not attached", label);
574                         }
575                     }
576
577                     // We have not handled the node -- let's decide what to do about that
578                     if (strictParsing) {
579                         throw new XMLStreamException(String.format(
580                             "Schema for node with name %s and namespace %s does not exist in parent %s", xmlElementName,
581                             elementNS, parentSchema), in.getLocation());
582                     }
583
584                     LOG.debug("Skipping unknown node ns=\"{}\" localName=\"{}\" in parent {}", elementNS,
585                         xmlElementName, parentSchema);
586                     skipUnknownNode(in);
587                 }
588                 break;
589             case XMLStreamConstants.END_ELEMENT:
590                 if (isNextEndDocument(in)) {
591                     break;
592                 }
593
594                 if (!isAtElement(in)) {
595                     in.nextTag();
596                 }
597                 break;
598             default:
599                 break;
600         }
601     }
602
603     // Return true if schema represents a construct which uses multiple sibling elements to represent its content. The
604     // siblings MAY be interleaved as per RFC7950.
605     private static boolean isElementList(final Deque<DataSchemaNode> childDataSchemaNodes) {
606         final DataSchemaNode last = childDataSchemaNodes.getLast();
607         return last instanceof ListSchemaNode || last instanceof LeafListSchemaNode;
608     }
609
610     private static void addMountPointChild(final MountPointData mount, final XMLNamespace namespace,
611             final String localName, final DOMSource source) {
612         final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
613         if (YangConstants.YANG_LIBRARY_NAMESPACE.equals(namespace)) {
614             final var optName = ContainerName.forLocalName(localName);
615             if (optName != null) {
616                 mount.setContainer(optName, child);
617                 return;
618             }
619
620             LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
621         } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
622             mount.setSchemaMounts(child);
623             return;
624         }
625
626         mount.addChild(child);
627     }
628
629     private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
630         return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
631     }
632
633     private static boolean isAtElement(final XMLStreamReader in) {
634         return in.getEventType() == XMLStreamConstants.START_ELEMENT
635                 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
636     }
637
638     private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
639         // in case when the unknown node and at least one of its descendant nodes have the same name
640         // we cannot properly reach the end just by checking if the current node is an end element and has the same name
641         // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
642         int levelOfNesting = 0;
643         while (in.hasNext()) {
644             // in case there are text characters in an element, we cannot skip them by calling nextTag()
645             // therefore we skip them by calling next(), and then proceed to next element
646             in.next();
647             if (!isAtElement(in)) {
648                 in.nextTag();
649             }
650             if (in.isStartElement()) {
651                 levelOfNesting++;
652             }
653
654             if (in.isEndElement()) {
655                 if (levelOfNesting == 0) {
656                     break;
657                 }
658
659                 levelOfNesting--;
660             }
661         }
662
663         in.nextTag();
664     }
665
666     private void setValue(final SimpleNodeDataWithSchema<?> parent, final Object value,
667             final NamespaceContext nsContext) {
668         final DataSchemaNode schema = parent.getSchema();
669         final Object prev = parent.getValue();
670         checkArgument(prev == null, "Node '%s' has already set its value to '%s'", schema.getQName(), prev);
671         parent.setValue(translateValueByType(value, schema, nsContext));
672     }
673
674     private Object translateValueByType(final Object value, final DataSchemaNode node,
675             final NamespaceContext namespaceCtx) {
676         if (node instanceof AnyxmlSchemaNode) {
677             checkArgument(value instanceof Document);
678             /*
679              * FIXME: Figure out some YANG extension dispatch, which will reuse JSON parsing or XML parsing -
680              *        anyxml is not well-defined in JSON.
681              */
682             return new DOMSource(((Document) value).getDocumentElement());
683         } else if (node instanceof AnydataSchemaNode) {
684             checkArgument(value instanceof Document);
685             return new DOMSourceAnydata(new DOMSource(((Document) value).getDocumentElement()));
686         } else if (node instanceof TypedDataSchemaNode typedNode) {
687             checkArgument(value instanceof String);
688             return codecs.codecFor(typedNode, stack).parseValue(namespaceCtx, (String) value);
689         } else {
690             throw new IllegalStateException("Unhandled schema " + node);
691         }
692     }
693
694     private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
695         if (parent instanceof MultipleEntryDataWithSchema<?> multiEntry) {
696             return multiEntry.newChildEntry();
697         }
698         throw new VerifyException("Unexpected parent " + parent);
699     }
700
701     @Override
702     public void close() throws IOException {
703         writer.flush();
704         writer.close();
705     }
706
707     @Override
708     public void flush() throws IOException {
709         writer.flush();
710     }
711
712     private Optional<QNameModule> resolveXmlNamespace(final String xmlNamespace) {
713         return resolvedNamespaces.computeIfAbsent(xmlNamespace, nsUri -> {
714             final var it = codecs.getEffectiveModelContext().findModuleStatements(XMLNamespace.of(nsUri)).iterator();
715             return it.hasNext() ? Optional.of(it.next().localQNameModule()) : Optional.empty();
716         });
717     }
718
719     private QNameModule rawXmlNamespace(final String xmlNamespace) {
720         return rawNamespaces.computeIfAbsent(xmlNamespace, nsUri -> QNameModule.create(XMLNamespace.of(nsUri)));
721     }
722 }