4e7d88fde5a117b1fe7b17517beae14ff96d3e65
[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.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.data.util.YangModeledAnyXmlNodeDataWithSchema;
74 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
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.LeafListSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.Module;
82 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
83 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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(URI.create("")).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 SchemaContext}.
195      */
196     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
197             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 SchemaContext}.
205      */
206     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
207             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 ContainerSchemaNode) {
254                 nodeDataWithSchema = new ContainerNodeDataWithSchema((ContainerSchemaNode) parentNode);
255             } else if (parentNode instanceof ListSchemaNode) {
256                 nodeDataWithSchema = new ListNodeDataWithSchema((ListSchemaNode) parentNode);
257             } else if (parentNode instanceof YangModeledAnyxmlSchemaNode) {
258                 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyxmlSchemaNode) parentNode);
259             } else if (parentNode instanceof AnyxmlSchemaNode) {
260                 nodeDataWithSchema = new AnyXmlNodeDataWithSchema((AnyxmlSchemaNode) parentNode);
261             } else if (parentNode instanceof LeafSchemaNode) {
262                 nodeDataWithSchema = new LeafNodeDataWithSchema((LeafSchemaNode) parentNode);
263             } else if (parentNode instanceof LeafListSchemaNode) {
264                 nodeDataWithSchema = new LeafListNodeDataWithSchema((LeafListSchemaNode) parentNode);
265             } else if (parentNode instanceof AnydataSchemaNode) {
266                 nodeDataWithSchema = new AnydataNodeDataWithSchema((AnydataSchemaNode) parentNode);
267             } else {
268                 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
269             }
270
271             read(reader, nodeDataWithSchema, reader.getLocalName());
272             nodeDataWithSchema.write(writer);
273         }
274
275         return this;
276     }
277
278     /**
279      * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
280      * YANG-modeled data contained in the source.
281      *
282      * @param src
283      *              {@link DOMSource} to be traversed
284      * @return
285      *              instance of XmlParserStream
286      * @throws XMLStreamException
287      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
288      * @throws URISyntaxException
289      *              if the namespace URI of an XML element contains a syntax error
290      * @throws IOException
291      *              if an error occurs while parsing the value of an anyxml node
292      * @throws SAXException
293      *              if an error occurs while parsing the value of an anyxml node
294      */
295     @Beta
296     public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
297             SAXException {
298         return parse(new DOMSourceXMLStreamReader(src));
299     }
300
301     private ImmutableMap<QName, Object> getElementAttributes(final XMLStreamReader in) {
302         checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
303         final Map<QName, Object> attributes = new LinkedHashMap<>();
304
305         for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
306             final String attributeNS = in.getAttributeNamespace(attrIndex);
307
308             // Skip namespace definitions
309             if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
310                 continue;
311             }
312
313             final String localName = in.getAttributeLocalName(attrIndex);
314             final String attrValue = in.getAttributeValue(attrIndex);
315             if (Strings.isNullOrEmpty(attributeNS)) {
316                 StreamWriterFacade.warnLegacyAttribute(localName);
317                 attributes.put(QName.create(LEGACY_ATTRIBUTE_NAMESPACE, localName), attrValue);
318                 continue;
319             }
320
321             // Cross-relate attribute namespace to the module
322             final Optional<QNameModule> optModule = resolveXmlNamespace(attributeNS);
323             if (optModule.isPresent()) {
324                 final QName qname = QName.create(optModule.get(), localName);
325                 final Optional<AnnotationSchemaNode> optAnnotation = AnnotationSchemaNode.find(
326                     codecs.getSchemaContext(), qname);
327                 if (optAnnotation.isPresent()) {
328                     final AnnotationSchemaNode schema = optAnnotation.get();
329                     final Object value = codecs.codecFor(schema).parseValue(in.getNamespaceContext(), attrValue);
330                     attributes.put(schema.getQName(), value);
331                     continue;
332                 }
333
334                 LOG.debug("Annotation for {} not found, using legacy QName", qname);
335             }
336
337             attributes.put(QName.create(rawXmlNamespace(attributeNS), localName), attrValue);
338         }
339
340         return ImmutableMap.copyOf(attributes);
341     }
342
343     private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
344         // Underlying reader might return null when asked for version, however when such reader is plugged into
345         // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
346         final XMLStreamReader inWrapper;
347         if (in.getVersion() == null) {
348             inWrapper = new StreamReaderDelegate(in) {
349                 @Override
350                 public String getVersion() {
351                     final String ver = super.getVersion();
352                     return ver != null ? ver : XML_STANDARD_VERSION;
353                 }
354             };
355         } else {
356             inWrapper = in;
357         }
358
359         final DOMResult result = new DOMResult();
360         try {
361             TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
362         } catch (final TransformerException e) {
363             throw new XMLStreamException("Unable to read anyxml value", e);
364         }
365         return (Document) result.getNode();
366     }
367
368     private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
369             throws XMLStreamException {
370         if (!in.hasNext()) {
371             return;
372         }
373
374         if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
375             parent.setAttributes(getElementAttributes(in));
376             setValue((SimpleNodeDataWithSchema<?>) parent, in.getElementText().trim(), in.getNamespaceContext());
377             if (isNextEndDocument(in)) {
378                 return;
379             }
380
381             if (!isAtElement(in)) {
382                 in.nextTag();
383             }
384             return;
385         }
386
387         if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
388             parent.setAttributes(getElementAttributes(in));
389         }
390
391         if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
392             String xmlElementName = in.getLocalName();
393             while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
394                 read(in, newEntryNode(parent), rootElement);
395                 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
396                         || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
397                     break;
398                 }
399                 xmlElementName = in.getLocalName();
400             }
401
402             return;
403         }
404
405         if (parent instanceof AnyXmlNodeDataWithSchema) {
406             setValue((AnyXmlNodeDataWithSchema) parent, readAnyXmlValue(in), in.getNamespaceContext());
407             if (isNextEndDocument(in)) {
408                 return;
409             }
410
411             if (!isAtElement(in)) {
412                 in.nextTag();
413             }
414
415             return;
416         }
417
418         if (parent instanceof AnydataNodeDataWithSchema) {
419             final AnydataNodeDataWithSchema anydata = (AnydataNodeDataWithSchema) parent;
420             anydata.setObjectModel(DOMSourceAnydata.class);
421             anydata.setAttributes(getElementAttributes(in));
422             setValue(anydata, readAnyXmlValue(in), in.getNamespaceContext());
423             if (isNextEndDocument(in)) {
424                 return;
425             }
426
427             if (!isAtElement(in)) {
428                 in.nextTag();
429             }
430
431             return;
432         }
433
434         if (parent instanceof YangModeledAnyxmlSchemaNode) {
435             parent.setAttributes(getElementAttributes(in));
436         }
437
438         switch (in.nextTag()) {
439             case XMLStreamConstants.START_ELEMENT:
440                 // FIXME: why do we even need this tracker? either document it or remove it
441                 final Set<Entry<String, String>> namesakes = new HashSet<>();
442                 while (in.hasNext()) {
443                     final String xmlElementName = in.getLocalName();
444
445                     DataSchemaNode parentSchema = parent.getSchema();
446
447                     final String parentSchemaName = parentSchema.getQName().getLocalName();
448                     if (parentSchemaName.equals(xmlElementName)
449                             && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
450                         if (isNextEndDocument(in)) {
451                             break;
452                         }
453
454                         if (!isAtElement(in)) {
455                             in.nextTag();
456                         }
457                         break;
458                     }
459
460                     if (in.isEndElement() && rootElement.equals(xmlElementName)) {
461                         break;
462                     }
463
464                     if (parentSchema instanceof YangModeledAnyxmlSchemaNode) {
465                         parentSchema = ((YangModeledAnyxmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
466                     }
467
468                     final String elementNS = in.getNamespaceURI();
469                     if (!namesakes.add(new SimpleImmutableEntry<>(elementNS, xmlElementName))) {
470                         throw new XMLStreamException(String.format(
471                             "Duplicate namespace \"%s\" element \"%s\" in XML input", elementNS, xmlElementName),
472                             in.getLocation());
473                     }
474
475                     final URI nsUri;
476                     try {
477                         nsUri = rawXmlNamespace(elementNS).getNamespace();
478                     } catch (IllegalArgumentException e) {
479                         throw new XMLStreamException("Failed to convert namespace " + xmlElementName, in.getLocation(),
480                             e);
481                     }
482
483                     final Deque<DataSchemaNode> childDataSchemaNodes =
484                             ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName, nsUri);
485                     if (!childDataSchemaNodes.isEmpty()) {
486                         // We have a match, proceed with it
487                         read(in, ((CompositeNodeDataWithSchema<?>) parent).addChild(childDataSchemaNodes), rootElement);
488                         continue;
489                     }
490
491                     if (parent instanceof AbstractMountPointDataWithSchema) {
492                         // Parent can potentially hold a mount point, let's see if there is a label present
493                         final Optional<MountPointSchemaNode> optMount;
494                         if (parentSchema instanceof ContainerSchemaNode) {
495                             optMount = MountPointSchemaNode.streamAll((ContainerSchemaNode) parentSchema).findFirst();
496                         } else if (parentSchema instanceof ListSchemaNode) {
497                             optMount = MountPointSchemaNode.streamAll((ListSchemaNode) parentSchema).findFirst();
498                         } else {
499                             throw new XMLStreamException("Unhandled mount-aware schema " + parentSchema);
500                         }
501
502                         if (optMount.isPresent()) {
503                             final MountPointIdentifier mountId = MountPointIdentifier.of(optMount.get().getQName());
504                             LOG.debug("Assuming node {} and namespace {} belongs to mount point {}", xmlElementName,
505                                 nsUri, mountId);
506
507                             final Optional<MountPointContextFactory> optFactory = codecs.mountPointContext()
508                                     .findMountPoint(mountId);
509                             if (optFactory.isPresent()) {
510                                 final MountPointData mountData = ((AbstractMountPointDataWithSchema<?>) parent)
511                                         .getMountPointData(mountId, optFactory.get());
512                                 addMountPointChild(mountData, nsUri, xmlElementName,
513                                     new DOMSource(readAnyXmlValue(in).getDocumentElement()));
514                                 continue;
515                             }
516
517                             LOG.debug("Mount point {} not attached", mountId);
518                         }
519                     }
520
521                     // We have not handled the node -- let's decide what to do about that
522                     if (strictParsing) {
523                         throw new XMLStreamException(String.format(
524                             "Schema for node with name %s and namespace %s does not exist at %s", xmlElementName,
525                             elementNS, parentSchema.getPath(), in.getLocation()));
526                     }
527
528                     LOG.debug("Skipping unknown node ns=\"{}\" localName=\"{}\" at path {}", elementNS, xmlElementName,
529                         parentSchema.getPath());
530                     skipUnknownNode(in);
531                 }
532                 break;
533             case XMLStreamConstants.END_ELEMENT:
534                 if (isNextEndDocument(in)) {
535                     break;
536                 }
537
538                 if (!isAtElement(in)) {
539                     in.nextTag();
540                 }
541                 break;
542             default:
543                 break;
544         }
545     }
546
547     private static void addMountPointChild(final MountPointData mount, final URI namespace, final String localName,
548             final DOMSource source) {
549         final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
550         if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
551             final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
552             if (optName.isPresent()) {
553                 mount.setContainer(optName.get(), child);
554                 return;
555             }
556
557             LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
558         } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
559             mount.setSchemaMounts(child);
560             return;
561         }
562
563         mount.addChild(child);
564     }
565
566     private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
567         return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
568     }
569
570     private static boolean isAtElement(final XMLStreamReader in) {
571         return in.getEventType() == XMLStreamConstants.START_ELEMENT
572                 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
573     }
574
575     private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
576         // in case when the unknown node and at least one of its descendant nodes have the same name
577         // we cannot properly reach the end just by checking if the current node is an end element and has the same name
578         // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
579         int levelOfNesting = 0;
580         while (in.hasNext()) {
581             // in case there are text characters in an element, we cannot skip them by calling nextTag()
582             // therefore we skip them by calling next(), and then proceed to next element
583             in.next();
584             if (!isAtElement(in)) {
585                 in.nextTag();
586             }
587             if (in.isStartElement()) {
588                 levelOfNesting++;
589             }
590
591             if (in.isEndElement()) {
592                 if (levelOfNesting == 0) {
593                     break;
594                 }
595
596                 levelOfNesting--;
597             }
598         }
599
600         in.nextTag();
601     }
602
603     private void setValue(final SimpleNodeDataWithSchema<?> parent, final Object value,
604             final NamespaceContext nsContext) {
605         final DataSchemaNode schema = parent.getSchema();
606         final Object prev = parent.getValue();
607         checkArgument(prev == null, "Node '%s' has already set its value to '%s'", schema.getQName(), prev);
608         parent.setValue(translateValueByType(value, schema, nsContext));
609     }
610
611     private Object translateValueByType(final Object value, final DataSchemaNode node,
612             final NamespaceContext namespaceCtx) {
613         if (node instanceof AnyxmlSchemaNode) {
614             checkArgument(value instanceof Document);
615             /*
616              * FIXME: Figure out some YANG extension dispatch, which will reuse JSON parsing or XML parsing -
617              *        anyxml is not well-defined in JSON.
618              */
619             return new DOMSource(((Document) value).getDocumentElement());
620         }
621         if (node instanceof AnydataSchemaNode) {
622             checkArgument(value instanceof Document);
623             return new DOMSourceAnydata(new DOMSource(((Document) value).getDocumentElement()));
624         }
625
626         checkArgument(node instanceof TypedDataSchemaNode);
627         checkArgument(value instanceof String);
628         return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
629     }
630
631     private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
632         verify(parent instanceof MultipleEntryDataWithSchema, "Unexpected parent %s", parent);
633         return ((MultipleEntryDataWithSchema<?>) parent).newChildEntry();
634     }
635
636     @Override
637     public void close() throws IOException {
638         writer.flush();
639         writer.close();
640     }
641
642     @Override
643     public void flush() throws IOException {
644         writer.flush();
645     }
646
647     private Optional<QNameModule> resolveXmlNamespace(final String xmlNamespace) {
648         return resolvedNamespaces.computeIfAbsent(xmlNamespace, nsUri -> {
649             final Iterator<Module> it = codecs.getSchemaContext().findModules(URI.create(nsUri)).iterator();
650             return it.hasNext() ? Optional.of(it.next().getQNameModule()) : Optional.empty();
651         });
652     }
653
654     private QNameModule rawXmlNamespace(final String xmlNamespace) {
655         return rawNamespaces.computeIfAbsent(xmlNamespace, nsUri -> QNameModule.create(URI.create(nsUri)));
656     }
657 }