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