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