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.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;
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.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.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;
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.
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.
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();
59 private final @NonNull StreamWriterFacade facade;
61 XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
62 facade = new StreamWriterFacade(writer);
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 new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
75 NormalizedNodeStreamWriterStack.of(context));
79 * Create a new writer with the specified context and rooted at the specified node.
81 * @param writer Output {@link XMLStreamWriter}
82 * @param inference root node inference
83 * @return A new {@link NormalizedNodeStreamWriter}
85 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
86 final EffectiveStatementInference inference) {
87 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, inference.getEffectiveModelContext(),
88 NormalizedNodeStreamWriterStack.of(inference));
92 * Create a new writer with the specified context and rooted in the specified schema path.
94 * @param writer Output {@link XMLStreamWriter}
95 * @param context Associated {@link EffectiveModelContext}.
97 * @return A new {@link NormalizedNodeStreamWriter}
99 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
100 final EffectiveModelContext context, final SchemaPath path) {
101 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
102 NormalizedNodeStreamWriterStack.of(context, path));
106 * Create a new writer with the specified context and rooted in the specified schema path.
108 * @param writer Output {@link XMLStreamWriter}
109 * @param context Associated {@link EffectiveModelContext}.
111 * @return A new {@link NormalizedNodeStreamWriter}
113 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
114 final EffectiveModelContext context, final Absolute path) {
115 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
116 NormalizedNodeStreamWriterStack.of(context, path));
120 * Create a new writer with the specified context and rooted in the specified operation's input.
122 * @param writer Output {@link XMLStreamWriter}
123 * @param context Associated {@link EffectiveModelContext}.
124 * @param operationPath Parent operation (RPC or action) path.
125 * @return A new {@link NormalizedNodeStreamWriter}
127 public static @NonNull NormalizedNodeStreamWriter forInputOf(final XMLStreamWriter writer,
128 final EffectiveModelContext context, final Absolute operationPath) {
129 return forOperation(writer, context, operationPath,
130 YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule()));
134 * Create a new writer with the specified context and rooted in the specified operation's output.
136 * @param writer Output {@link XMLStreamWriter}
137 * @param context Associated {@link EffectiveModelContext}.
138 * @param operationPath Parent operation (RPC or action) path.
139 * @return A new {@link NormalizedNodeStreamWriter}
141 public static @NonNull NormalizedNodeStreamWriter forOutputOf(final XMLStreamWriter writer,
142 final EffectiveModelContext context, final Absolute operationPath) {
143 return forOperation(writer, context, operationPath,
144 YangConstants.operationOutputQName(operationPath.lastNodeIdentifier().getModule()));
147 private static @NonNull NormalizedNodeStreamWriter forOperation(final XMLStreamWriter writer,
148 final EffectiveModelContext context, final Absolute operationPath, final QName qname) {
149 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context,
150 NormalizedNodeStreamWriterStack.ofOperation(context, operationPath, qname));
154 * Create a new schema-less writer. Note that this version is intended for debugging
155 * where doesn't have a SchemaContext available and isn't meant for production use.
157 * @param writer Output {@link XMLStreamWriter}
159 * @return A new {@link NormalizedNodeStreamWriter}
161 public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
162 return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
166 public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
167 return ImmutableClassToInstanceMap.of(StreamWriterMetadataExtension.class, this);
170 abstract void startAnydata(NodeIdentifier name);
172 abstract void startList(NodeIdentifier name);
174 abstract void startListItem(PathArgument name) throws IOException;
176 abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value)
177 throws XMLStreamException;
179 abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
180 throws XMLStreamException;
182 final void writeValue(final @NonNull Object value, final T context) throws IOException {
184 facade.writeCharacters(encodeValue(facade, value, context));
185 } catch (XMLStreamException e) {
186 throw new IOException("Failed to write value", e);
190 final void startElement(final QName qname) throws IOException {
192 facade.writeStartElement(qname);
193 } catch (XMLStreamException e) {
194 throw new IOException("Failed to start element", e);
198 final void endElement() throws IOException {
200 facade.writeEndElement();
201 } catch (XMLStreamException e) {
202 throw new IOException("Failed to end element", e);
206 final void anydataValue(final Object value) throws IOException {
207 if (value instanceof DOMSourceAnydata) {
209 facade.anydataWriteStreamReader(((DOMSourceAnydata) value).toStreamReader());
210 } catch (XMLStreamException e) {
211 throw new IOException("Unable to transform anydata value: " + value, e);
213 } else if (value instanceof NormalizedAnydata) {
215 facade.emitNormalizedAnydata((NormalizedAnydata) value);
216 } catch (XMLStreamException e) {
217 throw new IOException("Unable to emit anydata value: " + value, e);
220 throw new IllegalStateException("Unexpected anydata value " + value);
224 final void anyxmlValue(final DOMSource domSource) throws IOException {
225 if (domSource != null) {
226 final Node domNode = requireNonNull(domSource.getNode());
228 facade.anyxmlWriteStreamReader(new DOMSourceXMLStreamReader(domSource));
229 } catch (XMLStreamException e) {
230 throw new IOException("Unable to transform anyXml value: " + domNode, e);
236 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
241 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
243 startListItem(identifier);
247 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
252 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
257 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
262 public final void close() throws IOException {
265 } catch (XMLStreamException e) {
266 throw new IOException("Failed to close writer", e);
271 public final void flush() throws IOException {
274 } catch (XMLStreamException e) {
275 throw new IOException("Failed to flush writer", e);
280 public final void metadata(final ImmutableMap<QName, Object> attributes) throws IOException {
281 for (final Entry<QName, Object> entry : attributes.entrySet()) {
282 final QName qname = entry.getKey();
283 final String namespace = qname.getNamespace().toString();
284 final String localName = qname.getLocalName();
285 final Object value = entry.getValue();
287 // FIXME: remove this handling once we have complete mapping to metadata
289 if (namespace.isEmpty()) {
290 // Legacy attribute, which is expected to be a String
291 StreamWriterFacade.warnLegacyAttribute(localName);
292 if (!(value instanceof String)) {
293 if (BROKEN_ATTRIBUTES.add(localName)) {
294 LOG.warn("Unbound annotation {} does not have a String value, ignoring it. Please fix the "
295 + "source of this annotation either by formatting it to a String or removing its "
296 + "use", localName, new Throwable("Call stack"));
298 LOG.debug("Ignoring annotation {} value {}", localName, value);
300 facade.writeAttribute(localName, (String) value);
304 final String prefix = facade.getPrefix(qname.getNamespace(), namespace);
305 final String attrValue = encodeAnnotationValue(facade, qname, value);
306 facade.writeAttribute(prefix, namespace, localName, attrValue);
308 } catch (final XMLStreamException e) {
309 throw new IOException("Unable to emit attribute " + qname, e);
315 public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
316 if (DOMSourceAnydata.class.isAssignableFrom(objectModel)
317 || NormalizedAnydata.class.isAssignableFrom(objectModel)) {
319 startElement(name.getNodeType());