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