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