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