Rework NormalizedNodeStreamWriter
[yangtools.git] / yang / yang-data-codec-xml / src / main / java / org / opendaylight / yangtools / yang / data / codec / xml / XMLStreamNormalizedNodeStreamWriter.java
1 /*
2  * Copyright (c) 2014 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 java.util.Objects.requireNonNull;
12
13 import java.io.IOException;
14 import java.io.StringWriter;
15 import java.util.Map;
16 import javax.xml.stream.XMLStreamException;
17 import javax.xml.stream.XMLStreamWriter;
18 import javax.xml.transform.OutputKeys;
19 import javax.xml.transform.Transformer;
20 import javax.xml.transform.TransformerException;
21 import javax.xml.transform.TransformerFactory;
22 import javax.xml.transform.dom.DOMSource;
23 import javax.xml.transform.stream.StreamResult;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamAttributeWriter;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
31 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
35 import org.w3c.dom.Element;
36 import org.w3c.dom.Node;
37
38 /**
39  * A {@link NormalizedNodeStreamWriter} which translates the events into an {@link XMLStreamWriter},
40  * resulting in a RFC 6020 XML encoding. There are 2 versions of this class, one that takes a
41  * SchemaContext and encodes values appropriately according to the yang schema. The other is
42  * schema-less and merely outputs values using toString. The latter is intended for debugging
43  * where doesn't have a SchemaContext available and isn't meant for production use.
44  */
45 public abstract class XMLStreamNormalizedNodeStreamWriter<T> implements NormalizedNodeStreamAttributeWriter {
46     private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
47
48     private final @NonNull StreamWriterFacade facade;
49
50     XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
51         facade = new StreamWriterFacade(writer);
52     }
53
54     /**
55      * Create a new writer with the specified context as its root.
56      *
57      * @param writer Output {@link XMLStreamWriter}
58      * @param context Associated {@link SchemaContext}.
59      * @return A new {@link NormalizedNodeStreamWriter}
60      */
61     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
62             final SchemaContext context) {
63         return create(writer, context, context);
64     }
65
66     /**
67      * Create a new writer with the specified context and rooted at the specified node.
68      *
69      * @param writer Output {@link XMLStreamWriter}
70      * @param context Associated {@link SchemaContext}.
71      * @param rootNode Root node
72      * @return A new {@link NormalizedNodeStreamWriter}
73      */
74     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
75             final DataNodeContainer rootNode) {
76         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, SchemaTracker.create(rootNode));
77     }
78
79     /**
80      * Create a new writer with the specified context and rooted in the specified schema path.
81      *
82      * @param writer Output {@link XMLStreamWriter}
83      * @param context Associated {@link SchemaContext}.
84      * @param path path
85      * @return A new {@link NormalizedNodeStreamWriter}
86      */
87     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
88             final SchemaPath path) {
89         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, SchemaTracker.create(context, path));
90     }
91
92     /**
93      * Create a new schema-less writer. Note that this version is intended for debugging
94      * where doesn't have a SchemaContext available and isn't meant for production use.
95      *
96      * @param writer Output {@link XMLStreamWriter}
97      *
98      * @return A new {@link NormalizedNodeStreamWriter}
99      */
100     public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
101         return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
102     }
103
104     /**
105      * Utility method for formatting an {@link Element} to a string.
106      *
107      * @deprecated This method not used anywhere, users are advised to use their own formatting.
108      */
109     @Deprecated
110     public static String toString(final Element xml) {
111         try {
112             final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
113             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
114
115             final StreamResult result = new StreamResult(new StringWriter());
116             transformer.transform(new DOMSource(xml), result);
117
118             return result.getWriter().toString();
119         } catch (IllegalArgumentException | TransformerException e) {
120             throw new IllegalStateException("Unable to serialize xml element " + xml, e);
121         }
122     }
123
124     abstract void startList(NodeIdentifier name);
125
126     abstract void startListItem(PathArgument name) throws IOException;
127
128     abstract void writeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
129             throws XMLStreamException;
130
131     final void writeValue(final @NonNull Object value, final T context) throws IOException {
132         try {
133             writeValue(facade, value, context);
134         } catch (XMLStreamException e) {
135             throw new IOException("Failed to write value", e);
136         }
137     }
138
139     final void startElement(final QName qname) throws IOException {
140         try {
141             facade.writeStartElement(qname);
142         } catch (XMLStreamException e) {
143             throw new IOException("Failed to start element", e);
144         }
145     }
146
147     final void endElement() throws IOException {
148         try {
149             facade.writeEndElement();
150         } catch (XMLStreamException e) {
151             throw new IOException("Failed to end element", e);
152         }
153     }
154
155     final void anyxmlValue(final Object value) throws IOException {
156         if (value != null) {
157             checkArgument(value instanceof DOMSource, "AnyXML value must be DOMSource, not %s", value);
158             final DOMSource domSource = (DOMSource) value;
159             final Node domNode = requireNonNull(domSource.getNode());
160
161             try {
162                 facade.writeStreamReader(new DOMSourceXMLStreamReader(domSource));
163             } catch (XMLStreamException e) {
164                 throw new IOException("Unable to transform anyXml value: " + domNode, e);
165             }
166         }
167     }
168
169     @Override
170     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
171         startListItem(name);
172     }
173
174     @Override
175     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
176             throws IOException {
177         startListItem(identifier);
178     }
179
180     @Override
181     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
182         startList(name);
183     }
184
185     @Override
186     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
187         startList(name);
188     }
189
190     @Override
191     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
192         startList(name);
193     }
194
195     @Override
196     public final void close() throws IOException {
197         try {
198             facade.close();
199         } catch (XMLStreamException e) {
200             throw new IOException("Failed to close writer", e);
201         }
202     }
203
204     @Override
205     public final void flush() throws IOException {
206         try {
207             facade.flush();
208         } catch (XMLStreamException e) {
209             throw new IOException("Failed to flush writer", e);
210         }
211     }
212
213     @Override
214     public final void attributes(final Map<QName, String> attributes) throws IOException {
215         if (!attributes.isEmpty()) {
216             try {
217                 facade.writeAttributes(attributes);
218             } catch (final XMLStreamException e) {
219                 throw new IOException("Unable to emit attributes " + attributes, e);
220             }
221         }
222     }
223 }