2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.codec.xml;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.collect.ImmutableMap;
13 import java.io.IOException;
14 import java.util.List;
15 import java.util.Map.Entry;
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;
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.
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.
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();
59 private final @NonNull StreamWriterFacade facade;
61 XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer, final @Nullable PreferredPrefixes pref) {
62 facade = new StreamWriterFacade(writer, pref);
66 * Create a new writer with the specified context as its root.
68 * @param writer Output {@link XMLStreamWriter}
69 * @param context Associated {@link EffectiveModelContext}.
70 * @return A new {@link NormalizedNodeStreamWriter}
72 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
73 final EffectiveModelContext context) {
74 return create(writer, context, false);
78 * Create a new writer with the specified context as its root.
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}
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);
92 * Create a new writer with the specified context and rooted at the specified node.
94 * @param writer Output {@link XMLStreamWriter}
95 * @param inference root node inference
96 * @return A new {@link NormalizedNodeStreamWriter}
98 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
99 final EffectiveStatementInference inference) {
100 return create(writer, inference, false);
104 * Create a new writer with the specified context and rooted at the specified node.
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}
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);
118 * Create a new writer with the specified context and rooted in the specified schema path.
120 * @param writer Output {@link XMLStreamWriter}
121 * @param context Associated {@link EffectiveModelContext}.
123 * @return A new {@link NormalizedNodeStreamWriter}
125 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
126 final EffectiveModelContext context, final @Nullable Absolute path) {
127 return create(writer, context, path, false);
131 * Create a new writer with the specified context and rooted in the specified schema path.
133 * @param writer Output {@link XMLStreamWriter}
134 * @param context Associated {@link EffectiveModelContext}.
136 * @param preferPrefixes prefer prefixes known to {@code context}
137 * @return A new {@link NormalizedNodeStreamWriter}
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);
147 * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}.
149 * @param writer Output {@link XMLStreamWriter}
150 * @param context Associated {@link EffectiveModelContext}.
152 * @return A new {@link NormalizedNodeStreamWriter}
154 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
155 final EffectiveModelContext context, final YangInstanceIdentifier path) {
156 return create(writer, context, path, false);
160 * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}.
162 * @param writer Output {@link XMLStreamWriter}
163 * @param context Associated {@link EffectiveModelContext}.
165 * @param preferPrefixes prefer prefixes known to {@code context}
166 * @return A new {@link NormalizedNodeStreamWriter}
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);
175 * Create a new writer with the specified context and rooted in the specified operation's input.
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}
182 public static @NonNull NormalizedNodeStreamWriter forInputOf(final XMLStreamWriter writer,
183 final EffectiveModelContext context, final Absolute operationPath) {
184 return forInputOf(writer, context, operationPath, false);
188 * Create a new writer with the specified context and rooted in the specified operation's input.
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}
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);
203 * Create a new writer with the specified context and rooted in the specified operation's output.
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}
210 public static @NonNull NormalizedNodeStreamWriter forOutputOf(final XMLStreamWriter writer,
211 final EffectiveModelContext context, final Absolute operationPath) {
212 return forOutputOf(writer, context, operationPath, false);
216 * Create a new writer with the specified context and rooted in the specified operation's output.
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}
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()),
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);
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.
242 * @param writer Output {@link XMLStreamWriter}
244 * @return A new {@link NormalizedNodeStreamWriter}
246 public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
247 return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
251 public final List<MetadataExtension> supportedExtensions() {
252 return List.of(this);
255 abstract void startAnydata(NodeIdentifier name);
257 abstract void startList(NodeIdentifier name);
259 abstract void startListItem(PathArgument name) throws IOException;
261 abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value)
262 throws XMLStreamException;
264 abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
265 throws XMLStreamException;
267 final void writeValue(final @NonNull Object value, final T context) throws IOException {
269 facade.writeCharacters(encodeValue(facade, value, context));
270 } catch (XMLStreamException e) {
271 throw new IOException("Failed to write value", e);
275 final void startElement(final QName qname) throws IOException {
277 facade.writeStartElement(qname);
278 } catch (XMLStreamException e) {
279 throw new IOException("Failed to start element", e);
283 final void endElement() throws IOException {
285 facade.writeEndElement();
286 } catch (XMLStreamException e) {
287 throw new IOException("Failed to end element", e);
291 final void anydataValue(final Object value) throws IOException {
292 if (value instanceof DOMSourceAnydata) {
294 facade.anydataWriteStreamReader(((DOMSourceAnydata) value).toStreamReader());
295 } catch (XMLStreamException e) {
296 throw new IOException("Unable to transform anydata value: " + value, e);
298 } else if (value instanceof NormalizedAnydata) {
300 facade.emitNormalizedAnydata((NormalizedAnydata) value);
301 } catch (XMLStreamException e) {
302 throw new IOException("Unable to emit anydata value: " + value, e);
305 throw new IllegalStateException("Unexpected anydata value " + value);
309 final void anyxmlValue(final DOMSource domSource) throws IOException {
310 if (domSource != null) {
311 final Node domNode = requireNonNull(domSource.getNode());
313 facade.anyxmlWriteStreamReader(new DOMSourceXMLStreamReader(domSource));
314 } catch (XMLStreamException e) {
315 throw new IOException("Unable to transform anyXml value: " + domNode, e);
321 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
326 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
328 startListItem(identifier);
332 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
337 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
342 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
347 public final void close() throws IOException {
350 } catch (XMLStreamException e) {
351 throw new IOException("Failed to close writer", e);
356 public final void flush() throws IOException {
359 } catch (XMLStreamException e) {
360 throw new IOException("Failed to flush writer", e);
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();
372 // FIXME: remove this handling once we have complete mapping to metadata
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)) {
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"));
384 LOG.debug("Ignoring annotation {} value {}", localName, value);
386 facade.writeAttribute(localName, (String) value);
390 final String prefix = facade.getPrefix(qname.getNamespace(), namespace);
391 final String attrValue = encodeAnnotationValue(facade, qname, value);
392 facade.writeAttribute(prefix, namespace, localName, attrValue);
394 } catch (final XMLStreamException e) {
395 throw new IOException("Unable to emit attribute " + qname, e);
401 public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
402 if (DOMSourceAnydata.class.isAssignableFrom(objectModel)
403 || NormalizedAnydata.class.isAssignableFrom(objectModel)) {
405 startElement(name.getNodeType());