Make model prefix handling optional
[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 XMLStreamWriter writer, final @Nullable PreferredPrefixes pref) {
62         facade = new StreamWriterFacade(writer, pref);
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 create(writer, context, false);
75     }
76
77     /**
78      * Create a new writer with the specified context as its root.
79      *
80      * @param writer Output {@link XMLStreamWriter}
81      * @param context Associated {@link EffectiveModelContext}.
82      * @param preferPrefixes prefer prefixes known to {@code context}
83      * @return A new {@link NormalizedNodeStreamWriter}
84      */
85     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
86             final EffectiveModelContext context, final boolean preferPrefixes) {
87         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
88             NormalizedNodeStreamWriterStack.of(context), preferPrefixes);
89     }
90
91     /**
92      * Create a new writer with the specified context and rooted at the specified node.
93      *
94      * @param writer Output {@link XMLStreamWriter}
95      * @param inference root node inference
96      * @return A new {@link NormalizedNodeStreamWriter}
97      */
98     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
99             final EffectiveStatementInference inference) {
100         return create(writer, inference, false);
101     }
102
103     /**
104      * Create a new writer with the specified context and rooted at the specified node.
105      *
106      * @param writer Output {@link XMLStreamWriter}
107      * @param inference root node inference
108      * @param preferPrefixes prefer prefixes known to {@code context}
109      * @return A new {@link NormalizedNodeStreamWriter}
110      */
111     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
112             final EffectiveStatementInference inference, final boolean preferPrefixes) {
113         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, inference.getEffectiveModelContext(),
114             NormalizedNodeStreamWriterStack.of(inference), preferPrefixes);
115     }
116
117     /**
118      * Create a new writer with the specified context and rooted in the specified schema path.
119      *
120      * @param writer Output {@link XMLStreamWriter}
121      * @param context Associated {@link EffectiveModelContext}.
122      * @param path path
123      * @return A new {@link NormalizedNodeStreamWriter}
124      */
125     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
126             final EffectiveModelContext context, final @Nullable Absolute path) {
127         return create(writer, context, path, false);
128     }
129
130     /**
131      * Create a new writer with the specified context and rooted in the specified schema path.
132      *
133      * @param writer Output {@link XMLStreamWriter}
134      * @param context Associated {@link EffectiveModelContext}.
135      * @param path path
136      * @param preferPrefixes prefer prefixes known to {@code context}
137      * @return A new {@link NormalizedNodeStreamWriter}
138      */
139     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
140             final EffectiveModelContext context, final @Nullable Absolute path, final boolean preferPrefixes) {
141         return path == null ? create(writer, context)
142             : new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
143                 NormalizedNodeStreamWriterStack.of(context, path), preferPrefixes);
144     }
145
146     /**
147      * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}.
148      *
149      * @param writer Output {@link XMLStreamWriter}
150      * @param context Associated {@link EffectiveModelContext}.
151      * @param path path
152      * @return A new {@link NormalizedNodeStreamWriter}
153      */
154     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
155             final EffectiveModelContext context, final YangInstanceIdentifier path) {
156         return create(writer, context, path, false);
157     }
158
159     /**
160      * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}.
161      *
162      * @param writer Output {@link XMLStreamWriter}
163      * @param context Associated {@link EffectiveModelContext}.
164      * @param path path
165      * @param preferPrefixes prefer prefixes known to {@code context}
166      * @return A new {@link NormalizedNodeStreamWriter}
167      */
168     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
169             final EffectiveModelContext context, final YangInstanceIdentifier path, final boolean preferPrefixes) {
170         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
171             NormalizedNodeStreamWriterStack.of(context, path), preferPrefixes);
172     }
173
174     /**
175      * Create a new writer with the specified context and rooted in the specified operation's input.
176      *
177      * @param writer Output {@link XMLStreamWriter}
178      * @param context Associated {@link EffectiveModelContext}.
179      * @param operationPath Parent operation (RPC or action) path.
180      * @return A new {@link NormalizedNodeStreamWriter}
181      */
182     public static @NonNull NormalizedNodeStreamWriter forInputOf(final XMLStreamWriter writer,
183             final EffectiveModelContext context, final Absolute operationPath) {
184         return forInputOf(writer, context, operationPath, false);
185     }
186
187     /**
188      * Create a new writer with the specified context and rooted in the specified operation's input.
189      *
190      * @param writer Output {@link XMLStreamWriter}
191      * @param context Associated {@link EffectiveModelContext}.
192      * @param operationPath Parent operation (RPC or action) path.
193      * @param preferPrefixes prefer prefixes known to {@code context}
194      * @return A new {@link NormalizedNodeStreamWriter}
195      */
196     public static @NonNull NormalizedNodeStreamWriter forInputOf(final XMLStreamWriter writer,
197             final EffectiveModelContext context, final Absolute operationPath, final boolean preferPrefixes) {
198         return forOperation(writer, context, operationPath,
199             YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule()), preferPrefixes);
200     }
201
202     /**
203      * Create a new writer with the specified context and rooted in the specified operation's output.
204      *
205      * @param writer Output {@link XMLStreamWriter}
206      * @param context Associated {@link EffectiveModelContext}.
207      * @param operationPath Parent operation (RPC or action) path.
208      * @return A new {@link NormalizedNodeStreamWriter}
209      */
210     public static @NonNull NormalizedNodeStreamWriter forOutputOf(final XMLStreamWriter writer,
211             final EffectiveModelContext context, final Absolute operationPath) {
212         return forOutputOf(writer, context, operationPath, false);
213     }
214
215     /**
216      * Create a new writer with the specified context and rooted in the specified operation's output.
217      *
218      * @param writer Output {@link XMLStreamWriter}
219      * @param context Associated {@link EffectiveModelContext}.
220      * @param operationPath Parent operation (RPC or action) path.
221      * @param preferPrefixes prefer prefixes known to {@code context}
222      * @return A new {@link NormalizedNodeStreamWriter}
223      */
224     public static @NonNull NormalizedNodeStreamWriter forOutputOf(final XMLStreamWriter writer,
225             final EffectiveModelContext context, final Absolute operationPath, final boolean preferPrefixes) {
226         return forOperation(writer, context, operationPath,
227             YangConstants.operationOutputQName(operationPath.lastNodeIdentifier().getModule()),
228             preferPrefixes);
229     }
230
231     private static @NonNull NormalizedNodeStreamWriter forOperation(final XMLStreamWriter writer,
232             final EffectiveModelContext context, final Absolute operationPath, final QName qname,
233             final boolean preferPrefixes) {
234         return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
235             NormalizedNodeStreamWriterStack.ofOperation(context, operationPath, qname), preferPrefixes);
236     }
237
238     /**
239      * Create a new schema-less writer. Note that this version is intended for debugging
240      * where doesn't have a SchemaContext available and isn't meant for production use.
241      *
242      * @param writer Output {@link XMLStreamWriter}
243      *
244      * @return A new {@link NormalizedNodeStreamWriter}
245      */
246     public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
247         return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
248     }
249
250     @Override
251     public final List<MetadataExtension> supportedExtensions() {
252         return List.of(this);
253     }
254
255     abstract void startAnydata(NodeIdentifier name);
256
257     abstract void startList(NodeIdentifier name);
258
259     abstract void startListItem(PathArgument name) throws IOException;
260
261     abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value)
262             throws XMLStreamException;
263
264     abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
265             throws XMLStreamException;
266
267     final void writeValue(final @NonNull Object value, final T context) throws IOException {
268         try {
269             facade.writeCharacters(encodeValue(facade, value, context));
270         } catch (XMLStreamException e) {
271             throw new IOException("Failed to write value", e);
272         }
273     }
274
275     final void startElement(final QName qname) throws IOException {
276         try {
277             facade.writeStartElement(qname);
278         } catch (XMLStreamException e) {
279             throw new IOException("Failed to start element", e);
280         }
281     }
282
283     final void endElement() throws IOException {
284         try {
285             facade.writeEndElement();
286         } catch (XMLStreamException e) {
287             throw new IOException("Failed to end element", e);
288         }
289     }
290
291     final void anydataValue(final Object value) throws IOException {
292         if (value instanceof DOMSourceAnydata) {
293             try {
294                 facade.anydataWriteStreamReader(((DOMSourceAnydata) value).toStreamReader());
295             } catch (XMLStreamException e) {
296                 throw new IOException("Unable to transform anydata value: " + value, e);
297             }
298         } else if (value instanceof NormalizedAnydata) {
299             try {
300                 facade.emitNormalizedAnydata((NormalizedAnydata) value);
301             } catch (XMLStreamException e) {
302                 throw new IOException("Unable to emit anydata value: " + value, e);
303             }
304         } else {
305             throw new IllegalStateException("Unexpected anydata value " + value);
306         }
307     }
308
309     final void anyxmlValue(final DOMSource domSource) throws IOException {
310         if (domSource != null) {
311             final Node domNode = requireNonNull(domSource.getNode());
312             try {
313                 facade.anyxmlWriteStreamReader(new DOMSourceXMLStreamReader(domSource));
314             } catch (XMLStreamException e) {
315                 throw new IOException("Unable to transform anyXml value: " + domNode, e);
316             }
317         }
318     }
319
320     @Override
321     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
322         startListItem(name);
323     }
324
325     @Override
326     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
327             throws IOException {
328         startListItem(identifier);
329     }
330
331     @Override
332     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
333         startList(name);
334     }
335
336     @Override
337     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
338         startList(name);
339     }
340
341     @Override
342     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
343         startList(name);
344     }
345
346     @Override
347     public final void close() throws IOException {
348         try {
349             facade.close();
350         } catch (XMLStreamException e) {
351             throw new IOException("Failed to close writer", e);
352         }
353     }
354
355     @Override
356     public final void flush() throws IOException {
357         try {
358             facade.flush();
359         } catch (XMLStreamException e) {
360             throw new IOException("Failed to flush writer", e);
361         }
362     }
363
364     @Override
365     public final void metadata(final ImmutableMap<QName, Object> attributes) throws IOException {
366         for (final Entry<QName, Object> entry : attributes.entrySet()) {
367             final QName qname = entry.getKey();
368             final String namespace = qname.getNamespace().toString();
369             final String localName = qname.getLocalName();
370             final Object value = entry.getValue();
371
372             // FIXME: remove this handling once we have complete mapping to metadata
373             try {
374                 if (namespace.isEmpty()) {
375                     // Legacy attribute, which is expected to be a String
376                     StreamWriterFacade.warnLegacyAttribute(localName);
377                     if (!(value instanceof String)) {
378                         if (BROKEN_ATTRIBUTES.add(localName)) {
379                             LOG.warn("""
380                                 Unbound annotation {} does not have a String value, ignoring it. Please fix the \
381                                 source of this annotation either by formatting it to a String or removing its \
382                                 use""", localName, new Throwable("Call stack"));
383                         }
384                         LOG.debug("Ignoring annotation {} value {}", localName, value);
385                     } else {
386                         facade.writeAttribute(localName, (String) value);
387                         continue;
388                     }
389                 } else {
390                     final String prefix = facade.getPrefix(qname.getNamespace(), namespace);
391                     final String attrValue = encodeAnnotationValue(facade, qname, value);
392                     facade.writeAttribute(prefix, namespace, localName, attrValue);
393                 }
394             } catch (final XMLStreamException e) {
395                 throw new IOException("Unable to emit attribute " + qname, e);
396             }
397         }
398     }
399
400     @Override
401     public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
402         if (DOMSourceAnydata.class.isAssignableFrom(objectModel)
403                 || NormalizedAnydata.class.isAssignableFrom(objectModel)) {
404             startAnydata(name);
405             startElement(name.getNodeType());
406             return true;
407         }
408         return false;
409     }
410 }