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