Add convenience methods for XML codec
[yangtools.git] / codec / 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 java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.ClassToInstanceMap;
13 import com.google.common.collect.ImmutableClassToInstanceMap;
14 import com.google.common.collect.ImmutableMap;
15 import java.io.IOException;
16 import java.util.Map.Entry;
17 import java.util.Set;
18 import java.util.concurrent.ConcurrentHashMap;
19 import javax.xml.stream.XMLStreamException;
20 import javax.xml.stream.XMLStreamWriter;
21 import javax.xml.transform.dom.DOMSource;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.yangtools.rfc7952.data.api.StreamWriterMetadataExtension;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.common.YangConstants;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.NormalizedAnydata;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriterExtension;
33 import org.opendaylight.yangtools.yang.data.util.NormalizedNodeStreamWriterStack;
34 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
35 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
36 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
37 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.w3c.dom.Node;
41
42 /**
43  * A {@link NormalizedNodeStreamWriter} which translates the events into an {@link XMLStreamWriter}, resulting in an
44  * RFC6020 XML encoding. There are 2 versions of this class, one that takes a SchemaContext and encodes values
45  * appropriately according to the YANG schema. The other is schema-less and merely outputs values using toString. The
46  * latter is intended for debugging where doesn't have a SchemaContext available and isn't meant for production use.
47  *
48  * <p>
49  * Due to backwards compatibility reasons this writer recognizes RFC7952 metadata include keys QNames with empty URI
50  * (as exposed via {@link XmlParserStream#LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an
51  * unqualified XML attribute and their value can be assumed to be a String. Furthermore, this extends to qualified
52  * attributes, which uses the proper namespace, but will not bind to a proper module revision. This caveat will be
53  * removed in a future version.
54  */
55 public abstract class XMLStreamNormalizedNodeStreamWriter<T> implements NormalizedNodeStreamWriter,
56         StreamWriterMetadataExtension {
57     private static final Logger LOG = LoggerFactory.getLogger(XMLStreamNormalizedNodeStreamWriter.class);
58     private static final Set<String> BROKEN_ATTRIBUTES = ConcurrentHashMap.newKeySet();
59
60     private final @NonNull StreamWriterFacade facade;
61
62     XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
63         facade = new StreamWriterFacade(writer);
64     }
65
66     /**
67      * Create a new writer with the specified context as its root.
68      *
69      * @param writer Output {@link XMLStreamWriter}
70      * @param context Associated {@link EffectiveModelContext}.
71      * @return A new {@link NormalizedNodeStreamWriter}
72      */
73     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
74             final EffectiveModelContext context) {
75         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
76             NormalizedNodeStreamWriterStack.of(context));
77     }
78
79     /**
80      * Create a new writer with the specified context and rooted at the specified node.
81      *
82      * @param writer Output {@link XMLStreamWriter}
83      * @param inference root node inference
84      * @return A new {@link NormalizedNodeStreamWriter}
85      */
86     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
87             final EffectiveStatementInference inference) {
88         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, inference.getEffectiveModelContext(),
89             NormalizedNodeStreamWriterStack.of(inference));
90     }
91
92     /**
93      * Create a new writer with the specified context and rooted in the specified schema path.
94      *
95      * @param writer Output {@link XMLStreamWriter}
96      * @param context Associated {@link EffectiveModelContext}.
97      * @param path path
98      * @return A new {@link NormalizedNodeStreamWriter}
99      */
100     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
101             final EffectiveModelContext context, final SchemaPath path) {
102         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
103             NormalizedNodeStreamWriterStack.of(context, path));
104     }
105
106     /**
107      * Create a new writer with the specified context and rooted in the specified schema path.
108      *
109      * @param writer Output {@link XMLStreamWriter}
110      * @param context Associated {@link EffectiveModelContext}.
111      * @param path path
112      * @return A new {@link NormalizedNodeStreamWriter}
113      */
114     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
115             final EffectiveModelContext context, final Absolute path) {
116         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
117             NormalizedNodeStreamWriterStack.of(context, path));
118     }
119
120     /**
121      * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}.
122      *
123      * @param writer Output {@link XMLStreamWriter}
124      * @param context Associated {@link EffectiveModelContext}.
125      * @param path path
126      * @return A new {@link NormalizedNodeStreamWriter}
127      */
128     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
129             final EffectiveModelContext context, final YangInstanceIdentifier path) {
130         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
131             NormalizedNodeStreamWriterStack.of(context, path));
132     }
133
134     /**
135      * Create a new writer with the specified context and rooted in the specified operation's input.
136      *
137      * @param writer Output {@link XMLStreamWriter}
138      * @param context Associated {@link EffectiveModelContext}.
139      * @param operationPath Parent operation (RPC or action) path.
140      * @return A new {@link NormalizedNodeStreamWriter}
141      */
142     public static @NonNull NormalizedNodeStreamWriter forInputOf(final XMLStreamWriter writer,
143             final EffectiveModelContext context, final Absolute operationPath) {
144         return forOperation(writer, context, operationPath,
145             YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule()));
146     }
147
148     /**
149      * Create a new writer with the specified context and rooted in the specified operation's output.
150      *
151      * @param writer Output {@link XMLStreamWriter}
152      * @param context Associated {@link EffectiveModelContext}.
153      * @param operationPath Parent operation (RPC or action) path.
154      * @return A new {@link NormalizedNodeStreamWriter}
155      */
156     public static @NonNull NormalizedNodeStreamWriter forOutputOf(final XMLStreamWriter writer,
157             final EffectiveModelContext context, final Absolute operationPath) {
158         return forOperation(writer, context, operationPath,
159             YangConstants.operationOutputQName(operationPath.lastNodeIdentifier().getModule()));
160     }
161
162     private static @NonNull NormalizedNodeStreamWriter forOperation(final XMLStreamWriter writer,
163             final EffectiveModelContext context, final Absolute operationPath, final QName qname) {
164         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
165             NormalizedNodeStreamWriterStack.ofOperation(context, operationPath, qname));
166     }
167
168     /**
169      * Create a new schema-less writer. Note that this version is intended for debugging
170      * where doesn't have a SchemaContext available and isn't meant for production use.
171      *
172      * @param writer Output {@link XMLStreamWriter}
173      *
174      * @return A new {@link NormalizedNodeStreamWriter}
175      */
176     public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
177         return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
178     }
179
180     @Override
181     public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
182         return ImmutableClassToInstanceMap.of(StreamWriterMetadataExtension.class, this);
183     }
184
185     abstract void startAnydata(NodeIdentifier name);
186
187     abstract void startList(NodeIdentifier name);
188
189     abstract void startListItem(PathArgument name) throws IOException;
190
191     abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value)
192             throws XMLStreamException;
193
194     abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
195             throws XMLStreamException;
196
197     final void writeValue(final @NonNull Object value, final T context) throws IOException {
198         try {
199             facade.writeCharacters(encodeValue(facade, value, context));
200         } catch (XMLStreamException e) {
201             throw new IOException("Failed to write value", e);
202         }
203     }
204
205     final void startElement(final QName qname) throws IOException {
206         try {
207             facade.writeStartElement(qname);
208         } catch (XMLStreamException e) {
209             throw new IOException("Failed to start element", e);
210         }
211     }
212
213     final void endElement() throws IOException {
214         try {
215             facade.writeEndElement();
216         } catch (XMLStreamException e) {
217             throw new IOException("Failed to end element", e);
218         }
219     }
220
221     final void anydataValue(final Object value) throws IOException {
222         if (value instanceof DOMSourceAnydata) {
223             try {
224                 facade.anydataWriteStreamReader(((DOMSourceAnydata) value).toStreamReader());
225             } catch (XMLStreamException e) {
226                 throw new IOException("Unable to transform anydata value: " + value, e);
227             }
228         } else if (value instanceof NormalizedAnydata) {
229             try {
230                 facade.emitNormalizedAnydata((NormalizedAnydata) value);
231             } catch (XMLStreamException e) {
232                 throw new IOException("Unable to emit anydata value: " + value, e);
233             }
234         } else {
235             throw new IllegalStateException("Unexpected anydata value " + value);
236         }
237     }
238
239     final void anyxmlValue(final DOMSource domSource) throws IOException {
240         if (domSource != null) {
241             final Node domNode = requireNonNull(domSource.getNode());
242             try {
243                 facade.anyxmlWriteStreamReader(new DOMSourceXMLStreamReader(domSource));
244             } catch (XMLStreamException e) {
245                 throw new IOException("Unable to transform anyXml value: " + domNode, e);
246             }
247         }
248     }
249
250     @Override
251     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
252         startListItem(name);
253     }
254
255     @Override
256     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
257             throws IOException {
258         startListItem(identifier);
259     }
260
261     @Override
262     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
263         startList(name);
264     }
265
266     @Override
267     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
268         startList(name);
269     }
270
271     @Override
272     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
273         startList(name);
274     }
275
276     @Override
277     public final void close() throws IOException {
278         try {
279             facade.close();
280         } catch (XMLStreamException e) {
281             throw new IOException("Failed to close writer", e);
282         }
283     }
284
285     @Override
286     public final void flush() throws IOException {
287         try {
288             facade.flush();
289         } catch (XMLStreamException e) {
290             throw new IOException("Failed to flush writer", e);
291         }
292     }
293
294     @Override
295     public final void metadata(final ImmutableMap<QName, Object> attributes) throws IOException {
296         for (final Entry<QName, Object> entry : attributes.entrySet()) {
297             final QName qname = entry.getKey();
298             final String namespace = qname.getNamespace().toString();
299             final String localName = qname.getLocalName();
300             final Object value = entry.getValue();
301
302             // FIXME: remove this handling once we have complete mapping to metadata
303             try {
304                 if (namespace.isEmpty()) {
305                     // Legacy attribute, which is expected to be a String
306                     StreamWriterFacade.warnLegacyAttribute(localName);
307                     if (!(value instanceof String)) {
308                         if (BROKEN_ATTRIBUTES.add(localName)) {
309                             LOG.warn("Unbound annotation {} does not have a String value, ignoring it. Please fix the "
310                                     + "source of this annotation either by formatting it to a String or removing its "
311                                     + "use", localName, new Throwable("Call stack"));
312                         }
313                         LOG.debug("Ignoring annotation {} value {}", localName, value);
314                     } else {
315                         facade.writeAttribute(localName, (String) value);
316                         continue;
317                     }
318                 } else {
319                     final String prefix = facade.getPrefix(qname.getNamespace(), namespace);
320                     final String attrValue = encodeAnnotationValue(facade, qname, value);
321                     facade.writeAttribute(prefix, namespace, localName, attrValue);
322                 }
323             } catch (final XMLStreamException e) {
324                 throw new IOException("Unable to emit attribute " + qname, e);
325             }
326         }
327     }
328
329     @Override
330     public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
331         if (DOMSourceAnydata.class.isAssignableFrom(objectModel)
332                 || NormalizedAnydata.class.isAssignableFrom(objectModel)) {
333             startAnydata(name);
334             startElement(name.getNodeType());
335             return true;
336         }
337         return false;
338     }
339 }