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