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