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