Integrate rfc7952-data-api into yang-data-api
[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.eclipse.jdt.annotation.Nullable;
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.api.schema.stream.StreamWriterMetadataExtension;
34 import org.opendaylight.yangtools.yang.data.util.NormalizedNodeStreamWriterStack;
35 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
36 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
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 sealed class XMLStreamNormalizedNodeStreamWriter<T>
56         implements NormalizedNodeStreamWriter, StreamWriterMetadataExtension
57         permits SchemaAwareXMLStreamNormalizedNodeStreamWriter, SchemalessXMLStreamNormalizedNodeStreamWriter {
58     private static final Logger LOG = LoggerFactory.getLogger(XMLStreamNormalizedNodeStreamWriter.class);
59     private static final Set<String> BROKEN_ATTRIBUTES = ConcurrentHashMap.newKeySet();
60
61     private final @NonNull StreamWriterFacade facade;
62
63     XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
64         facade = new StreamWriterFacade(writer);
65     }
66
67     /**
68      * Create a new writer with the specified context as its root.
69      *
70      * @param writer Output {@link XMLStreamWriter}
71      * @param context Associated {@link EffectiveModelContext}.
72      * @return A new {@link NormalizedNodeStreamWriter}
73      */
74     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
75             final EffectiveModelContext context) {
76         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
77             NormalizedNodeStreamWriterStack.of(context));
78     }
79
80     /**
81      * Create a new writer with the specified context and rooted at the specified node.
82      *
83      * @param writer Output {@link XMLStreamWriter}
84      * @param inference root node inference
85      * @return A new {@link NormalizedNodeStreamWriter}
86      */
87     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
88             final EffectiveStatementInference inference) {
89         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, inference.getEffectiveModelContext(),
90             NormalizedNodeStreamWriterStack.of(inference));
91     }
92
93     /**
94      * Create a new writer with the specified context and rooted in the specified schema path.
95      *
96      * @param writer Output {@link XMLStreamWriter}
97      * @param context Associated {@link EffectiveModelContext}.
98      * @param path path
99      * @return A new {@link NormalizedNodeStreamWriter}
100      */
101     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
102             final EffectiveModelContext context, final @Nullable Absolute path) {
103         return path == null ? create(writer, context)
104             : new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
105                 NormalizedNodeStreamWriterStack.of(context, path));
106     }
107
108     /**
109      * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}.
110      *
111      * @param writer Output {@link XMLStreamWriter}
112      * @param context Associated {@link EffectiveModelContext}.
113      * @param path path
114      * @return A new {@link NormalizedNodeStreamWriter}
115      */
116     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
117             final EffectiveModelContext context, final YangInstanceIdentifier path) {
118         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
119             NormalizedNodeStreamWriterStack.of(context, path));
120     }
121
122     /**
123      * Create a new writer with the specified context and rooted in the specified operation's input.
124      *
125      * @param writer Output {@link XMLStreamWriter}
126      * @param context Associated {@link EffectiveModelContext}.
127      * @param operationPath Parent operation (RPC or action) path.
128      * @return A new {@link NormalizedNodeStreamWriter}
129      */
130     public static @NonNull NormalizedNodeStreamWriter forInputOf(final XMLStreamWriter writer,
131             final EffectiveModelContext context, final Absolute operationPath) {
132         return forOperation(writer, context, operationPath,
133             YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule()));
134     }
135
136     /**
137      * Create a new writer with the specified context and rooted in the specified operation's output.
138      *
139      * @param writer Output {@link XMLStreamWriter}
140      * @param context Associated {@link EffectiveModelContext}.
141      * @param operationPath Parent operation (RPC or action) path.
142      * @return A new {@link NormalizedNodeStreamWriter}
143      */
144     public static @NonNull NormalizedNodeStreamWriter forOutputOf(final XMLStreamWriter writer,
145             final EffectiveModelContext context, final Absolute operationPath) {
146         return forOperation(writer, context, operationPath,
147             YangConstants.operationOutputQName(operationPath.lastNodeIdentifier().getModule()));
148     }
149
150     private static @NonNull NormalizedNodeStreamWriter forOperation(final XMLStreamWriter writer,
151             final EffectiveModelContext context, final Absolute operationPath, final QName qname) {
152         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
153             NormalizedNodeStreamWriterStack.ofOperation(context, operationPath, qname));
154     }
155
156     /**
157      * Create a new schema-less writer. Note that this version is intended for debugging
158      * where doesn't have a SchemaContext available and isn't meant for production use.
159      *
160      * @param writer Output {@link XMLStreamWriter}
161      *
162      * @return A new {@link NormalizedNodeStreamWriter}
163      */
164     public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
165         return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
166     }
167
168     @Override
169     public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
170         return ImmutableClassToInstanceMap.of(StreamWriterMetadataExtension.class, this);
171     }
172
173     abstract void startAnydata(NodeIdentifier name);
174
175     abstract void startList(NodeIdentifier name);
176
177     abstract void startListItem(PathArgument name) throws IOException;
178
179     abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value)
180             throws XMLStreamException;
181
182     abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
183             throws XMLStreamException;
184
185     final void writeValue(final @NonNull Object value, final T context) throws IOException {
186         try {
187             facade.writeCharacters(encodeValue(facade, value, context));
188         } catch (XMLStreamException e) {
189             throw new IOException("Failed to write value", e);
190         }
191     }
192
193     final void startElement(final QName qname) throws IOException {
194         try {
195             facade.writeStartElement(qname);
196         } catch (XMLStreamException e) {
197             throw new IOException("Failed to start element", e);
198         }
199     }
200
201     final void endElement() throws IOException {
202         try {
203             facade.writeEndElement();
204         } catch (XMLStreamException e) {
205             throw new IOException("Failed to end element", e);
206         }
207     }
208
209     final void anydataValue(final Object value) throws IOException {
210         if (value instanceof DOMSourceAnydata) {
211             try {
212                 facade.anydataWriteStreamReader(((DOMSourceAnydata) value).toStreamReader());
213             } catch (XMLStreamException e) {
214                 throw new IOException("Unable to transform anydata value: " + value, e);
215             }
216         } else if (value instanceof NormalizedAnydata) {
217             try {
218                 facade.emitNormalizedAnydata((NormalizedAnydata) value);
219             } catch (XMLStreamException e) {
220                 throw new IOException("Unable to emit anydata value: " + value, e);
221             }
222         } else {
223             throw new IllegalStateException("Unexpected anydata value " + value);
224         }
225     }
226
227     final void anyxmlValue(final DOMSource domSource) throws IOException {
228         if (domSource != null) {
229             final Node domNode = requireNonNull(domSource.getNode());
230             try {
231                 facade.anyxmlWriteStreamReader(new DOMSourceXMLStreamReader(domSource));
232             } catch (XMLStreamException e) {
233                 throw new IOException("Unable to transform anyXml value: " + domNode, e);
234             }
235         }
236     }
237
238     @Override
239     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
240         startListItem(name);
241     }
242
243     @Override
244     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
245             throws IOException {
246         startListItem(identifier);
247     }
248
249     @Override
250     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
251         startList(name);
252     }
253
254     @Override
255     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
256         startList(name);
257     }
258
259     @Override
260     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
261         startList(name);
262     }
263
264     @Override
265     public final void close() throws IOException {
266         try {
267             facade.close();
268         } catch (XMLStreamException e) {
269             throw new IOException("Failed to close writer", e);
270         }
271     }
272
273     @Override
274     public final void flush() throws IOException {
275         try {
276             facade.flush();
277         } catch (XMLStreamException e) {
278             throw new IOException("Failed to flush writer", e);
279         }
280     }
281
282     @Override
283     public final void metadata(final ImmutableMap<QName, Object> attributes) throws IOException {
284         for (final Entry<QName, Object> entry : attributes.entrySet()) {
285             final QName qname = entry.getKey();
286             final String namespace = qname.getNamespace().toString();
287             final String localName = qname.getLocalName();
288             final Object value = entry.getValue();
289
290             // FIXME: remove this handling once we have complete mapping to metadata
291             try {
292                 if (namespace.isEmpty()) {
293                     // Legacy attribute, which is expected to be a String
294                     StreamWriterFacade.warnLegacyAttribute(localName);
295                     if (!(value instanceof String)) {
296                         if (BROKEN_ATTRIBUTES.add(localName)) {
297                             LOG.warn("Unbound annotation {} does not have a String value, ignoring it. Please fix the "
298                                     + "source of this annotation either by formatting it to a String or removing its "
299                                     + "use", localName, new Throwable("Call stack"));
300                         }
301                         LOG.debug("Ignoring annotation {} value {}", localName, value);
302                     } else {
303                         facade.writeAttribute(localName, (String) value);
304                         continue;
305                     }
306                 } else {
307                     final String prefix = facade.getPrefix(qname.getNamespace(), namespace);
308                     final String attrValue = encodeAnnotationValue(facade, qname, value);
309                     facade.writeAttribute(prefix, namespace, localName, attrValue);
310                 }
311             } catch (final XMLStreamException e) {
312                 throw new IOException("Unable to emit attribute " + qname, e);
313             }
314         }
315     }
316
317     @Override
318     public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
319         if (DOMSourceAnydata.class.isAssignableFrom(objectModel)
320                 || NormalizedAnydata.class.isAssignableFrom(objectModel)) {
321             startAnydata(name);
322             startElement(name.getNodeType());
323             return true;
324         }
325         return false;
326     }
327 }